<?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');
    $module_entity = 'auctions';

    $action = isset($_GET['action']) ? $_GET['action'] : 'main';

    $categories = [];
    $result = $db_connect->select("auctions_categories", "*") ?? [];
    if (!empty($result["id"])) {
        $categories[] = $result;
    } else {
        foreach ($result as $row) {
            $categories[] = $row;
        }
    }

    if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'modules/auctions/edit') {
        // Обработка POST-запроса для сохранения изменений страницы
        if (isset($_POST['p_id'])) {
            $page_id = $_POST['page_id'];
            $folder = $_POST['folder'] ?? '';
            $p_id = $_POST['p_id'] ?? '';

            $x_values = isset($_POST['x_value']) ? implode(', ', $_POST['x_value']) : '';
            $field_ids = $_POST['field_ids'] ?? [];
            $auctions_id = $page_id;

            if (!empty($field_ids)) {
                foreach ($field_ids as $field_id) {
                    if (!empty($_POST['x_value'][$field_id])) {
                        $insertField = $db_connect->insert("auctions_field_values", [
                            "auctions_id" => $auctions_id,
                            "field_id" => $field_id,
                            "x_value" => $_POST['x_value'][$field_id]
                        ]);
                    }
                }
            }

            $date = isset($_POST['date']) && !empty($_POST['date']) ? strip_tags(trim($_POST['date'])) : date($config['date_format']);
            $autor = isset($_POST['autor']) ? strip_tags(trim($_POST['autor'])) : '';
            $category = isset($_POST['category']) ? (is_array($_POST['category']) ? implode(', ', $_POST['category']) : $_POST['category']) : '';
            $language = isset($_POST['language']) ? (is_array($_POST['language']) ? implode(', ', $_POST['language']) : $_POST['language']) : '';
            $title = strip_tags(trim($_POST['title']));
            $alt_name = strip_tags(trim($_POST['alt_name']));
            $short_desc = htmlspecialchars($_POST['short_desc'], ENT_QUOTES);
            $full_desc = htmlspecialchars($_POST['full_desc'], ENT_QUOTES);
            
            $start_date = isset($_POST['start_date']) && !empty($_POST['start_date']) ? strip_tags(trim($_POST['start_date'])) : date($config['date_format']);
            $end_date = isset($_POST['end_date']) && !empty($_POST['end_date']) ? strip_tags(trim($_POST['end_date'])) : date($config['date_format']);
            $location = isset($_POST['location']) ? (is_array($_POST['location']) ? implode(', ', $_POST['location']) : $_POST['location']) : '';
            $capacity = isset($_POST['capacity']) ? (is_array($_POST['capacity']) ? implode(', ', $_POST['capacity']) : $_POST['capacity']) : '';
            $status = isset($_POST['status']) ? (is_array($_POST['status']) ? implode(', ', $_POST['status']) : $_POST['status']) : '';
            $performers = isset($_POST['performers']) ? (is_array($_POST['performers']) ? implode(', ', $_POST['performers']) : $_POST['performers']) : '';
            
            $meta_desc = strip_tags(trim($_POST['meta_desc']));
            $meta_keys = strip_tags(trim($_POST['meta_keys']));
            $views = isset($_POST['views']) ? intval($_POST['views']) : 0;

            $stmt = $db_connect->update("auctions", [
                "user_id" => $_SESSION["user_id"],
                "title" => $title,
                "short_desc" => $short_desc,
                "full_desc" => $full_desc,
                "start_price" => $_POST["start_price"],
                "current_price" => $_POST["current_price"],
                "buy_now_price" => $_POST["buy_now_price"],
                "language" => $language == "" ? $_SESSION['lang'] : $language,
                "views" => $views,
                "meta_desc" => $meta_desc,
                "meta_keys" => $meta_keys,
                "status" => $status,
                "start_at" => $start_date,
                "end_at" => $end_date
            ], ["id" => $p_id]);

            $db_connect->delete("auctions_cat_relations", ["auctions_id" => (int)$p_id]);

            if (!empty($_POST["category"])) {
                foreach ($_POST["category"] as $categoryId) {
                    $db_connect->insert("auctions_cat_relations", [
                        "auctions_id" => (int)$p_id,
                        "category_id" => (int)$categoryId,
                    ]);
                }
            }

            if ($stmt) {
                header("Location: /admin?action=modules/auctions/list");
                exit();
            } else {
                echo "Ошибка подготовки запроса: " . mysqli_error($db_connect);
                exit();
            }

        } else {

            echo "Ошибка: ID страницы не указан.";
            exit();

        }
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET" && $action == 'modules/auctions/edit') {
        // Обработка GET-запроса для отображения страницы редактирования
        if (isset($_GET['id'])) {
            $page_id = $_GET['id'];
            require_once ENGINE_DIR.'/mods/get_module_categories.php';

            // Подключаем дополнительные поля
            require_once(SYSTEM_DIR . '/plugins/extra_fields.php');
            $stmt = $db_connect->get("auctions", "*", ["id" => $page_id]);

            if ($stmt) {
                $result = $stmt;
                if ($result) {
                    $page = $result;
                    $smarty->assign('page', $page);
                    $selectedCategories = getCategoriesIds($page["id"], "auctions");
                    $smarty->assign('selectedCategories', $selectedCategories);

                    $selectedLanguages = explode(", ", $page['language']);
                    $smarty->assign('selectedLanguages', $selectedLanguages);
                } else {
                    echo "Ошибка: Страница не найдена.";
                    exit();
                }
            } else {
                // В случае ошибки выводим сообщение
                echo "Ошибка подготовки запроса: " . mysqli_error($db_connect);
                exit();
            }
        } else {
            // Если запрос не был отправлен методом GET или отсутствует параметр id, выводим сообщение об ошибке
            echo "Ошибка: Доступ запрещен.";
            exit();
        }
    }

    $smarty->assign('categories', $categories);
    // Устанавливаем массив переменных в Smarty
    $smarty->assign('add_page', 'add_page');
    $smarty->assign('page_id', $page_id);
    $smarty->assign('stmt', $stmt);
    $yourData = array('title' => $lang['nav']['auctionsedit'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/admin?action=auctions/list">' . $lang['topmenu']['auctions'] . '</a></li>
        <li class="breadcrumb-item active">Редактирование лота</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);