<?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.                                                      *
        *****************************************************************************
    */

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    $start_time = microtime(true);

    define('ENGINE_DIR', $_SERVER['DOCUMENT_ROOT'] . '/engine');
    define('SYSTEM_DIR', $_SERVER['DOCUMENT_ROOT'] . '/system');
    define('TEMPLATES_DIR', $_SERVER['DOCUMENT_ROOT'] . '/templates');

    require_once(ENGINE_DIR . '/data/config.php');
    require_once(ENGINE_DIR . '/data/dbconfig.php');
    require_once(ENGINE_DIR . '/libs/Smarty.class.php');
    require_once 'Autoloader.php';
    require_once ENGINE_DIR . '/mods/exceptions_handler.php';

    try {

        require_once(ENGINE_DIR . '/mods/api_exchanges.php');
        $exchangeRates = json_decode(file_get_contents(ENGINE_DIR . '/data/exchange_rates.json'));
        $config["payment_info"]["currencies"] = (array)$exchangeRates->rates;

        // Создаем экземпляр Smarty
        $smarty = new Smarty();
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }

        $dispatcher = new EventDispatcher($config, $db_connect);
        require_once(ENGINE_DIR . '/mods/event_subscribers.php');

        // Устанавливаем временную зону
        date_default_timezone_set($config['default_timezone']);

        // Подключаем функционал заданий в админ панели
        require_once(SYSTEM_DIR . '/plugins/tasks.php');

        // Подключаем языковой пакет для административного интерфейса
        require_once(SYSTEM_DIR . '/plugins/language.php');

        // проверка статуса модулей
        require_once(ENGINE_DIR . '/mods/module_status_check.php');
        require_once ENGINE_DIR . '/mods/convert_user_balance.php';


        require_once(SYSTEM_DIR . '/plugins/php_mail.php');
        require_once(ENGINE_DIR . '/login.php'); // Включаем авторизацию

        if (!$config['cms_installed']) {
            $beforeInitData = $dispatcher->dispatch("index.beforeInit", []);
            $smarty->assign("config", $config);
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/blocks/wizard.tpl');

            exit();
        }

        $_SESSION["user_email"] = !empty($_SESSION['user_email']) ? $_SESSION['user_email'] : $_COOKIE["user_email"] ?? "";
        $user = $db_connect->get("users", "*", [
            "email" => $_SESSION['user_email']
        ]);

        $user['role_id'] = $db_connect->get("users_roles", "role_id", ["user_id" => $user['id']]);

        if ($user) {
            $role = $db_connect->get("roles", [
                "name"
            ], [
                "id" => $user['role_id'] ?? 0
            ]);

            $user['role_name'] = $role['name'] ?? 'Guest';
        }

        $userGroup = '';
        $userSubscription = "No subscription";
        $userGroup = $user['role_id'];

        if ($user) {

            $userBalanceInfo = getConvertedBalanceInfo();

            $user["balance"] = $userBalanceInfo["finalBalance"];

            $smarty->assign('user', $user);
            $smarty->assign('user_email', htmlspecialchars($user['email']));
            $smarty->assign('user_group_id', $user['role_id']);
            $smarty->assign('user_balance', $user['balance']);
            $smarty->assign('group_name', $db_connect->get("roles", "name", ["id" => $user["role_id"]]));
            $smarty->assign('currency', $userBalanceInfo["currentCurrency"]);
            foreach ($user as $key => $value) {
                $smarty->assign($key, $value);
            }

            $_SESSION['user_id'] = $user['id'];

            $userSubscription = $db_connect->get("user_subscriptions", "*", ["user_id" => $user['id']]);
            if (!empty($userSubscription)) {
                $userSubscription = $db_connect->get("subscriptions", "name", ["id" => $userSubscription['subscription_id']]);
            } else {
                $userSubscription = "No subscription";
            }

        }
        require_once(ENGINE_DIR . '/mods/user_rules.php');

        $action = isset($_GET['action']) ? $_GET['action'] : 'main';
        $dataFile = "system/sections/{$action}.php";

        if (file_exists($dataFile)) {
            include($dataFile);
        }

        $root_url = $_SERVER['DOCUMENT_ROOT'];
        $smarty->assign('root_url', $root_url);

        // Получаем текущий URL запроса
        $currentDir = $_SERVER['REQUEST_URI'];
        $currentDir = strtok($currentDir, '?');
        $smarty->assign('currentDir', $currentDir);

        // Импортируем глобальный функционал для всех разделов админ панели
        require_once(SYSTEM_DIR . '/general.php');
        require_once(ENGINE_DIR . '/mods/database_helper.php');

        $smarty->assign("globalLangJson", json_encode($lang["chat"]));

        $smarty->assign("userSubscription", $userSubscription);
        // Подключеие общего шаблона
        $smarty->assign($config);
        $smarty->assign('lang', $lang);
        $content = $smarty->fetch('file:system/content/' . $action . '.tpl');
        $smarty->assign('content', $content);
        $smarty->display('system/main.tpl');

        $end_time = microtime(true);
        $execution_time = $end_time - $start_time;

    } catch (Exception $e) {
        function displayError($message) {
            global $smarty, $config;
            $smarty->assign('error_message', $message);
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
        }
        displayError($e);

    }

