<?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."/mods/database_helper.php");

    function createPaymentWidgetController()
    {
        global $db_connect;

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['pWidget/create'])) {
            $name = trim($_POST['name']);
            $btnName = trim($_POST['btn_name']);
            $price = floatval($_POST['price']);
            $priceModel = intval($_POST['price_model']);
            $widgetType = trim($_POST['w_type']);
            $paymentType = trim($_POST['p_type']);
            $period = trim($_POST['period']);
            $notifyFrequency = trim($_POST['notify_fr']);
            $limit = intval($_POST['limit']);
            $templateName = trim($_POST['template_name']);
            $superDonatSum = trim($_POST['super_donater_sum']);

            $settings = [
                "email_template" => $_POST['email_template'] == "" ? false : $_POST['email_template'],
                "statistic_counter" => $_POST["statistic_counter"] == "true",
                "account_required" => $_POST["account_required"] == "true",
                "success_url" => $_POST["success_url"],
                "error_url" => $_POST["error_url"],
                "api_key" => $_POST["api_key"],
                "group_field" => $_POST["group_field"],
                "redirect_to_registration" => $_POST["redirect_to_registration"] == "true",
            ];

            $errors = [];
           /* if (empty($name)) {
                $errors[] = 'Название виджета обязательно для заполнения.';
            }*/
            /*if ($price <= 0) {
                $errors[] = 'Цена должна быть положительным числом.';
            }*/
            if (!in_array($priceModel, [0, 1])) {
                $errors[] = 'Неверный тип ценообразования.';
            }
            if (!in_array($widgetType, ['sale', 'pay_for_hidden_data', 'donate', 'subscription'])) {
                $errors[] = 'Неверный тип виджета.';
            }
            if (!in_array($paymentType, ['one_time', 'recurring'])) {
                $errors[] = 'Неверный тип оплаты.';
            }
            if (!in_array($period, ['once', 'daily', 'weekly', 'monthly', 'yearly'])) {
                $errors[] = 'Неверный периодичности.';
            }
            if (!in_array($notifyFrequency, ['once', 'daily', 'weekly'])) {
                $errors[] = 'Неверная частота уведомлений.';
            }
            if ($limit < 0) {
                $errors[] = 'Лимит операций должен быть неотрицательным числом.';
            }
            if (empty($templateName)) {
             //   $errors[] = 'Название шаблона обязательно для заполнения.';
            }


            if (!empty($errors)) {
                foreach ($errors as $error) {
                    echo "<p style='color:red;'>$error</p>";
                }
                exit;
            }
            $stmt = $db_connect->insert("payment_widgets", array(
               "s_date" => date("Y-m-d H:i:s"),
               "uniq_name" => generateUniqueCode(),
               "name" => $name,
               "price" => (int)$price ?? 0,
               "price_model" => $priceModel,
               "w_type" => $widgetType,
               "period" => $period,
               "notify_fr" => $notifyFrequency,
               "limit" => (int)$limit ?? 0,
               "template_name" => $templateName,
               "p_type" => $paymentType,
               "disable_promo" => $_POST["disable_promo"] == "true",
               "disable_delivery" => $_POST["disable_delivery"] == "true",
               "super_donater_sum" => (int)$superDonatSum ?? 0,
               "disable_title" => $_POST["disable_title"] == "true",
               "pay_with_redirect" => $_POST["pay_with_redirect"] == "true",
               "disable_sum_input" => $_POST["disable_sum_input"] == "true",
               "btn_text" => $btnName,
               "settings" => json_encode($settings)
            ));

            $widgetId = $db_connect->id();

            foreach ($_POST["translations"] as $lng => $translationAssoc) {
                foreach ($translationAssoc as $k => $v) {
                    $db_connect->insert("widgets_translations", [
                        "widget_id" => $widgetId,
                        "widget_type" => "payment_widget",
                        "lang_code" => $lng,
                        "name" => $k,
                        "value" => $v,
                    ]);
                }
            }
            if ($widgetType == "subscription") {
                $db_connect->insert("subscriptions", [
                    "name" => $name,
                    "widget_id" => $db_connect->id(),
                    "duration_days" => 0
                ]);
            }


            if ($stmt) {
                header("Location: /admin?action=widgets/payments/list");
                exit;
            } else {
                echo "<p style='color:red;'>Ошибка создания виджета: " . $stmt->error . "</p>";
            }

        }

    }

    function generateUniqueCode() {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $code = '';

        for ($i = 0; $i < 5; $i++) {
            $code .= $characters[random_int(0, strlen($characters) - 1)];
        }

        return $code;
    }

    function updatePaymentWidgetController()
    {
        global $db_connect;

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['pWidget/edit'])) {
            $id = $_POST["id"];
            $name = trim($_POST['name']);
            $price = floatval($_POST['price']);
            $priceModel = intval($_POST['price_model']);
            $widgetType = trim($_POST['w_type']);
            $paymentType = trim($_POST['p_type']);
            $period = trim($_POST['period']);
            $notifyFrequency = trim($_POST['notify_fr']);
            $limit = intval($_POST['limit']);
            $templateName = trim($_POST['template_name']);
            $superDonatSum = trim($_POST['super_donater_sum']);
            $btnName = trim($_POST['btn_name']);

            $settings = [
                "email_template" => $_POST['email_template'] == "" ? false : $_POST['email_template'],
                "statistic_counter" => $_POST["statistic_counter"] == "true",
                "account_required" => $_POST["account_required"] == "true",
                "success_url" => $_POST["success_url"],
                "error_url" => $_POST["error_url"],
                "api_key" => $_POST["api_key"],
                "group_field" => $_POST["group_field"],
                "redirect_to_registration" => $_POST["redirect_to_registration"] == "true",
            ];

            $errors = [];
         /*   if (empty($name)) {
                $errors[] = 'Название виджета обязательно для заполнения.';
            }*/
           /* if ($price <= 0) {
                $errors[] = 'Цена должна быть положительным числом.';
            }*/
            if (!in_array($priceModel, [0, 1])) {
                $errors[] = 'Неверный тип ценообразования.';
            }
            if (!in_array($widgetType, ['sale', 'pay_for_hidden_data', 'donate', 'subscription'])) {
                $errors[] = 'Неверный тип виджета.';
            }
            if (!in_array($paymentType, ['one_time', 'recurring'])) {
                $errors[] = 'Неверный тип оплаты.';
            }
            if (!in_array($period, ['once', 'daily', 'weekly', 'monthly', 'yearly'])) {
                $errors[] = 'Неверный периодичности.';
            }
            if (!in_array($notifyFrequency, ['once', 'daily', 'weekly'])) {
                $errors[] = 'Неверная частота уведомлений.';
            }
            if ($limit < 0) {
                $errors[] = 'Лимит операций должен быть неотрицательным числом.';
            }
            if (empty($templateName)) {
                //$errors[] = 'Название шаблона обязательно для заполнения.';
            }

            if (!empty($errors)) {
                foreach ($errors as $error) {
                    echo "<p style='color:red;'>$error</p>";
                }
                exit;
            }

            $db_connect->update("payment_widgets", [
                "name" => $name,
                "price" => (int)$price,
                "price_model" => $priceModel,
                "w_type" => $widgetType,
                "p_type" => $paymentType,
                "period" => $period,
                "notify_fr" => $notifyFrequency,
                "limit" => (int)$limit ?? 0,
                "template_name" => $templateName,
                "disable_promo" => $_POST["disable_promo"] == "true",
                "disable_delivery" => $_POST["disable_delivery"] == "true",
                "super_donater_sum" => (int)$superDonatSum ?? 0,
                "disable_title" => $_POST["disable_title"] == "true",
                "pay_with_redirect" => $_POST["pay_with_redirect"] == "true",
                "disable_sum_input" => $_POST["disable_sum_input"] == "true",
                "btn_text" => $btnName,
                "settings" => json_encode($settings)
            ], ["id" => $id]);

            $db_connect->delete("widgets_translations", ["widget_id" => $id, "widget_type" => "payment_widget"]);

            foreach ($_POST["translations"] as $lng => $translationAssoc) {
                foreach ($translationAssoc as $k => $v) {
                    $db_connect->insert("widgets_translations", [
                        "widget_id" => $id,
                        "widget_type" => "payment_widget",
                        "lang_code" => $lng,
                        "name" => $k,
                        "value" => $v,
                    ]);
                }
            }

            header("Location: /admin?action=widgets/payments/list");

        }

    }