<?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.                                                      *
        *****************************************************************************
    */

// Путь к config.php относительно текущего файла
require_once(ENGINE_DIR . '/data/config.php');
require_once(ENGINE_DIR . '/mods/database_helper.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["create_promocode"])) {
    $data = [
        "code" => $_POST['code'],
        "discount_percent" => $_POST['discount_percent'],
        "valid_from" => $_POST['valid_from'],
        "valid_to" => $_POST['valid_to'],
        "usage_limit" => $_POST['usage_limit'],
    ];
    $inserted = $db_connect->insert("promocodes", $data);

    header("Location: ".$_SERVER["HTTP_REFERER"]);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["edit_promocode"])) {
    $data = [
        "code" => $_POST['code'],
        "discount_percent" => $_POST['discount_percent'],
        "valid_from" => $_POST['valid_from'],
        "valid_to" => $_POST['valid_to'],
        "usage_limit" => $_POST['usage_limit'],
    ];
    $updated = $db_connect->update("promocodes", $data, ["id" => $_POST['promocode_id']]);

    header("Location: ".$_SERVER["HTTP_REFERER"]);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["delete_promocode"])) {
    $deleted = $db_connect->delete("promocodes", ["id" => $_POST['id']]);

    header("Location: ".$_SERVER["HTTP_REFERER"]);
}

// Получаем список промокодов
$promocodes = $db_connect->select("promocodes", "*");
if (!isset($_SESSION['category_form_key'])) {
    $_SESSION['category_form_key'] = uniqid();
}
foreach ($promocodes as &$promocode) {
    $promocode[$lang["datatable"]["code"]] = $promocode["code"];
    $promocode[$lang["datatable"]["discount_percent"]] = $promocode["discount_percent"];
    $promocode[$lang["datatable"]["valid_from"]] = $promocode["valid_from"];
    $promocode[$lang["datatable"]["valid_to"]] = $promocode["valid_to"];
    $promocode[$lang["datatable"]["usage_limit"]] = $promocode["usage_limit"];
    $promocode[$lang["datatable"]["count"]] = $promocode["count"];


    $promocode[$lang["datatable"]["actions"]] = "<button type='button' class='mx-1 bg-transparent border' onclick='largeModal(`eventsCategoriesEditForm{$promocode['id']}`)'><i class='fa fa-edit'></i></button>
                        <form method='POST' action='/admin?action=promocodes' style='display:inline;'>
                            <input type='hidden' name='form_key' value='{$_SESSION['category_form_key']}'>
                            <input type='hidden' name='id' value='{$promocode['id']}'>
                            <input type='hidden' name='delete_events_category' value='1'>
                            <button type='submit' class='no-b mx-1' name='delete_promocode' onclick='return confirm(\"Вы уверены, что хотите удалить промокод?\");'>
                                <i class='fa fa-trash'></i>
                            </button>
                        </form>
                        <div id='eventsCategoriesEditForm{$promocode['id']}' class='hidden'>
        <h5 class='mt-0'>{$lang["datatable"]["edit_promo"]}</h5>
        <form method='POST'>
            <input type='hidden' name='form_key' value='{$_SESSION['category_form_key']}'>
            <input type='hidden' name='promocode_id' value='{$promocode['id']}'>
            <div class='row'>
                <div class='col-6'>
                    <label class='col-form-label mt-1'>{$lang["datatable"]["promo_name"]}</label>
                    <input type='text' class='form-control' name='code' value='{$promocode["code"]}' id='code' required>
                </div>
                <div class='col-6'>
                    <label class='col-form-label mt-1'>{$lang["datatable"]["discount_percent"]}</label>
                    <input type='number' class='form-control' name='discount_percent' value='{$promocode["discount_percent"]}' id='discount_percent' required>
                </div>
                <div class='col-6'>
                    <label class='col-form-label mt-1'>{$lang["datatable"]["valid_from"]}</label>
                    <input type='datetime-local' class='form-control' name='valid_from' id='valid_from' value='{$promocode["valid_from"]}' required>
                </div>
                <div class='col-6'>
                    <label class='col-form-label mt-1'>{$lang["datatable"]["valid_to"]}</label>
                    <input type='datetime-local' class='form-control' name='valid_to' id='valid_to' value='{$promocode["valid_to"]}' required>
                </div>
                <div class='col-6'>
                    <label class='col-form-label mt-1'>{$lang["datatable"]["usage_limit"]}</label>
                    <input type='number' class='form-control' name='usage_limit' id='usage_limit' value='{$promocode["usage_limit"]}' required>
                </div>
                <div class='col-12'>
                    <button type='submit' name='edit_promocode' class='btn btn-success mt-4' id='submitButton'>{$lang["datatable"]["edit"]}</button>
                </div>
            </div>
        </form>
    </div>
</div>";
}
$smarty->registerPlugin('modifier', 'json_encode', function($value) {
    return json_encode($value);
});
// Устанавливаем массив переменных в Smarty
$yourData = array('title' => $lang['megamenu']['allpromocodes'] . ' - ' . $config['title']);
$smarty->assign("promocodes", $promocodes);
$smarty->assign('data', $yourData);
$smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['megamenu']['allpromocodes'] . '</li>
    ');
$smarty->assign('form_key', $_SESSION['category_form_key']);
$yourData = array('title' => $lang['nav']['adscategorieslist'] . ' - ' . $config['title']);
$smarty->assign('theme', SYSTEM_DIR);
$smarty->assign('config', $config);
?>
