<?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');
require_once(ENGINE_DIR . '/mods/database_helper.php');

if (!isset($_SESSION['ref_settings_form_key'])) {
    $_SESSION['ref_settings_form_key'] = uniqid();
}

if (isset($_POST["create_ref_settings"]) && $_POST["form_key"] == $_SESSION["ref_settings_form_key"]) {
    $objectType = "roles";
    $groupName = $db_connect->get($objectType, "name", ["id" => $_POST["user_group_name"]]);
    $db_connect->insert("referral_settings", [
        "object_name" => $groupName,
        "object_type" => $objectType,
        "object_id" => $_POST["user_group_name"],
        "discount_percent" => (int)$_POST["discount_percent"],
        "discount_sum" => (int)$_POST["discount_sum"],
        "operations" => json_encode(!empty($_POST["operation"]) ? $_POST["operation"] : []),
    ]);

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


if (isset($_POST["edit_ref_settings"]) && $_POST["form_key"] == $_SESSION["ref_settings_form_key"]) {
    $objectType = "roles";
    $groupName = $db_connect->get($objectType, "name", ["id" => $_POST["user_group_name"]]);
    $db_connect->update("referral_settings", [
        "object_name" => $groupName,
        "object_type" => $objectType,
        "object_id" => $_POST["user_group_name"],
        "discount_percent" => (int)$_POST["discount_percent"],
        "discount_sum" => (int)$_POST["discount_sum"],
        "operations" => json_encode(!empty($_POST["operation"]) ? $_POST["operation"] : []),
    ], ["id" => $_POST["refSettingsId"]]);

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

if (!empty($_POST["delete_ref_setting"]) && $_POST["form_key"] == $_SESSION["ref_settings_form_key"]) {
    $db_connect->delete("referral_settings", ["id" => $_POST["id"]]);

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

$referralSettings = $db_connect->select("referral_settings", "*");
$groups = $db_connect->select("roles", "*");

foreach ($referralSettings as $key => &$referralSetting) {
    $referralSetting[$lang["datatable"]["uniq_id"]] = $key + 1;
    $referralSetting[$lang["datatable"]["ref_operations"]] = implode(", ", json_decode($referralSetting["operations"] ?? [], true));
    $referralSetting[$lang["datatable"]["group_name"]] = $referralSetting["object_name"];
    $referralSetting[$lang["datatable"]["ref_object_type"]] = $referralSetting["object_type"];
    $referralSetting[$lang["datatable"]["discount_percent"]] = $referralSetting["discount_percent"];
    $referralSetting[$lang["datatable"]["discount_sum"]] = $referralSetting["discount_sum"];

    $referralSetting[$lang["datatable"]["actions"]] = "<button type='button' class='mx-1 bg-transparent border editRef' data-id='{$referralSetting['id']}' onclick='largeModal(`refSettingsEditForm`)'><i class='fa fa-edit'></i></button>
                        <form method='POST' action='/admin?action=referral-settings' style='display:inline;'>
                            <input type='hidden' name='form_key' value='{$_SESSION['ref_settings_form_key']}'>
                            <input type='hidden' name='id' value='{$referralSetting['id']}'>
                            <input type='hidden' name='delete_ref_setting' value='1'>
                            <button type='submit' class='no-b mx-1' onclick='return confirm(`Вы уверены, что хотите удалить настройку?`);'>
                                <i class='fa fa-trash'></i>
                            </button>
                        </form>";
}


$smarty->registerPlugin('modifier', 'json_encode', function($value) {
    return json_encode($value);
});
// Устанавливаем массив переменных в Smarty
$yourData = array('title' => $lang['megamenu']['referralsettings'] . ' - ' . $config['title']);
$smarty->assign("referralSettings", $referralSettings);
$smarty->assign("groups", $groups);
$smarty->assign('data', $yourData);
$smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['megamenu']['referralsettings'] . '</li>
    ');
$smarty->assign('form_key', $_SESSION['ref_settings_form_key']);
$yourData = array('title' => $lang['nav']['adscategorieslist'] . ' - ' . $config['title']);
$smarty->assign('theme', SYSTEM_DIR);
$smarty->assign('config', $config);