<?php
if (!isset($_GET['file']) || $_GET['file'] == '') die();

$published = 'false';
if (isset($_GET['published']) && $_GET['published'] != '') $published = $_GET['published'];

$categoryID     = $published == 'true' ? 360002617418 : 360003000617;
$userSegment    = $published == 'true' ? null : 360000483097;
?>

<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="https://stuk.github.io/jszip/dist/jszip.js"></script>
<script type="text/javascript" src="https://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>

<div id="response"></div>

<script type="text/javascript">
    var zipName = '<?= $_GET['file'] ?>';
    var sections = {};
    var articles = {};
    var articlePromise = getArticles();

    articlePromise.then(function(articleResult) {
        var sectionPromise = getSections();

        sectionPromise.then(function(sectionResult) {
            readZip();
        });
    });

    async function readZip() {
        var dataUrl = 'https://www.archline.hu/maintenance/zendesk/datas/';

        await JSZipUtils.getBinaryContent(dataUrl + zipName, function(err, jsonDatas) {
            if (err) throw err;

            const promise = getZipFilesContent(jsonDatas);

            promise.then(function(jsonDatas) {
                var datas = {};

                for (var i = 0; i < jsonDatas.length; i++) {
                    if (jsonDatas[i]['file'] == 'details.xml') continue;

                    var name = '';

                    var jsonContent = JSON.parse(jsonDatas[i]['content']);
                    if (jsonContent.section !== undefined) name = jsonContent.section.name;
                    else name = jsonContent.article.title;

                    datas[name] = jsonContent;
                    datas[name]['fileName'] = jsonDatas[i]['file'];
                }

                $.each(datas, function(key, value) {
                    var articleID = '';
                    var parentSectionName = '';
                    var fileName = value.fileName.split(".json");
                    fileName = fileName[0].split('.');

                    if (fileName.length == 1) parentSectionName = fileName[0];
                    else parentSectionName = fileName[fileName.length - 2];

                    var section = sections[parentSectionName];
                    var parentSection = datas[parentSectionName];

                    if (section === undefined) insertSection(parentSection);
                    section = sections[parentSectionName];

                    if (value.section !== undefined) crcUpdate(zipName, value.fileName, sections[fileName].html_url);

                    if (value.article !== undefined) {
                        var articleName = value.article.title;

                        if (articles[articleName] === undefined) {
                            insertArticle(section.id, value);
                        } else {
                            articleID = articles[articleName].id;
                            var translation = {};
                            translation['translation'] = {};
                            translation.translation['title'] = value.article.title;
                            translation.translation['body'] = value.article.body;

                            updatetArticle(articles[articleName].id, translation, value.fileName, articles[articleName].html_url);
                        }
                    }
                });
            });
        });
    }

    async function getSections() {
        await $.ajax({
            url: 'https://help.archlinexp.com/api/v2/help_center/categories/<?= $categoryID ?>/sections.json?per_page=100',
            type: "GET",
            dataType: "json",
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {
                for (var i = 0; i < response.sections.length; i++) {
                    sections[response.sections[i].name] = response.sections[i];
                }
            }
        });
        return true;
    }

    async function getArticles() {
        await $.ajax({
            url: 'https://help.archlinexp.com/api/v2/help_center/categories/<?= $categoryID ?>/articles.json?per_page=100',
            type: "GET",
            dataType: "json",
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {
                for (var i = 0; i < response.articles.length; i++) {
                    articles[response.articles[i].name] = response.articles[i];
                }
            }
        });
        return true;
    }

    function insertArticle(sectionID, article) {
        $.ajax({
            url: 'https://help.archlinexp.com/api/v2/help_center/en-us/sections/' + sectionID + '/articles',
            type: "POST",
            dataType: "json",
            async: false,
            data: article,
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {
                updatePermissionGroup(response.article.id);
                crcUpdate(zipName, article.fileName, response.article.html_url);
                console.log(response);

                $('#response').append(response.article.title + '<br/>');
            }
        });
    }

    function updatetArticle(articleID, translation, jsonFile, htmlUrl) {
        var sectionID = '';

        $.ajax({
            url: 'https://help.archlinexp.com/api/v2/help_center/articles/' + articleID + '/translations/en-us',
            type: "PUT",
            dataType: "json",
            async: false,
            data: translation,
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {
                crcUpdate(zipName, jsonFile, htmlUrl);
                console.log(response);

                updatePermissionGroup(articleID);
                $('#response').append(response.article.title + '<br/>');
            }
        });
    }

    function updatePermissionGroup(articleID) {
        var permissionGroup = '';

        <?php if ($userSegment == null) : ?>
            permissionGroup = null;
        <?php else : ?>
            permissionGroup = '<?= $userSegment ?>';
        <?php endif; ?>

        var permission = {};
        permission['article'] = {};
        permission.article['user_segment_id'] = permissionGroup;

        $.ajax({
            url: 'https://help.archlinexp.com/api/v2/help_center/articles/' + articleID,
            type: "PUT",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "false",
            data: JSON.stringify(permission),
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {}
        });
    }

    async function crcUpdate(file, jsonFile, htmlUrl) {
        await $.ajax({
            url: "https://www.archline.hu/maintenance/zendesk/update_crc.php",
            type: "POST",
            dataType: "json",
            data: {
                file: file,
                jsonFile: jsonFile,
                htmlUrl: htmlUrl,
                published: '<?= $published ?>'
            },
            success: function(response) {
                console.log(response);
            }
        });
    }

    function insertSection(section) {
        var url = 'https://help.archlinexp.com/api/v2/help_center/en-us/categories/<?= $categoryID ?>/sections';
        var sectionID = '';

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            async: false,
            data: section,
            beforeSend: function(xmlhttp) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer 7d9786dde6607b4f5939f0e54caa9f04155823ad3881255ef07a2c64675a42da');
            },
            success: function(response) {
                console.log(response);
                sections[response.section.name] = response.section;
                sectionID = response.section.id;

                $('#response').append(response.section.name + '<br/>');
            }
        });
    }

    async function getZipFilesContent(data) {
        const zipContent = [];
        const promises = [];
        const zip = await JSZip.loadAsync(data);
        zip.forEach(async (relativePath, file) => {
            const promise = file.async('string');
            promises.push(promise);
            zipContent.push({
                file: relativePath,
                content: await promise
            });
        });

        await Promise.all(promises);
        return zipContent;
    }
</script>