<?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 shopProductPageController($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';

        if (!empty($_GET["product_id"])) {
            $product_id = $_GET["product_id"];

            $shopProduct = $db_connect->get("shop_products", "*", ["id" => $product_id]);
            $shopProduct["images"] = $db_connect->select("shop_product_files", "url", ["product_id" => $shopProduct["id"]]) ?? [];
            $shopProduct["main_image"] = $db_connect->get("shop_product_files", "url", ["product_id" => $shopProduct["id"]]) ?? [];
            $shopProduct["shop_name"] = $db_connect->get("shops", "shop_name", ["shop_id" => $shopProduct["shop_id"]]) ?? [];
            $shopProduct["shop_main_image"] = $db_connect->get("shop_product_files", "url", ["shop_id" => $shopProduct["shop_id"], "is_main" => 1]) ?? [];
            $shopProduct["attributes"] = $db_connect->select("shop_product_attributes", "*", ["product_id" => $shopProduct["id"]]);

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

            foreach ($shopProducts as &$shopProductAssoc) {
                $shopProductAssoc["image_url"] = $db_connect->get("shop_product_files", "url", ["product_id" => $shopProductAssoc["id"]]) ?? [];
            }
            $shop = $db_connect->get("shops", "*", ["shop_id" => $shopProduct["shop_id"]]) ?? [];
           // rateProduct($shopProduct["id"], $_SESSION["user_id"], 5, "Respect");
            $shop["coupons"] = $db_connect->select("shop_coupons", "*", ["shop_id" => $shopProduct["shop_id"]]) ?? [];

            $productRating = getRating('product', $product_id);
            $reviews = getProductReviews($product_id, 5); // последние 10 отзывов

            require_once ENGINE_DIR . '/mods/get_module_categories.php';
            $shopProduct['category_alt_names'] = getCategoriesAltNames($product_id, "shop", "product");
            $categoriesIds = getCategoriesIds($product_id, "shop", "product");
            $categories = !empty($categoriesIds) ? $db_connect->select("shop_categories", "*", ["id" => $categoriesIds]) : [];

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

            $smarty->assign("cartProductCount", $cartAllQuantity);
            $smarty->assign('shopProducts', $shopProducts);
            $smarty->assign('productReviews', $reviews);
            $smarty->assign('productRating', [
                'average' => $productRating['average_rating'],
                'votes' => $productRating['votes_count']
            ]);
            $smarty->assign('title', $shopProduct['name']  . ' | ' . "{$shop['shop_name']}" .  ' | ' . $config['title']);
           /* $smarty->assign('page_name', '
                <li class="breadcrumb-item"><a href="/shops/'. $shop["slug"] .'">' . $shopProduct['shop_name'] . '</a></li>
                <li class="breadcrumb-item active">' . $shopProduct["name"] . '</li>
            ');*/

            require_once ENGINE_DIR."/mods/breadcrumbs.php";


            require_once(ENGINE_DIR . '/mods/binding_control.php');
            generateBindings("shops", '
                <li class="breadcrumb-item"><a href="/shops/products">Все товары</a></li>
                <li class="breadcrumb-item"><a href="/shops/'.$shop['slug'].'">'.$shop['shop_name'].'</a></li>
                <li class="breadcrumb-item active">' . $shopProduct['name'] . '</li>
            ');


            $smarty->assign("shop", $shop);
            $smarty->assign("shopProduct", $shopProduct);
     //       $smarty->assign('entity', ['id' => $moduletype['id']]);
            $smarty->assign('categories', $categories);

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

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

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