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

    define('SKILLSENERGY', true);
    define('ENGINE_DIR', $_SERVER['DOCUMENT_ROOT'] . '/engine');
    define('SYSTEM_DIR', $_SERVER['DOCUMENT_ROOT'] . '/system');
    define('TEMPLATES_DIR', $_SERVER['DOCUMENT_ROOT'] . '/templates');
    require_once 'Autoloader.php';
    require_once ENGINE_DIR . '/mods/exceptions_handler.php';

    try {
        // Загрузка конфигурации
        require_once(ENGINE_DIR . '/data/config.php');
        require_once(ENGINE_DIR . '/data/dbconfig.php');
        require_once(ENGINE_DIR . '/libs/Smarty.class.php');
        $smarty = new Smarty();
        global $db_connect;

        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 = new Smarty();
        if(session_status() == PHP_SESSION_NONE) {
            session_start();
        }

        if (empty($_SESSION["user_email"])) {
            $_SESSION["user_id"] = null;
        }

        require_once(ENGINE_DIR . '/mods/permission.php');

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

        date_default_timezone_set($config['default_timezone']);
        require_once(ENGINE_DIR . '/mods/php_mail.php');

        require_once(ENGINE_DIR . '/extensions/api-qr-code/api-qr-code.php');

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

            exit();
        }
        require_once(ENGINE_DIR . '/mods/language.php');
        require_once(ENGINE_DIR . '/mods/module_status_check.php');

        $user_authenticated = isset($_SESSION['user_id']) || isset($_COOKIE['user_id']) || (isset($_SESSION['user_authenticated']) && $_SESSION['user_authenticated']);
        $smarty->assign('user_authenticated', $user_authenticated ?? false);
        require_once ENGINE_DIR.'/mods/convert_user_balance.php';
        require_once ENGINE_DIR.'/tools/check_mobile.php';

        require_once(ENGINE_DIR . '/mods/check_user_auth.php');
        require_once(ENGINE_DIR . '/mods/check_payed_role.php');

        $smarty->assign('login', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/login.tpl'));
        $smarty->assign('user_email', $user['email'] ?? null);
        $smarty->assign('group_name', $user['group_name'] ?? null);
        $smarty->assign('config', $config ?? null);

        require_once ENGINE_DIR . '/mods/smarty_temp_tpl.php';

        if ($adsAvailable || $eventsAvailable || $productsAvailable) {
            require_once(ENGINE_DIR . '/mods/currency.php');
        }

        $smarty->assign("globalLangJson", json_encode($lang["chat"]));
        require_once(ENGINE_DIR . '/controllers/universal.php');
        require_once(ENGINE_DIR . '/router.php');



    } catch (Exception $e) {
        $errorMessage = sprintf(
            "[%s] %s in %s on line %d\nStack trace:\n%s\n\n",
            date("Y-m-d H:i:s"),
            $e->getMessage(),
            $e->getFile(),
            $e->getLine(),
            $e->getTraceAsString()
        );

        file_put_contents(__DIR__ . '/var/logs/error_log.txt', $errorMessage, FILE_APPEND);

        error_log($errorMessage);

        if (isset($smarty)) {
            $smarty->assign("error_message", $errorMessage);
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/blocks/error.tpl');
        } else {
            echo "Ошибка сервера. Попробуйте позже.";
        }

    }


