<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');
    require_once(ENGINE_DIR . '/mods/database_helper.php');

    class FileManager {
        public $rootDir = './';
        private $currentPath;
        private $db;

        public function __construct($db) {
            $this->db = $db;
            $this->rootDir = $_SERVER["DOCUMENT_ROOT"];
            $requestedPath = isset($_GET['path']) ? trim($_GET['path'], '/') : '';
            $this->currentPath = $this->rootDir . ($requestedPath ? '/' . $requestedPath : '');
        }

        public function getCurrentPath($relative = false) {
            // Возвращает относительный или полный путь
            return $relative
                ? (isset($_GET['path']) ? trim($_GET['path'], '/') : '')
                : $this->currentPath;
        }

        public function getParentPath() {
            $parentPath = dirname($this->currentPath);

            // Если текущая директория — корневая, возвращаем null
            if ($parentPath === $this->rootDir) {
                return null;
            }

            return $parentPath;
        }

        public function getFilesAndFolders($path = null) {
            $path = $path ?: $this->currentPath;

            if (!is_dir($path)) {
                return [];
            }

            $items = scandir($path);
            $result = [];

            foreach ($items as $item) {
                if ($item === '.' || $item === '..') continue;
                $fullPath = $path . '/' . $item;

                $extension = pathinfo($_SERVER["DOCUMENT_ROOT"] . "/" . $fullPath, PATHINFO_EXTENSION);
                if ($extension == "metadata") {
                    continue;
                }

                $result[] = [
                    'extension' => $extension,
                    'full_path' => $fullPath,
                    'name' => $item,
                    'is_dir' => is_dir($fullPath),
                    'normal_path' => str_replace($this->rootDir . "/", "", $fullPath) != "uploads"
                        ? str_replace($this->rootDir . "/", "", $fullPath)
                        : $item
                ];
            }
            return $result;
        }

        private function getFormattedPermissions($filePath) {
            $perms = fileperms($filePath);

            // Определяем тип файла
            switch ($perms & 0xF000) {
                case 0xC000: $type = 's'; break; // Сокет
                case 0xA000: $type = 'l'; break; // Символическая ссылка
                case 0x8000: $type = '-'; break; // Обычный файл
                case 0x6000: $type = 'b'; break; // Блочное устройство
                case 0x4000: $type = 'd'; break; // Каталог
                case 0x2000: $type = 'c'; break; // Символьное устройство
                case 0x1000: $type = 'p'; break; // Канал FIFO
                default:     $type = 'u'; break; // Неизвестный тип
            }

            // Права для владельца
            $owner = (($perms & 0x0100) ? 'r' : '-') .
                (($perms & 0x0080) ? 'w' : '-') .
                (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x') : (($perms & 0x0800) ? 'S' : '-'));

            // Права для группы
            $group = (($perms & 0x0020) ? 'r' : '-') .
                (($perms & 0x0010) ? 'w' : '-') .
                (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x') : (($perms & 0x0400) ? 'S' : '-'));

            // Права для остальных
            $others = (($perms & 0x0004) ? 'r' : '-') .
                (($perms & 0x0002) ? 'w' : '-') .
                (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x') : (($perms & 0x0200) ? 'T' : '-'));

            return $type . $owner . $group . $others;
        }

        public function createFolder($name) {
            $newDir = $this->currentPath . '/' . $name;
            if (!file_exists($newDir)) {
                mkdir($newDir);
            }
        }

        public function uploadFile($file) {
            move_uploaded_file($file['tmp_name'], $this->currentPath . '/' . $file['name']);
        }

        public function renameItem($oldName, $newName) {
            rename($this->currentPath . '/' . $oldName, $this->currentPath . '/' . $newName);
        }

        public function deleteItem($name) {
            $itemPath = $this->currentPath . '/' . $name;
            if (is_dir($itemPath)) {
                rmdir($itemPath);
            } else {
                unlink($itemPath);
            }
        }
    }

    $fileManager = new FileManager($db_connect);
    $templates = $fileManager->getFilesAndFolders($_SERVER["DOCUMENT_ROOT"]."/templates/email");

    $widgets = [];
    $widgets = $db_connect->select("payment_widgets", "*");
    $groups = [];
    foreach ($config["default_roles"] as $key => $value) {
        if ($key != "roles_from_confirm") {
            $groups[] = $key;
        }
    }

    foreach ($widgets as $key => &$widget) {
        $widget["uniq_id"] = $key+1;
        $widget["name"] = $db_connect->get("widgets_translations", "value", ["widget_id" => $widget["id"], "widget_type" => "payment_widget", "name" => "name", "lang_code" => $_SESSION["lang"] ?? $config['default_lang']]);
        if ($widget["template_name"] == "universal-payment") {
            $widget["include_copy"] = '{include file="templates/'.$config["skin"].'/widgets/payment_widget.tpl" uniqName="'.$widget["uniq_name"].'"}';
        } else {
            $widget["include_copy"] = '{include file="templates/'.$config["skin"].'/widgets/custom/payments-widgets/'.$widget["w_type"]."/".$widget["template_name"].'.tpl" customUniqName="'.$widget["uniq_name"].'" widgetData=$widgetData}';
        }
    }

    $availableLanguagesList = [];
    foreach ($available_languages as $available_language) {
        $availableLanguagesList[] = [
          "code" => $available_language,
          "name" => $available_language
        ];
    }

    $smarty->assign('langs', $availableLanguagesList);
    $smarty->assign("emailTemplates", $templates);
    $smarty->assign("widgets", $widgets);
    $smarty->assign("groups", $groups);
    $yourData = array('title' => $lang['nav']['payments'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['nav']['payments'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);