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

        $data = [
            'x_name' => $x_name,
            'column_type' => $column_type,
            'column_length' => $column_length
        ];

        if ($db_connect->insert('lots_fields', $data)) {
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при добавлении поля";
        }
    }


    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;

        $data = [
            'x_name' => $new_x_name,
            'column_type' => $new_column_type,
            'column_length' => $new_column_length
        ];

        if ($db_connect->update('lots_fields', $data, ['id' => $id])) {
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при изменении поля";
        }
    }

    // Если отправлена форма для удаления поля
    if (isset($_POST['form_id']) && $_POST['form_id'] === 'delete_column') {
        $id = $_POST['id'];

        if ($db_connect->delete('lots_fields', ['id' => $id])) {
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        } else {
            $error_message = "Ошибка при удалении поля";
        }
    }

$columns = $db_connect->select('lots_fields', '*');

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

foreach ($columns as $key => &$column) {

    $types = ['VARCHAR', 'INT', 'TEXT', 'TIMESTAMP', 'TINYINT', 'BOOLEAN', 'MEDIUMTEXT', 'DECIMAL'];
    $options = '';

    foreach ($types as $type) {
        $selected = ($column['column_type'] == $type) ? 'selected' : '';
        $options .= "<option value='$type' $selected>$type</option>";
    }

    $column["actions"] = "<button type='button' class='no-b mx-1' onclick='smallModal(`editColumn{$column['id']}`)' >
                        <i class='fa fa-edit text-warning'></i>
                    </button>
                    <!-- Форма для удаления поля -->
                    <form method='POST' action='#' class='d-inline'>
        <input type='hidden' name='form_id' value='delete_column'>
                        <input type='hidden' name='id' value='{$column['id']}'>
                        <button type='submit' class='no-b mx-1' onclick='return confirm(`Удалить поле {$column['x_name']}?`)'>
                            <i class='fa fa-trash text-danger'></i>
                        </button>
                    </form><div id='editColumn{$column['id']}' class='hidden'>
                <!-- Форма для редактирования поля -->
                <form method='POST' action='#'>
        <input type='hidden' name='form_id' value='edit_column'>
                    <input type='hidden' name='id' value='{$column['id']}'>
                    <div class='row'>
                        <div class='col-12 mb-2'>
                            <label>Заголовок столбца:</label>
                            <input type='text' class='form-control' name='new_x_name' value='{$column['x_name']}' required>
                        </div>
                        <div class='col-12 mb-2'>
                            <label>Тип столбца:</label>
                            <select class='form-control' name='new_column_type'>
                                $options
                            </select>
                        </div>
                        <div class='col-12 mb-2'>
                            <label>Длина:</label>
                            <input type='number' class='form-control' name='new_column_length' value='{$column['column_length']}' placeholder='Только для VARCHAR, TINYINT, DECIMAL'>
                        </div>
                        <div class='col-12 mb-0'>
                            <button type='submit' class='btn btn-outline-success w-100'>Сохранить изменения</button>
                        </div>
                    </div>
                </form>
            </div>";

    $column["Заголовок"] = $column["x_name"];
    $column["Тип"] = $column["column_type"];
    $column["Длина"] = $column["column_length"];
    $column["Действия"] = $column["actions"];
    unset($columns[$key]["column_type"]);
    unset($columns[$key]["column_length"]);
    unset($columns[$key]["x_name"]);
    unset($columns[$key]["actions"]);
}
    $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);