<?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("movies_categories", "*");

    require_once(ENGINE_DIR . '/mods/autoincrement.php');
    $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']) {
            $name = $_POST['name'];
            $alt_name = $_POST['alt_name'];
            $language = $_POST['language'];
            $parentid = intval($_POST['parentid']);

            if ($parentid === 0) {
                $max_position = $db_connect->max("movies_categories", "position", ["parentid" => 0]) == "" ? null : $db_connect->max("movies_categories", "position", ["parentid" => 0]);
                $position = $max_position !== null ? $max_position + 1 : 1;
            } else {
                $max_position = $db_connect->max("movies_categories", "position", ["parentid" => $parentid]);
                $position = $max_position !== null ? $max_position + 1 : 1;
            }

            $result = $db_connect->insert("movies_categories", [
               // 'id' => $db_connect->max("movies_categories", "id") + 1,
                "name" => $name,
                "alt_name" => $alt_name,
                "language" => $language,
                "parentid" => $parentid,
                "position" => $position
            ]);

            if ($result->rowCount() > 0) {
                unset($_SESSION['category_form_key']);
                header("Location: {$_SERVER['REQUEST_URI']}&success=added");
                exit();
            } else {
                die('Ошибка добавления категории.');
            }
        } else {
            die('Ошибка: неверный ключ формы.');
        }
    }

    // Проверка запроса на удаление категории
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_movies_category'])) {
        if (isset($_POST['form_key']) && $_POST['form_key'] === $_SESSION['category_form_key']) {
            $id = intval($_POST['id']);
            $result = $db_connect->delete("movies_categories", ["id" => $id]);

            if ($result->rowCount() > 0) {
                unset($_SESSION['category_form_key']);
                header("Location: {$_SERVER['REQUEST_URI']}&success=deleted");
                exit();
            } else {
                die('Ошибка удаления категории.');
            }
        } else {
            die('Ошибка: неверный ключ формы.');
        }
    }
    global $smarty;
    // Уведомления об успехе
    if (isset($_GET['success'])) {
        if ($_GET['success'] == 'deleted') {
            $smarty->assign('successMessage', 'Категория успешно удалена.');
        } elseif ($_GET['success'] == 'added') {
            $smarty->assign('successMessage', 'Категория успешно добавлена.');
        } elseif ($_GET['success'] == 'edited') {
            $smarty->assign('successMessage', 'Категория успешно отредактирована.');
        }
    }

    $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_movies_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 = ['title' => $lang['nav']['moviescategories'] . ' - ' . $config['title']];
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
            <li class="breadcrumb-item active"><a href="/admin?action=movies/list">Фильмы</a></li>
            <li class="breadcrumb-item active">' . $lang['nav']['moviescategories'] . '</li>
        ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);
    ?>
