<?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 (!empty($_POST["action"]) && $_POST["action"] == "update_application_status") {
    $db_connect->update("user_applications", [
        "status" => $_POST["status"]
    ], ["id" => $_POST["user_application_id"]]);

    if ($_POST["status"] == "accepted") {
        $acceptedGroup = $db_connect->get("user_applications", "group_id", ["id" => $_POST["user_application_id"]]);

        $db_connect->update("users", [
            "group" => $acceptedGroup
        ], ["id" => $_POST["user_id"]]);
    }

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

// Получаем список промокодов
$userApplications = $db_connect->select("user_applications", "*", [
    'ORDER' => ['id' => 'DESC']
]);

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

foreach ($userApplications as $key => &$userApplication) {

    $userInfo = $db_connect->get("users", "*", ["id" => $userApplication["user_id"]]);
    $userApplication["current_id"] = $userApplication["id"];
    $userApplication["id"] = $key + 1;
    $userApplication[$lang["datatable"]["email"]] = $userInfo["email"];
    $userApplication[$lang["datatable"]["name"]] = $userInfo["name"];
    $userApplication[$lang["datatable"]["group"]] = $db_connect->get("roles", "name", ["id" => $userInfo["group"]]);
    $userApplication[$lang["datatable"]["requested_group"]] = $db_connect->get("roles", "name", ["id" => $userApplication["group_id"]]);

    $className = "";
    $classNamePay = "";
    if ($userApplication["status"] == "progress") {
        $className = "orange";
    } elseif ($userApplication["status"] == "accepted") {
        $className = "green";
    } elseif ($userApplication["status"] == "rejected") {
        $className = "red";
    }

    if ($userApplication["payed_status"] == "paid") {
        $classNamePay = "green";
    } elseif ($userApplication["payed_status"] == "progress") {
        $classNamePay = "orange";
    }

    $transactionId = "";
    if (!empty($userApplication["json_data"])) {
        $jsonData = json_decode($userApplication["json_data"], true);
        $transactionId = !empty($jsonData["transaction_id"]) ? $jsonData["transaction_id"] : "";
    }

    $disabled = "";
    $newText = "";
    if ($userApplication["status"] == "accepted") {
        $disabled = "disabled";
        $newText = $lang["datatable"]["request_accepted"];
    } else {
        $newText = $lang["datatable"]["update_request"];
    }

    if (!empty($userApplication["payed_status"]) && $userApplication["payed_status"] == "progress") {
        $disabled = "disabled";
        $newText = $lang["datatable"]["proggres_pay"];
    }

    $userApplication[$lang["datatable"]["payed_status"]] = "<b style='color: $classNamePay'>{$userApplication['payed_status']}</b>";
    $userApplication[$lang["datatable"]["status"]] = "<b style='color: $className'>{$userApplication['status']}</b>";
    $userApplication[$lang["datatable"]["actions"]] = "<button type='button' $disabled class='mx-1 bg-transparent border' onclick='smallModal(`application-{$userApplication['current_id']}`)'>
                                    $newText
                                    </button>
                      
                      
                    <div id='application-{$userApplication['current_id']}' class='hidden'>
                    <div class='col-12'>
                        <h5 class='pb-2 border-bottom'>{$userApplication[$lang["datatable"]["email"]]}</h5>
                        <p class='pb-2 border-bottom'>{$lang["datatable"]["request_to_get_group"]} - {$userApplication[$lang["datatable"]["requested_group"]]}</p>
                        <form method='POST' action='admin?action=user-applications' class='status mt-2'>
                            <input type='hidden' name='action' value='update_application_status'>
                            <input type='hidden' name='user_application_id' value='{$userApplication['current_id']}'>
                            <input type='hidden' name='user_id' value='{$userInfo['id']}'>
                            <div class='btn-group w-100'>
                                <select name='status' class='form-select'>
                                   <option value='accepted'>{$lang["datatable"]["accept"]}</option>
                                   <option value='rejected' selected>{$lang["datatable"]["reject"]}</option>
                                </select>
                                <button type='submit' class='btn btn-outline-secondary btn-sm'>{$lang["datatable"]["update_status"]}</button>
                            </div>
                        </form>
                    </div>
                </div>
    </div>
</div>";
}
$smarty->registerPlugin('modifier', 'json_encode', function($value) {
    return json_encode($value);
});
// Устанавливаем массив переменных в Smarty
$yourData = array('title' => $lang['megamenu']['userapplications'] . ' - ' . $config['title']);
$smarty->assign("userApplications", $userApplications);
$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);
?>
