<?php

use Mnv\Core\Config;
use Mnv\Core\Filesystem\FileTree;

require_once '../../includes/overall.inc.php';
include('../../includes/admin-functions.inc.php');

$errors = array();
$messages = array();

if (request()->ajax()) {

    loadLanguage(Config::getValue('admin_language'));

    $action      = request()->get('action','');
    $root        = request()->get('root','');
    $path        = request()->get('dir','/');
    $file        = request()->get('file','');

    $fileTree = new FileTree($root);

    /** сохранение файла */
    if (!empty($action) && $action == "save") {

        $result = $fileTree->save($file)
            ? array('status' => 200, 'message' => lang('templates:messages:0'), 'type' => 'success')
            : array('status' => 403, 'message' => lang('templates:errors:1'), 'type' => 'error');

        response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
        exit();
    }

    /** чтение файла */
    else if (!empty($action) && $action == "load") {

        $script = "";

        $type    = $fileTree->extension($file['path']);
        $content = $fileTree->read($file);
        $content = htmlspecialchars($content);
        echo '<p class="p-2 mb-0">Редактирование файла: <b>' . $file['path'] . '</b></p>';
        if (!is_writable($fileTree->realPath . $file['path'])) {
            echo '<span class="text-danger">Невозможно создать временный файл шаблона</span>';
        }

if ($type == "tpl") {
$script = <<<HTML
<script>
    var editor = CodeMirror.fromTextArea(document.getElementById('file_text'), {
        mode: "htmlmixed", lineNumbers: true, dragDrop: false, indentUnit: 4, indentWithTabs: false,
        extraKeys: { "Tab": function(cm){ cm.replaceSelection("  " , "end"); } }
    });
</script>
HTML;
}

if ($type == "css") {
$script = <<<HTML
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('file_text'), {
            indentUnit: 4, lineNumbers: true, dragDrop: false, mode: "css"
        });
    </script>
HTML;
}

if ($type == "js") {
$script = <<<HTML
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('file_text'), {
            lineNumbers: true, matchBrackets: true, indentUnit: 4, dragDrop: false, mode: "javascript"
        });
    </script>
HTML;
}

echo <<<HTML
<div style="border-top: solid 1px #BBB;border-bottom: solid 1px #BBB;;width:100%;height:475px;">
<textarea style="width:100%;height:475px;" name="file_text" id="file_text" wrap="off">{$content}</textarea>
</div>
<div class="p-1"><button type="button" class="btn btn-sm btn-primary" onclick="updateFile('{$file['path']}')"><i class="ph-floppy-disk me-2"></i>Сохранить</button></div>
{$script}
HTML;

    }
    /** получение списка дерева папок и файлов */
    else {

        $resultList = $fileTree->all($path);
        echo $resultList;

    }
} else {

    die('Hacking attempt!');

}
