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

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');

    // Проверка, была ли отправлена форма для удаления страницы
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_page_id'])) {
        $page_id = $_POST['delete_page_id'];

        $db_connect->delete("shop_products", ["shop_id" => $page_id]);

        $db_connect->delete("shops", ["shop_id" => $page_id]);
        
        header("Location: /admin?action=modules/shops/list");
        exit();
    }

    // Выполняем запрос для получения полного списка объявлений с использованием Medoo
    $shops = $db_connect->select('shops', '*');

    // Получаем alt_names для каждой категории и формируем ассоциативный массив
    $categoriesAltNames = [];
    $categories = $db_connect->select('shop_categories', ['name', 'alt_name']);
    foreach ($categories as $category) {
        $categoriesAltNames[$category['name']] = $category['alt_name'];
    }
    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });

    require_once ENGINE_DIR . '/mods/get_module_categories.php';
    // Формируем данные для отображения
    foreach ($shops as &$shop) {
        $shop[$lang["datatable"]['category']] = getCategoriesString($shop['shop_id'], "shop");

        $shop[$lang["datatable"]["description"]] = $shop["description"];
        $shop[$lang["datatable"]["location"]] = $shop["location"];
        $shop[$lang["datatable"]["date"]] = $shop["date"];

        $shop[$lang["datatable"]["title"]] = "<a target='_blank' href='/shops/{$shop['slug']}?lang={$shop['language']}'>" . $shop["shop_name"] . "</a>";
        $shop[$lang["datatable"]["lang"]] = "<img src='/engine/lang/{$shop['language']}/icon.png' style='height: 22px;' alt=''>";
        $shop[$lang["datatable"]["actions"]] = "<a href='/admin?action=modules/shops/list_shop_products&shop_id={$shop['shop_id']}' class='mx-1 top-1'>Товары магазина<i class='fa fa-add'></i></a>
                            <a href='/admin?action=modules/shops/add_product&shop_id={$shop['shop_id']}' class='mx-1 top-1'>Добавить товар<i class='fa fa-add'></i></a>
                                <a href='/admin?action=modules/shops/edit&id={$shop['shop_id']}' class='mx-1 top-1'><i class='fa fa-edit'></i></a>
                                    <form method='POST' action='/admin?action=modules/shops/list' style='display:inline;'>
                                        <input type='hidden' name='delete_page_id' value='{$shop['shop_id']}'>
                                        <button type='submit' class='no-b mx-1' onclick='return confirm(`Вы уверены, что хотите удалить этот магазин? Будут удалены все товары магазина!`);'>
                                            <i class='fa fa-trash'></i>
                                        </button>
                                    </form>";
    }

    // Устанавливаем массив переменных в Smarty
    $smarty->assign('shops', $shops);
    $yourData = array('title' => $lang['nav']['shoplist'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
                <li class="breadcrumb-item active">' . $lang['nav']['shoplist'] . '</li>
            ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);