<?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');

    // Сбрасываем счетчик автоинкремента к максимальному значению id
    require_once(ENGINE_DIR . '/mods/autoincrement.php');

    // Если отправлена форма для добавления нового поля
    if (isset($_POST['form_id']) && $_POST['form_id'] === 'add_column') {
        $x_name = $_POST['x_name'];
        $column_type = $_POST['column_type'];
        $column_length = isset($_POST['column_length']) ? intval($_POST['column_length']) : 0;

        $query = "INSERT INTO lots_fields (x_name, column_type, column_length) VALUES (?, ?, ?)";
        $stmt = $db_connect->prepare($query);
        $stmt->bind_param("ssi", $x_name, $column_type, $column_length);
        
        if ($stmt->execute()) {
            list($page_id, $max_id) = resetAutoIncrement($db_connect, 'lots_fields');
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при добавлении поля: " . $stmt->error;
        }
    }

    // Если отправлена форма для редактирования поля
    if (isset($_POST['form_id']) && $_POST['form_id'] === 'edit_column') {
        $id = $_POST['id'];
        $new_x_name = $_POST['new_x_name'];
        $new_column_type = $_POST['new_column_type'];
        $new_column_length = isset($_POST['new_column_length']) ? intval($_POST['new_column_length']) : 0;

        $query = "UPDATE lots_fields SET x_name = ?, column_type = ?, column_length = ? WHERE id = ?";
        $stmt = $db_connect->prepare($query);
        $stmt->bind_param("ssii", $new_x_name, $new_column_type, $new_column_length, $id);
        
        if ($stmt->execute()) {
            list($page_id, $max_id) = resetAutoIncrement($db_connect, 'lots_fields');
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при изменении поля: " . $stmt->error;
        }
    }

    // Если отправлена форма для удаления поля
    if (isset($_POST['form_id']) && $_POST['form_id'] === 'delete_column') {
        $id = $_POST['id'];
        
        $query = "DELETE FROM lots_fields WHERE id = ?";
        $stmt = $db_connect->prepare($query);
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            list($page_id, $max_id) = resetAutoIncrement($db_connect, 'lots_fields');
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при удалении поля: " . $stmt->error;
        }
    }

    // Получение списка дополнительных полей для отображения
    $columns = [];
    $result = $db_connect->query("SELECT * FROM lots_fields");
    while ($row = $result->fetch_assoc()) {
        $columns[] = $row;
    }

    $smarty->assign('columns', $columns);
    $smarty->assign('success_message', $success_message ?? null);
    $smarty->assign('error_message', $error_message ?? null);
    
    $yourData = array('title' => $lang['nav']['lots'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/admin?action=lots/list">' . $lang['topmenu']['lots'] . '</a></li>
        <li class="breadcrumb-item active">' . $lang['nav']['lots'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);