<?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');

    global $db_connect;

    $paymentBonuses = $db_connect->select("payment_bonuses", "*");

    if (isset($_POST["save_payment_bonus"])) {
        $id = $_POST['id'] ?? null;
        $payment_system = trim($_POST['payment_system'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $type = $_POST['type'] ?? '';
        $value = floatval($_POST['value'] ?? 0);
        $currency = strtoupper(trim($_POST['currency'] ?? ''));
        $min_payment = floatval($_POST['min_payment'] ?? 0);
        $max_uses = intval($_POST['max_uses_per_user'] ?? 0);
        $active = isset($_POST['active']) ? 1 : 0;

        // валидация
        $errors = [];
        if(!$payment_system || !preg_match('/^[A-Za-z0-9_-]{2,50}$/', $payment_system)) $errors[] = 'Неверная платёжная система';
        if(!$name || strlen($name) < 3 || strlen($name) > 100) $errors[] = 'Название бонуса 3-100 символов';
        if(!in_array($type, ['percent','fixed'])) $errors[] = 'Неверный тип бонуса';
        if($value <= 0) $errors[] = 'Значение бонуса должно быть больше 0';
/*        if(!preg_match('/^[A-Z]{3}$/', $currency)) $errors[] = 'Валюта должна быть 3 заглавные буквы';*/
/*        if($min_payment < 0) $errors[] = 'Минимальная сумма не может быть меньше 0';
        if($max_uses < 0) $errors[] = 'Максимальное количество использований не может быть меньше 0';*/

        if(!empty($errors)){
            $_SESSION['error'] = implode('; ', $errors);
            header("Location: /admin?action=payment-bonuses-control");
            exit;
        }

        $data = [
            'payment_system' => $payment_system,
            'name' => $name,
            'type' => $type,
            'value' => $value,
            'currency' => $currency,
            'min_payment' => $min_payment,
            'max_uses_per_user' => $max_uses,
            'active' => $active,
            'updated_at' => date('Y-m-d H:i:s')
        ];

        if($id){
            $db_connect->update('payment_bonuses', $data, ['id' => $id]);
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $db_connect->insert('payment_bonuses', $data);
        }
        header("Location: /admin?action=payment-bonuses-control");
        exit;
    }



    foreach ($paymentBonuses as $key => &$paymentBonus) {

        $paymentBonus["actions"] = "<a href='#' id='edit-ico' class='mx-3 fa fa-edit edit-ico' data-id='{$paymentBonus['id']}'></a>
                            <a href='#' id='delete-ico' class='mx-3 fa fa-trash delete-ico' data-id='{$paymentBonus['id']}'></a>";

    }
    unset($paymentBonus);
    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });
    $smarty->assign("pattern1", "[A-Za-z0-9_-]{2,50}");
    $yourData = array('title' => "Payment Bonuses" . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('paymentBonuses', $paymentBonuses);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . "Payment Bonuses" . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);