<?php

/* перебор файлов и папок */

function scanDirTree() {
    global $path, $_SESSION;

    $file = $path . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'filepath.' . $_SESSION['lng'] . '.php';
    $content = file_get_contents($file);
    $xml = simplexml_load_string($content);

    function generateArray($xml, $urlParts = [], $isOpen = false) {
        $result = [];
        foreach ($xml->children() as $child) {
            $item = [
                'name' => (string) $child->attributes()->name,
                'tag' => $child->getName(),
                'children' => generateArray($child, $urlParts, $isOpen),
                'isOpen' => false,

                'url' => (string) $child->attributes()->url,
                'title' => (string) $child->attributes()->title,
                'template' => (string) $child->attributes()->template,
                'PageMenu' => (string) $child->attributes()->PageMenu,
                'users' => (string) $child->attributes()->users,
                'group' => (string) $child->attributes()->group,

                'content' => (string)$child
            ];
    
            if (!empty($urlParts) && $urlParts[0] == $item['tag']) {
                array_shift($urlParts);
                if (empty($urlParts)) {
                    if ($item['tag'] !== 'index') {
                        $item['isOpen'] = true;
                    }
                }
            }
    
            $result[] = $item;
        }
        return $result;
    }
    
    $url = $_SERVER['REQUEST_URI'];
    $urlParts = array_filter(explode('/', trim($url, '/')));
    $urlParts = array_map(function($part) {
        return pathinfo($part, PATHINFO_FILENAME);  
    }, $urlParts);

    $result = generateArray($xml, $urlParts);

    return ['items' => $result];
}

/* сохронения древа */
function saveTree($params) {
    global $path, $_SESSION;

    $file = $path . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'filepath.' . ($_SESSION['lng'] ?? 'en') . '.php';

    if (!isset($params['data']) || !is_array($params['data'])) {
        return ['status' => 'error', 'message' => 'Invalid data'];
    }

    $treeData = $params['data'];
    $siteName = isset($treeData['sitename']) ? htmlspecialchars($treeData['sitename'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '';
    $slogan = isset($treeData['slogan']) ? htmlspecialchars($treeData['slogan'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '';

    $xmlContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".
    "<site>\n".
    "    <sitename>$siteName</sitename>\n".
    "    <slogan>$slogan</slogan>\n".
    buildXml($treeData['children'] ?? []).
    "</site>\n";

    $result = @file_put_contents($file, $xmlContent);

    if ($result === false) {
        return ['status' => 'error', 'message' => 'Failed to write file'];
    }

    if (!file_exists($file)) {
        return ['status' => 'error', 'message' => 'File does not exist after write'];
    }

    return ['status' => 'success', 'message' => 'File saved successfully'];
}

function buildXml($data, $level = 1) {
    $xml = "";
    foreach ($data as $item) {
        if (!isset($item['name']) || empty($item['name'])) continue;

        $tag = htmlspecialchars(trim(explode(' ', $item['name'])[0]), ENT_XML1 | ENT_QUOTES, 'UTF-8');
        $nameAttr = htmlspecialchars(trim($tag), ENT_XML1 | ENT_QUOTES, 'UTF-8');

        $attributes = [
            'url'      => isset($item['url']) ? htmlspecialchars($item['url'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '',
            'title'    => isset($item['title']) ? htmlspecialchars($item['title'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '',
            'name'     => $nameAttr,
            'template' => isset($item['template']) ? htmlspecialchars($item['template'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '',
            'PageMenu' => isset($item['PageMenu']) ? htmlspecialchars($item['PageMenu'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '',
            'users'    => isset($item['users']) ? htmlspecialchars($item['users'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : '',
            'group'    => isset($item['group']) ? htmlspecialchars($item['group'], ENT_XML1 | ENT_QUOTES, 'UTF-8') : ''
        ];

        $attrString = "";
        foreach ($attributes as $key => $value) {
            $attrString .= " $key='$value'";
        }

        $xml .= str_repeat("    ", $level) . "<$tag$attrString>\n";
        if (!empty($item['children'])) {
            $xml .= buildXml($item['children'], $level + 1);
        }
        $xml .= str_repeat("    ", $level) . "</$tag>\n";
    }
    return $xml;
}

/* текущий файл страницы */

function currentPageFile() {
    global $_SESSION, $path;
    return ['folders' => $folders];
}

/* текущий файл страницы */
function getFolderNames() {
    global $path;
    $folder = $path . DIRECTORY_SEPARATOR . $_POST['folder'];
    $folders = array();
    if ($folder && is_dir($folder)) {
        $files = scandir($folder);
        foreach ($files as $file) {
            if ($file != '.' && $file != '..' && is_dir($folder . DIRECTORY_SEPARATOR . $file)) {
                $folders[] = $file;
            }
        }
    }
    return ['folders' => $folders];
}

?>