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

    $action = isset($_GET['action']) ? $_GET['action'] : 'main';

    if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'page_edit') {
        // Обработка POST-запроса для сохранения изменений страницы
        if (isset($_POST['page_id'])) {
            $page_id = $_POST['page_id'];
            $date = isset($_POST['date']) && !empty($_POST['date']) ? strip_tags(trim($_POST['date'])) : date($config['date_format']);
            $title = $_POST['title'];
            $language = isset($_POST['language']) ? (is_array($_POST['language']) ? implode(', ', $_POST['language']) : $_POST['language']) : '';
            $full_desc = htmlspecialchars($_POST['full_desc'], ENT_QUOTES);
            $alt_name = $_POST['alt_name'];
            $meta_keys = $_POST['meta_keys'];
            $meta_desc = $_POST['meta_desc'];
            $views = isset($_POST['views']) ? intval($_POST['views']) : 0;
            $full_meta_desc = htmlspecialchars($_POST['full_desc'], ENT_QUOTES);;

            if ($_POST["show_select_widget"] === "on") {
                if (str_contains($full_desc, "{payment-widget}") || str_contains($full_desc, "{ payment-widget }")) {

                    $widget = $db_connect->get("payment_widgets", "*", ["id" => $_POST["selected_widget"]]);

                    if (!empty($widget)) {
                        $oldWidget = $db_connect->get("widget_objects", "id", [
                            "object_id" => $page_id,
                        ]);
                        if (!empty($oldWidget)) {
                            $db_connect->delete("widget_objects", ["id" => $oldWidget]);
                        }

                        $db_connect->insert("widget_objects", [
                            "object_name" => $alt_name,
                            "object_id" => $page_id,
                            "widget_name" => $widget["template_name"],
                            "widget_id" => $widget["id"],
                            "active" => 1
                        ]);

                      /*  $smarty->assign("currency", getCurrentCurrency());

                        $moduleName = $alt_name;
                        $moduletype["id"] = $page_id;
                        require_once(ENGINE_DIR . '/mods/widget-select.php');
                        $smarty->assign('dynamicName', "pages");
                        $smarty->assign('price', $widget["price"]);
                        $smarty->assign('widgetId', $widget["id"]);

                        $html = $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/payments-widgets/' . $widget["template_name"] . ".tpl");
                        $full_desc = preg_replace('/\{\s*payment-widget\s*\}/', $html, $full_desc);*/
                    }
                }

            } else {
                $oldWidget = $db_connect->get("widget_objects", "id", [
                    "object_id" => $page_id,
                ]);
                if (!empty($oldWidget)) {
                    $db_connect->delete("widget_objects", ["id" => $oldWidget]);
                }
                $full_desc = preg_replace('/\{\s*payment-widget\s*\}/', "", $full_desc);
            }

            $stmt = $db_connect->update("static_pages", [
                'date' => $date,
                'title' => $title,
                'language' => $language,
                'full_desc' => $full_desc,
                'alt_name' => $alt_name,
                'meta_keys' => $meta_keys,
                'meta_desc' => $meta_desc,
                "full_meta_desc" => $full_meta_desc,
            ], ["id" => $page_id]);


            if ($stmt) {
                header("Location: /admin?action=pages");
                exit();
            } else {
                echo "Ошибка подготовки запроса: " . mysqli_error($db_connect);
                exit();
            }
        } else {
            echo "Ошибка: ID страницы не указан.";
            exit();
        }
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET" && $action == 'page_edit') {
        // Обработка GET-запроса для отображения страницы редактирования
        if (isset($_GET['id'])) {
            $page_id = $_GET['id'];

            $page = $db_connect->get("static_pages", "*", ["id" => $page_id]);
            $oldWidgetId = $db_connect->get("widget_objects", "widget_id", [
                "object_id" => $page_id,
            ]);

            if ($page) {
                $smarty->assign('page', $page);
                $smarty->assign('oldWidgetId', $oldWidgetId);

                $selectedLanguages = explode(", ", $page['language']);
                $smarty->assign('selectedLanguages', $selectedLanguages);
            } else {
                // Если страница не найдена, выдаем ошибку
                echo "Ошибка: Страница не найдена.";
                exit();
            }
        } else {
            // В случае ошибки выводим сообщение
            echo "Ошибка подготовки запроса: " . mysqli_error($db_connect);
            exit();
        }
    }

    $widgets = $db_connect->select("payment_widgets", "*");


// Устанавливаем массив переменных в Smarty
    $smarty->assign('add_page', 'add_page');
    $smarty->assign('page_id', $page_id);
    $smarty->assign('p_widgets', $widgets);
    $smarty->assign('stmt', "");
    $yourData = array('title' => $lang['nav']['pageedit'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/admin?action=pages">Страницы</a></li>
        <li class="breadcrumb-item active">Редактирование страницы</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);