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

    // Загрузка конфигурации
    require_once(ENGINE_DIR . '/data/config.php');

    require_once(ENGINE_DIR . '/login.php'); // Включаем авторизацию
    require_once(ENGINE_DIR . '/controllers/registration/registration.php'); // Включаем регистрацию
    require_once(ENGINE_DIR . '/policy-terms-cookies.php'); // Включаем Политику•Условия•Cookies

    // Подключение глобально доступного поиска по всему сайту
    require_once(ENGINE_DIR . '/mods/search.php');

    // Подключение глобально доступной корзины
    require_once(ENGINE_DIR . '/mods/cartcount.php');

    // Подключение независимых контроллеров
    require_once(ENGINE_DIR . '/controllers/home.php');
    require_once(ENGINE_DIR . '/controllers/profile.php');
    require_once(ENGINE_DIR . '/payment/cart.php');
    require_once(ENGINE_DIR . '/payment/payment.php');
    require_once(ENGINE_DIR . '/payment/checkout.php');
    require_once(ENGINE_DIR . '/payment/systems/stripe/payment.php');
    require_once(ENGINE_DIR . '/payment/systems/coinbase/payment.php');
    require_once(ENGINE_DIR . '/payment/systems/balance/payment.php');
    require_once(ENGINE_DIR . '/controllers/my-wallet.php');
    require_once(ENGINE_DIR . '/controllers/payment-widget.php');
    require_once(ENGINE_DIR . '/controllers/check_promocode.php');
    require_once(ENGINE_DIR . '/controllers/widget-object-controller.php');
    require_once(ENGINE_DIR . '/controllers/referrer-controller.php');
    require_once(ENGINE_DIR . '/controllers/chat/personal-messages.php');
    require_once(ENGINE_DIR . '/controllers/add-objects.php');
    require_once(ENGINE_DIR . '/controllers/user-profile.php');
    require_once(ENGINE_DIR . '/controllers/chat/live-chat.php');
    require_once(ENGINE_DIR . '/controllers/notifications.php');
    require_once(ENGINE_DIR . '/controllers/chat/tickets-chat.php');
    require_once(ENGINE_DIR . '/controllers/google-auth.php');
    require_once(ENGINE_DIR . '/controllers/facebook-auth.php');
    require_once(ENGINE_DIR . '/controllers/api/qr-code-validation.php');
    require_once(ENGINE_DIR . '/controllers/modules/events/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/ads/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/products/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/lots/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/files/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/movies/add.php');
    require_once(ENGINE_DIR . '/controllers/modules/shop/add.php');
    require_once(ENGINE_DIR . '/controllers/extensions/education/grades/grades.php');
    require_once(ENGINE_DIR . '/controllers/extensions/education/schedules/schedules.php');
    require_once(ENGINE_DIR . '/controllers/extensions/education/student_progress/students_progress.php');

    if (isset($_GET['cart'])) {viewCartController();}
    if (isset($_GET['payment'])) {viewPaymentPage();}
    if (isset($_GET['checkout'])) {checkoutController();}
    if (isset($_GET['payment/error'])) {errorControllerStripe();}
    if (isset($_GET['payment/success'])) {successControllerStripe();}
    if (isset($_GET['payment/error'])) {errorControllerCoinbase();}
    if (isset($_GET['payment/success'])) {successControllerCoinbase();}

    if (isset($_GET['myWallet'])) {walletViewController();}
    if (isset($_GET['pWidget/create'])) {createPaymentWidgetController();}
    if (isset($_GET['payment/withdraw'])) {withdrawControllerStripe();}
    if (isset($_GET['user-profile'])) {userProfileController();}

    if (isset($_GET['promo/check'])) {checkPromocodeController();}
    if (isset($_GET['widget/join'])) {joinWidgetToObjectController();}
    if (isset($_GET['widget/removeRel'])) {deleteWidgetObjectRelationController();}
    if (isset($_GET['pWidget/edit'])) {updatePaymentWidgetController();}
    if (isset($_GET['payment/checkout'])) {viewPaymentControllerBalance();}
    if (isset($_GET['payment/checkout'])) {viewPaymentControllerStripe();}
    if (isset($_GET['payment/checkout'])) {viewPaymentControllerCoinbase();}
    if (isset($_GET['googleAuth'])) {googleAuth();}
    if (isset($_GET['facebookAuth'])) {facebookAuth();}
    if (isset($_GET["pages"]) && $_GET["pages"] == "widgets/handle") {
        require_once(ENGINE_DIR . '/controllers/widgets/widgets_controller.php');
        widgetHandle();
    }
    if (isset($_GET['addObject'])) {addObjectController();}

    if (isset($_GET['referrer/uid'])) {referrerController();}
    if (isset($_GET['pages']) && $_GET["pages"] === "pm") {PMController();}
    if (isset($_GET['pages']) && $_GET["pages"] === "chat") {liveChatController();}
    if (isset($_GET['pages']) && $_GET["pages"] === "notifications") {liveNotificationsController();}
    if (isset($_GET['pages']) && $_GET["pages"] === "myTickets") {ticketsChatController();}
    if (isset($_GET['pages']) && $_GET["pages"] === "qrCodeValidation") {qrCodeValidationController();}

    addToCartController();

    // Дополнительные переменные из URL
    $pages = $_GET['pages'] ?? null;
    $lots = $_GET['lots'] ?? null;
    $lotsCategory = $_GET['lots-category'] ?? null;
    $ads = $_GET['ads'] ?? null;
    $adsCategory = $_GET['ads-category'] ?? null;
    $files = $_GET['files'] ?? null;
    $filesCategory = $_GET['files-category'] ?? null;
    $events = $_GET['events'] ?? null;
    $eventsCategory = $_GET['events-category'] ?? null;
    $movies = $_GET['movies'] ?? null;
    $moviesCategory = $_GET['movies-category'] ?? null;
    $news = $_GET['news'] ?? null;
    $newsCategory = $_GET['news-category'] ?? null;
    $products = $_GET['products'] ?? null;
    $productsCategory = $_GET['products-category'] ?? null;
    $profileId = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $shops = $_GET['shops'] ?? null;
    $shopCategory = $_GET['shop-category'] ?? null;
    $coupons = $_GET['coupons'] ?? null;
    $couponsCategory = $_GET['coupons-category'] ?? null;
    $auctions = $_GET['auctions'] ?? null;
    $auctionsCategory = $_GET['auctions-category'] ?? null;


    // Функция для отображения ошибки
    function displayError($message, $title = "") {
        global $smarty, $config;
        $smarty->assign('error_message', $message);
        $smarty->assign('error_title', $title);
        $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
    }

    // Обработка страницы регистрации
    if (isset($_GET['registration'])) {
        require_once(ENGINE_DIR . '/controllers/registration/page.php');
        registrationPageController();
        exit; // Завершаем выполнение скрипта
    }

    // Обработка запросов для профиля
    if (isset($_GET['profile'])) {

        $action = $_GET['action'] ?? $_POST["action"];

        if ($action) {
            handleProfileAction($action);
            exit;
        }

        if (isset($_GET['id'])) {
            $profileId = (int)$_GET['id'];
            profileController($profileId);
            exit;
        }

        $currentUserId = $_SESSION['user_id'] ?? ($_COOKIE['user_id'] ?? null);

        if ($currentUserId) {
            profileController($currentUserId);
        } else {
            displayError('Invalid request');
        }

        exit;
    }

    function handleProfileAction($action) {
        global $db_connect;
        $parts = explode('/', $action);

        // modules/events/add → parts:
        // [0] => modules
        // [1] => events
        // [2] => add

        switch ($parts[0]) {
            case 'modules':
                if ($parts[1] === 'news' && $parts[2] === 'add') {
                    addObjectNewsController();
                    return;
                } else if ($parts[1] === 'events' && $parts[2] === 'add') {
                    addObjectEventController();
                } else if ($parts[1] === 'products' && $parts[2] === 'add') {
                    addObjectProductController();
                } else if ($parts[1] === 'ads' && $parts[2] === 'add') {
                    addObjectAdsController();
                } else if ($parts[1] === 'files' && $parts[2] === 'add') {
                    addObjectFileController();
                } else if ($parts[1] === 'lots' && $parts[2] === 'add') {
                    addObjectLotController();
                } else if ($parts[1] === 'movies' && $parts[2] === 'add') {
                    addObjectMovieController();
                } else if ($parts[1] === 'shops' && $parts[2] === 'add') {
                    addObjectShopController();
                }
                exit;
            case 'grades':
                $roleName = $db_connect->get("roles", "name", [
                    "id" => $_SESSION["user_group_id"]
                ]);

                if ($roleName == "Teacher") {
                    teacherGradesController();
                } else if ($roleName == "Parent") {
                    parentGradesController();
                } else {
                    displayError('У вас нет доступа к этой странице', 'Доступ запрещен');
                }

                exit;

            case 'save-schedule':
                saveScheduleController();
                header("Location: " . $_SERVER["HTTP_REFERER"]);
                exit;

            case 'delete-schedule':
                $db_connect->delete("schedules", ["id" => $_POST["schedule_id"]]);
                header("Location: " . "/profile?tab=schedules");
                exit;

            case 'save-stud-progress':
                saveStudProgressController();

                exit;
        }

        displayError('Страница не существует', '404 Ошибка');
    }


// Если пользователь отправил запрос на поиск
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['searchbutton'])) {
        searchController();
    }

    // Обработка запросов на основе конфигурации
    $moduleProcessed = false;

    if ($lotsAvailable && $lotsUsed) {
        if (in_array("lots", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($lotsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/lots/lotsByCategory.php');
            lotsByCategoryController($lotsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($lots)) {
            require_once(ENGINE_DIR . '/controllers/modules/lots/full-lots.php');
            lotController($lots, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['lots'])) {
            require_once(ENGINE_DIR . '/controllers/modules/lots/short-lots.php');
            allLotsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($lots)) {
        displayError($lang['errorpage']['not_available']['lots']);
    }

    if ($adsAvailable && $adsUsed) {
        if (in_array("ads", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($adsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/ads/adsByCategory.php');
            adsByCategoryController($adsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($ads)) {
            require_once(ENGINE_DIR . '/controllers/modules/ads/full-ads.php');
            adsController($ads, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['ads'])) {
            require_once(ENGINE_DIR . '/controllers/modules/ads/short-ads.php');
            allAdsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($ads)) {
        displayError($lang['errorpage']['not_available']['ads']);
    }

    if ($eventsAvailable && $eventsUsed) {
        if (in_array("events", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($eventsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/events/eventsByCategory.php');
            eventsByCategoryController($eventsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($events)) {
            require_once(ENGINE_DIR . '/controllers/modules/events/full-events.php');
            eventsController($events, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['events'])) {
            require_once(ENGINE_DIR . '/controllers/modules/events/short-events.php');
            allEventsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($events)) {
        displayError($lang['errorpage']['not_available']['events']);
    }

    if ($filesAvailable && $filesUsed) {
        if (in_array("files", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($filesCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/files/filesByCategory.php');
            filesByCategoryController($filesCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($files)) {
            require_once(ENGINE_DIR . '/controllers/modules/files/full-files.php');
            filesController($files, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['files'])) {
            require_once(ENGINE_DIR . '/controllers/modules/files/short-files.php');
            allFilesController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($files)) {
        displayError($lang['errorpage']['not_available']['files']);
    }

    if ($moviesAvailable && $moviesUsed) {
        if (in_array("movies", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($moviesCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/movies/moviesByCategory.php');
            moviesByCategoryController($moviesCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($movies)) {
            require_once(ENGINE_DIR . '/controllers/modules/movies/full-movies.php');
            moviesController($movies, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['movies'])) {
            require_once(ENGINE_DIR . '/controllers/modules/movies/short-movies.php');
            allMoviesController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($movies)) {
        displayError($lang['errorpage']['not_available']['movies']);
    }

    if ($newsAvailable && $newsUsed) {
        if (in_array("news", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($newsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/news/newsByCategory.php');
            newsByCategoryController($newsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($news)) {
            require_once(ENGINE_DIR . '/controllers/modules/news/full-news.php');
            newsController($news, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['news'])) {
            require_once(ENGINE_DIR . '/controllers/modules/news/short-news.php');
            allNewsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($news)) {
        displayError($lang['errorpage']['not_available']['news']);
    }

    if ($productsAvailable && $productsUsed) {
        if (in_array("products", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        if (isset($productsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/products/productsByCategory.php');
            productsByCategoryController($productsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif (!empty($products)) {
            require_once(ENGINE_DIR . '/controllers/modules/products/full-products.php');
            productsController($products, $lang_code);
            $moduleProcessed = true;
        } elseif (isset($_GET['products'])) {
            require_once(ENGINE_DIR . '/controllers/modules/products/short-products.php');
            allProductsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($products)) {
        displayError($lang['errorpage']['not_available']['products']);
    }

    if ($auctionsAvailable && $auctionsUsed) {
        if (in_array("auctions", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        $uri = trim($_SERVER['REQUEST_URI'], '/');
        $parts = explode('/', $uri);
        if (isset($auctionsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/auctions/auctionsByCategory.php');
            auctionsByCategoryController($auctionsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif ($parts[0] === "auctions" && !empty($parts[1])) {
            require_once(ENGINE_DIR . '/controllers/modules/auctions/full-auctions.php');
            auctionController($parts[1], $lang_code);
            $moduleProcessed = true;
        } elseif ($_GET['pages'] == "auctions") {
            require_once(ENGINE_DIR . '/controllers/modules/auctions/short-auctions.php');
            allauctionsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($auctions)) {
        displayError($lang['errorpage']['not_available']['auctions']);
    }

    if ($couponsAvailable && $couponsUsed) {
        if (in_array("coupons", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        $uri = trim($_SERVER['REQUEST_URI'], '/');
        $parts = explode('/', $uri);
        if (isset($couponsCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/coupons/couponsByCategory.php');
            couponsByCategoryController($couponsCategory, $lang_code);
            $moduleProcessed = true;
        } elseif ($parts[0] === "coupons" && !empty($parts[1])) {
            require_once(ENGINE_DIR . '/controllers/modules/coupons/full-coupons.php');
            couponsController($parts[1], $lang_code);
            $moduleProcessed = true;
        } elseif ($_GET['pages'] == "coupons") {
            require_once(ENGINE_DIR . '/controllers/modules/coupons/short-coupons.php');
            allCouponsController($lang_code);
            $moduleProcessed = true;
        }
    } elseif (isset($coupons)) {
        displayError($lang['errorpage']['not_available']['coupons']);
    }

    if ($shopAvailable && $shopUsed) {
        if (in_array("shops", $config["extensions"]["qr_codes"])) {
            require_once(ENGINE_DIR . '/extensions/page-qr-sharing/page-qr-sharing.php');
        }
        $uri = trim($_SERVER['REQUEST_URI'], '/');
        $parts = explode('/', $uri);
        if (isset($shopCategory)) {
            require_once(ENGINE_DIR . '/controllers/modules/shop/shopByCategory.php');
            shopByCategoryController($shopCategory, $lang_code);
            $moduleProcessed = true;

        } elseif (!empty($shop)) {
            require_once(ENGINE_DIR . '/controllers/modules/shop/full-shop.php');
            shopController($shop, $lang_code);
            $moduleProcessed = true;

        } elseif ($parts[0] === "shops" && !empty($parts[1]) && !str_contains($parts[1], "products")) {
            require_once(ENGINE_DIR . '/controllers/modules/shop/shop-page.php');
            shopPageController($parts[1], $lang_code);
            $moduleProcessed = true;

        } elseif ($parts[0] === "shopProduct") {
            require_once(ENGINE_DIR . '/controllers/modules/shop/product-page.php');
            shopProductPageController($lang_code);
            $moduleProcessed = true;
        }  elseif ($parts[0] === "shops" && !empty($parts[1]) && str_contains($parts[1], "products")) {
            require_once(ENGINE_DIR . '/controllers/modules/shop/short-shop.php');
            allShopProductsController($lang_code);
            $moduleProcessed = true;
        }

    } elseif (isset($shop)) {
        displayError($lang['errorpage']['not_available']['shop']);
    }


// Обработка основной страницы
    if (!$moduleProcessed) {
        if (empty($pages) && empty($news) && empty($products) && empty($ads) && empty($files) && empty($movies)) {
            homeController();
        } elseif (!empty($pages)) {
            require_once(ENGINE_DIR . '/controllers/pages.php');
            pagesController($pages, $lang_code);
        } else {
            displayError('Invalid request');
        }
    }