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

    // Получение всех категорий
    $categories = $db_connect->select("products_categories", "*");

    // Сбрасываем счетчик автоинкремента к максимальному значению id
    require_once(ENGINE_DIR . '/mods/autoincrement.php');
    //list($page_id, $max_id) = resetAutoIncrement($db_connect, 'ads_categories');

    $parent_categories = array_filter($categories, function($category) {
        return $category['parentid'] == 0;
    });

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

    // Проверка запроса на добавление категории
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_category'])) {
        if (isset($_POST['form_key']) && $_POST['form_key'] === $_SESSION['category_form_key']) {
            $data = [
           //     'id' => $db_connect->max("products_categories", "id") + 1,
                'name' => $_POST['name'],
                'alt_name' => $_POST['alt_name'],
                'language' => $_POST['language'],
                'parentid' => intval($_POST['parentid']),
            ];

            $max_position = $db_connect->max("products_categories", "position", [
                "parentid" => $data['parentid']
            ]);
            $data['position'] = $max_position ? $max_position + 1 : 1;

            $db_connect->insert("products_categories", $data);
            unset($_SESSION['category_form_key']);
            header("Location: {$_SERVER['REQUEST_URI']}&success=added");
            exit();
        } else {
            die('Ошибка: неверный ключ формы.');
        }
    }

    // Проверка запроса на удаление категории
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_products_category'])) {
        if (isset($_POST['form_key']) && $_POST['form_key'] === $_SESSION['category_form_key']) {
            $db_connect->delete("products_categories", [
                "id" => intval($_POST['id'])
            ]);
            unset($_SESSION['category_form_key']);
            header("Location: {$_SERVER['REQUEST_URI']}&success=deleted");
            exit();
        } else {
            die('Ошибка: неверный ключ формы.');
        }
    }

    // Уведомления об успехе
    if (isset($_GET['success'])) {
        $messages = [
            'deleted' => 'Категория успешно удалена.',
            'added' => 'Категория успешно добавлена.',
            'edited' => 'Категория успешно отредактирована.'
        ];
        $smarty->assign('successMessage', $messages[$_GET['success']]);
    }

    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    foreach ($categories as $key => &$category) {
        $category[$lang['datatable']['uniq_id']] = $key+1;
        $category[$lang['datatable']['position']] = $category['position'];
        $category[$lang['datatable']['name']] = $category['name'];
        $category[$lang['datatable']['views']] = $category['name'];
        $category[$lang['datatable']['parentid']] = $category['parentid'];

        $category[$lang['datatable']['lang']] = "<img src='/engine/lang/{$category['language']}/icon.png' style='height: 22px;' alt=''>";
        $category[$lang['datatable']['actions']] = "
            <button type='button' class='mx-1 bg-transparent border' onclick='largeModal(`eventsCategoriesEditForm`)'><i class='fa fa-edit'></i></button>
            <form method='POST' action='/admin?action=movies/categories' style='display:inline;'>
                <input type='hidden' name='form_key' value='{$_SESSION['category_form_key']}'>
                <input type='hidden' name='id' value='{$category['id']}'>
                <input type='hidden' name='delete_products_category' value='1'>
                <button type='submit' class='no-b mx-1' onclick='return confirm(`Вы уверены, что хотите удалить категорию?`);'>
                    <i class='fa fa-trash'></i>
                </button>
            </form>";
        $category[$lang['datatable']['count']] = 0;
    }

    require_once(ENGINE_DIR . '/mods/nested_categories_tree_build.php');
    $categories = buildTree($categories, null);

    // Передача данных в шаблон
    $smarty->assign('form_key', $_SESSION['category_form_key']);
    $smarty->assign('categories', $categories);
    $smarty->assign('parent_categories', $parent_categories);
    $yourData = array('title' => $lang['nav']['productscategories'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/admin?action=products/list">Объявления</a></li>
        <li class="breadcrumb-item active">' . $lang['nav']['productscategories'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);