<?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');
    list($page_id, $max_id) = resetAutoIncrement($db_connect, 'social_sliders');

    // Передача уникального ключа для добавления/удаления категорий
    if (!isset($_SESSION['slider_form_key'])) {
        $_SESSION['slider_form_key'] = uniqid();
    }


    $sliders = $db_connect->select("social_sliders", "*");

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_slider'])) {
        if (isset($_POST['form_key']) && $_POST['form_key'] === $_SESSION['slider_form_key']) {
            // Получение значений из формы
            $title = $_POST['title'];
            $social = $_POST['social'];
            $token = $_POST['token'];
            $resource = $_POST['resource'];
            $rows = $_POST['rows'];
            $columns = $_POST['columns'];

            $query = $db_connect->insert("social_sliders", [
                "title" => $title,
                "social" => $social,
                "token" => $token,
                "resource" => $resource,
                "rows" => $rows,
                "columns" => $columns
            ]);

            if ($query) {
                unset($_SESSION['slider_form_key']);
                header("Location: {$_SERVER['REQUEST_URI']}&result=added");
                exit();
            } else {
                echo "Ошибка при добавлении: " . mysqli_error($db_connect);
            }
        }
    }    

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_slider'])) {
        $slider_id = intval($_POST['delete_slider']); // Безопасное приведение к целому числу для защиты от SQL-инъекций
        $delete_query = $db_connect->delete("social_sliders", ["id" => $slider_id]);

        if ($delete_query) {
            unset($_SESSION['slider_form_key']);
            header("Location: {$_SERVER['REQUEST_URI']}&result=deleted");
            exit();
        } else {
            header("Location: {$_SERVER['REQUEST_URI']}");
            exit();
        }
    }

    // Уведомления об успехе
    if (isset($_GET['result'])) {
        if ($_GET['result'] == 'deleted') {
            $smarty->assign('resultMessage', 'Удаление успешно завершено.');
        } elseif ($_GET['result'] == 'added') {
            $smarty->assign('resultMessage', 'Добавление успешно завершено.');
        } elseif ($_GET['result'] == 'edited') {
            $smarty->assign('resultMessage', 'Редактирование успешно завершено.');
        }
    }

    // Передача данных в шаблон
    $smarty->assign('sliders', $sliders);
    $smarty->assign('form_key', $_SESSION['slider_form_key']);
    $yourData = array('title' => $lang['nav']['socialwidgets'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['nav']['socialwidgets'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);