<?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 ($db_connect->connect_error) {
        die("Ошибка подключения: " . $db_connect->connect_error);
    }

    // Проверка, была ли отправлена форма для удаления страницы
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_page_id'])) {
        $page_id = $_POST['delete_page_id'];
        
        // Выполняем запрос для удаления страницы
        $deleteQuery = "DELETE FROM lots WHERE id = ?";
        $stmt = mysqli_prepare($db_connect, $deleteQuery);
        
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "i", $page_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
        } else {
            die("Ошибка подготовки запроса: " . mysqli_error($db_connect));
        }
        
        header("Location: /admin?action=lots/list");
        exit();
    }

    // Выполняем запрос для получения полного списка фильмов
    $selectQuery = "SELECT * FROM lots";
    $result = $db_connect->query($selectQuery);
    $lots = [];

    while ($story = $result->fetch_assoc()) {
        $categories = explode(',', $story['category']);
        $altNames = [];
    
        foreach ($categories as $category) {
            $category = trim($category);
            $altNameQuery = $db_connect->prepare('SELECT alt_name FROM lots_categories WHERE name = ?');
            $altNameQuery->bind_param('s', $category);
            $altNameQuery->execute();
            $altNameResult = $altNameQuery->get_result();
            $altName = $altNameResult->fetch_assoc();
            $altNames[] = $altName ? $altName['alt_name'] : '';
        }
    
        $story['category_alt_names'] = implode(',', $altNames);
        $story['category_links'] = array_map(function ($altName) {
            return "/lc/{$altName}";
        }, $altNames);
        $story['category_names'] = $categories;
        $lots[] = $story;
    }

    // Получаем alt_names для каждой категории и формируем ассоциативный массив
    $categoriesAltNames = [];
    $categoryAltNameQuery = $db_connect->query("SELECT name, alt_name FROM lots_categories");
    while ($categoryAltName = $categoryAltNameQuery->fetch_assoc()) {
        $categoriesAltNames[$categoryAltName['name']] = $categoryAltName['alt_name'];
    }

    // Закрываем соединение с базой данных
    $db_connect->close();

    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });

    foreach ($lots as &$lot) {
        $lot["title"] = "<a target='_blank' href='/lots/lot-{$lot['id']}'>" . $lot["title"] . "</a>";
        $lot["lang"] = "<img src='/engine/lang/{$lot['language']}/icon.png' style='height: 22px;' alt=''>";
        $lot["actions"] = "<a href='/admin?action=news/edit&id={$lot['id']}' class='mx-1 top-1'><i class='fa fa-edit'></i></a>
                                    <form method='POST' action='/admin?action=news/list' style='display:inline;'>
                                        <input type='hidden' name='delete_page_id' value='{$lot['id']}'>
                                        <button type='submit' class='no-b mx-1' onclick='return confirm('Вы уверены, что хотите удалить эту новость?');'>
                                            <i class='fa fa-trash'></i>
                                        </button>
                                    </form>";
    }

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