<?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 . '/mods/comments.php');
    function shopPageController($slugName, $lang_code) {
        global $db_connect, $smarty, $config, $lang, $currentCurrency;

        require_once ENGINE_DIR.'/mods/banned_words_detector.php';
        require_once ENGINE_DIR.'/mods/rating_control.php';

            $shop = $db_connect->get("shops", "*", ["slug" => $slugName]);
            if (empty($shop)) {
                $smarty->assign('error_message', 'Магазин не найден');
                $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
                return;
            }

            $shop_id = $shop["shop_id"];

            $shop["main_image"] = $db_connect->get("shop_product_files", "url", ["shop_id" => $shop_id, "is_main" => 1]) ?? "";
            $shop["coupons"] = $db_connect->select("shop_coupons", "*", ["shop_id" => $shop_id]) ?? [];
            $shop["shop_images"] = $db_connect->select("shop_product_files", "url", ["shop_id" => $shop_id, "is_main" => 0]) ?? [];

            $shopProducts = $db_connect->select("shop_products", "*", ["shop_id" => $shop_id]) ?? [];

            $db_connect->update("co_buyings", [
                "status" => "failed"
            ], [
                "date_end[<]" => date("Y-m-d H:i:s"),
                "status" => "active",
                "current_amount[<]" => \Medoo\Medoo::raw("goal_amount")
            ]);

            $db_connect->update("co_buyings", [
                "status" => "completed"
            ], [
                "status" => "active",
                "current_amount[>=]" => \Medoo\Medoo::raw("goal_amount")
            ]);

            $coBuyings = $db_connect->select("co_buyings", [
                "[>]shop_products" => ["product_id" => "id"]
            ], [
                "co_buyings.id",
                "co_buyings.product_id",
                "co_buyings.goal_amount",
                "co_buyings.current_amount",
                "co_buyings.status",
                "co_buyings.date_end",
                "shop_products.name(product_title)",
                "shop_products.price(product_price)"
            ], [
                "co_buyings.status" => "active",
                "shop_products.shop_id" => $shop_id
            ]);

            foreach ($coBuyings as &$cb) {
                $cb["progress"] = ($cb["goal_amount"] > 0)
                    ? round(($cb["current_amount"] / $cb["goal_amount"]) * 100)
                    : 0;

                // Подтягиваем участников
                $cb["participants"] = $db_connect->select("co_buyings_participants", [
                    "[>]users" => ["user_id" => "id"]
                ], [
                    "users.id(user_id)",
                    "users.name(user_name)",
                    "co_buyings_participants.paid_amount",
                    "co_buyings_participants.date_paid"
                ], [
                    "co_buyings_participants.co_buying_id" => $cb["id"]
                ]);
            }
            unset($cb);


            foreach ($shopProducts as &$shopProduct) {
                $shopProduct["image_url"] = $db_connect->get("shop_product_files", "url", ["product_id" => $shopProduct["id"]]) ?? [];
                $shopProduct["rating"] = getRating('product', $shopProduct["id"]);
            }

            require_once ENGINE_DIR . '/mods/get_module_categories.php';
            $shop['category_alt_names'] = getCategoriesAltNames($shop_id, "shop");
            $categoriesIds = getCategoriesIds($shop_id, "shop");

            $categories = !empty($categoriesIds) ? $db_connect->select("shop_categories", "*", ["id" => $categoriesIds]) : [];


            if ($shop["owner_id"] == $_SESSION["user_id"]) {
                $shop["is_owner"] = true;
            } else {
                $shop["is_owner"] = false;
            }

            $shopRating = getRating('shop', $shop_id);
            $cartAllQuantity = 0;
            foreach ($_SESSION['cart'] as $key => $value) {
                $cartAllQuantity += (int)$value['quantity'] ?? 0;
            }

           $smarty->assign("coBuyings", $coBuyings);
            $smarty->assign("cartProductCount", $cartAllQuantity);
            $smarty->assign('title', $shop['shop_name']  . ' - ' . "Shops" . ' - ' . $config['title']);

        require_once(ENGINE_DIR . '/mods/binding_control.php');
        generateBindings("shops", '
                <li class="breadcrumb-item"><a href="/shops/'. $shop["slug"] .'">' . $shop['shop_name'] . '</a></li>
            ');

            $smarty->assign('shopRating', [
                'average' => $shopRating['average_rating'],
                'votes' => $shopRating['votes_count']
            ]);
            $smarty->assign("categories", $categories);

            $smarty->assign("shop", $shop);
            $smarty->assign("shopProducts", $shopProducts);
            $smarty->assign('entity', ['id' => $moduletype['id']]);
            $smarty->assign('entity_type', $moduletype);

            $smarty->assign('currentCurrency', $currentCurrency);
            $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/shops/' . $config['modules']['shop']['shop_page_tpl'], ['shop' => $shop]));

            // Проверяем, выключен ли сайт
            require_once(ENGINE_DIR . '/mods/offline.php');
       // }

        // Устанавливаем счетчик просмотров
        $sqltablename = 'shops';
        require_once(ENGINE_DIR . '/mods/views.php');
    }
    $smarty->assign($config);