<?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');
    $module_entity = 'coupons';

    require_once(SYSTEM_DIR . '/plugins/reserved_urls.php');

    $coupons_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    if ($coupons_id <= 0) {
        header("Location: /admin?action=modules/coupons/list");
        exit;
    }

    /* === ТЕКУЩИЙ КУПОН === */
    $coupon = $db_connect->get("coupons", "*", [
        "id" => $coupons_id
    ]);

    if (!$coupon) {
        header("Location: /admin?action=modules/coupons/list");
        exit;
    }

    /* === КАТЕГОРИИ === */
    $categories = $db_connect->select("coupons_categories", "*") ?? [];

    $selectedCategories = $db_connect->select(
        "coupons_cat_relations",
        "category_id",
        ["coupons_id" => $coupons_id]
    ) ?? [];

    /* === EDIT === */
    if (isset($_POST['editcoupon'])) {

        $result = $db_connect->update("coupons", [
            "start_at" => $_POST['start_at'],
            "end_at" => $_POST['end_at'],
            "code" => $_POST['code'],
            "discount_type" => $_POST['discount_type'],
            "discount_value" => $_POST['discount_value'],
            "apply_to_all" => $_POST['apply_to_all'],
            "status" => $_POST['status'],
            "min_order_sum" => $_POST['min_order_sum'],
            "max_discount_sum" => $_POST['max_discount_sum'],
            "usage_limit" => $_POST['usage_limit'],
            "usage_limit_per_user" => $_POST['usage_limit_per_user'],
            "description" => $_POST['description'],
        ], [
            "id" => $coupons_id
        ]);

        /* === КАТЕГОРИИ (перезапись) === */
        $db_connect->delete("coupons_cat_relations", [
            "coupons_id" => $coupons_id
        ]);

        if (!empty($_POST["category"])) {
            foreach ($_POST["category"] as $categoryId) {
                $db_connect->insert("coupons_cat_relations", [
                    "coupons_id" => $coupons_id,
                    "category_id" => (int)$categoryId,
                ]);
            }
        }

        /* === ACCESS === */
        require_once ENGINE_DIR . '/mods/access_control.php';
        saveAccessSettings(
            $coupons_id,
            "coupons",
            $_POST["exclude_locations"] ?? [],
            $_POST["include_locations"] ?? [],
            $_POST["groups"] ?? []
        );

        /* === EXTRA FIELDS === */
        $db_connect->delete("coupons_field_values", [
            "coupons_id" => $coupons_id
        ]);

        if (!empty($_POST['field_ids'])) {
            foreach ($_POST['field_ids'] as $field_id) {
                if (!empty($_POST['x_value'][$field_id])) {
                    $db_connect->insert("coupons_field_values", [
                        "coupons_id" => $coupons_id,
                        "field_id" => $field_id,
                        "x_value" => $_POST['x_value'][$field_id]
                    ]);
                }
            }
        }

        if ($result) {
            header("Location: /admin?action=modules/coupons/list");
            exit;
        }
    }

    /* === EXTRA FIELDS === */
    require_once(SYSTEM_DIR . '/plugins/extra_fields.php');
    $groups = $db_connect->select("roles", "*") ?? [];

    /* === SMARTY === */
    $smarty->assign('coupon', $coupon);
    $smarty->assign('categories', $categories);
    $smarty->assign('selectedCategories', $selectedCategories);
    $smarty->assign('groups', $groups);

    $smarty->assign('data', [
        'title' => $lang['nav']['editcoupon'] . ' - ' . $config['title']
    ]);

    $smarty->assign('page_name', '
            <li class="breadcrumb-item active">
                <a href="/admin?action=coupons/list">Купоны</a>
            </li>
            <li class="breadcrumb-item active">'.$lang['nav']['editcoupon'].'</li>
        ');

    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);
