<?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');
    $module_entity = 'shop';

    // Макс. ограничения
    $maxVideoSize     = 300 * 1024 * 1024; // 300 MB
    $maxVideoDuration = 180;               // 3 минуты в секундах

    $action = isset($_GET['action']) ? $_GET['action'] : 'main';
    $categories = [];
    $result = $db_connect->select("shop_categories", "*") ?? [];
    if (!empty($result["id"])) {
        $categories[] = $result;
    } else {
        foreach ($result as $row) {
            $categories[] = $row;
        }
    }

    if ($_SERVER["REQUEST_METHOD"] == "POST" && $action == 'modules/shops/edit') {
        // Обработка POST-запроса для сохранения изменений страницы
        if (isset($_POST['page_id'])) {
            $page_id = $_POST['page_id'];
            $folder = $_POST['folder'] ?? '';
            require_once ENGINE_DIR."/mods/compress_images.php";

            // Подготовка запроса на добавление в таблицу shops_field_values
            $x_values = isset($_POST['x_value']) ? implode(', ', $_POST['x_value']) : '';
            $field_ids = $_POST['field_ids'] ?? [];
            $shop_id = $page_id;

            // Добавляем в базу данные для каждого дополнительного поля
            if (!empty($field_ids)) {
                foreach ($field_ids as $field_id) {
                    if (!empty($_POST['x_value'][$field_id])) {
                        $insertField = $db_connect->insert("shop_field_values", [
                            "shop_id" => $shop_id,
                            "field_id" => $field_id,
                            "x_value" => $_POST['x_value'][$field_id]
                        ]);
                    }
                }
            }

            $shop_id = $_POST['page_id'];

            // 1. Удаляем отмеченные на фронтенде
                if (!empty($_POST['deleted_images'])) {
                $deleted = explode(',', $_POST['deleted_images']);
                foreach ($deleted as $id) {
                    $file = $db_connect->get("shop_product_files", "*", ["id" => $id]);
                    if ($file) {
                        $path = $_SERVER["DOCUMENT_ROOT"] . $file['url'];
                        if (file_exists($path)) unlink($path); // удаляем файл с диска
                        $db_connect->delete("shop_product_files", ["id" => $id]); // удаляем из БД
                    }
                }
            }

            // 2. Обновляем главный файл
            $mainIndex = isset($_POST['is_main_image']) ? (int)$_POST['is_main_image'] : 0;

            // Получаем все существующие картинки после удаления
            $existingImages = $db_connect->select("shop_product_files", "*", ["shop_id" => $shop_id, "file_type" => "image"]);

            foreach ($existingImages as $idx => $img) {
                $isMain = ($idx === $mainIndex) ? 1 : 0;
                $db_connect->update("shop_product_files", ["is_main" => $isMain], ["id" => $img['id']]);
            }

            if (!empty($_FILES['shop_images']['name'][0])) {
                foreach ($_FILES['shop_images']['name'] as $i => $originalName) {
                    if ($_FILES['shop_images']['error'][$i] !== UPLOAD_ERR_OK) continue;

                    $tmp_name = $_FILES['shop_images']['tmp_name'][$i];
                    if (!is_uploaded_file($tmp_name)) continue;

                    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                    $filename = time() . "_" . rand(1000, 9999) . "." . $ext;

                    $uploadDir = $_SERVER["DOCUMENT_ROOT"] . "/uploads/images/shops/shop/" . $shop_id . "/";
                    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                    if (!is_writable($uploadDir)) continue;

                    $fullPath = $uploadDir . $filename;

                    // Если WebP — просто перемещаем
                    if ($ext === 'webp') {
                        move_uploaded_file($tmp_name, $fullPath);
                        $webpFilename = $filename;
                    } else {
                        // Перемещаем исходник
                        move_uploaded_file($tmp_name, $fullPath);

                        // Конвертируем в WebP
                        $webpFilename = preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $filename);
                        $webpFullPath = $uploadDir . $webpFilename;
                        autoOptimizeWebP($fullPath, $webpFullPath, 1200, 0); // ширина 1200px

                        // Удаляем исходник
                        @unlink($fullPath);
                    }

                    // Если mainIndex указывает на новую картинку
                    $isMain = (count($existingImages) + $i === $mainIndex) ? 1 : 0;

                    // Сохраняем путь WebP в БД
                    $db_connect->insert("shop_product_files", [
                        "shop_id" => $shop_id,
                        "url" => "/uploads/images/shops/shop/$shop_id/" . $webpFilename,
                        "is_main" => $isMain,
                        "file_type" => "image"
                    ]);
                }
            }


            // 0) Обработка удалённых видео
            if (!empty($_POST['deleted_videos'])) {
                $deletedVideos = explode(',', $_POST['deleted_videos']);
                foreach ($deletedVideos as $videoId) {
                    // Получаем путь к файлу из БД
                    $video = $db_connect->get("shop_product_files", "*", ["id" => $videoId, "shop_id" => $shop_id, "file_type" => "video"]);
                    if ($video) {
                        $filePath = $_SERVER["DOCUMENT_ROOT"] . $video['url'];
                        if (file_exists($filePath)) {
                            @unlink($filePath); // удаляем файл
                        }
                        // Удаляем запись из БД
                        $db_connect->delete("shop_product_files", ["id" => $videoId]);
                    }
                }
            }

            // 1) Обработка новых видео
            if (!empty($_FILES['shop_videos']) && !empty($_FILES['shop_videos']['name'][0])) {
                foreach ($_FILES['shop_videos']['name'] as $i => $originalName) {

                    if ($_FILES['shop_videos']['error'][$i] !== UPLOAD_ERR_OK) continue;

                    $tmp_name = $_FILES['shop_videos']['tmp_name'][$i];
                    if (!is_uploaded_file($tmp_name)) continue;

                    // Проверка размера
                    $size = (int)$_FILES['shop_videos']['size'][$i];
                    if ($size > $maxVideoSize) continue;

                    // Проверка расширения
                    $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                    $allowedExt = ['mp4','mov','webm','avi','mkv'];
                    if (!in_array($ext, $allowedExt, true)) continue;

                    // Сохранение файла
                    $filename  = time() . "_" . rand(1000, 9999) . "." . $ext;
                    $uploadDir = $_SERVER["DOCUMENT_ROOT"] . "/uploads/videos/shops/shop/" . $shop_id . "/";
                    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                    if (!is_writable($uploadDir)) continue;

                    $fullPath = $uploadDir . $filename;
                    if (!move_uploaded_file($tmp_name, $fullPath)) continue;

                    // Запись в БД
                    $db_connect->insert("shop_product_files", [
                        "shop_id" => $shop_id,
                        "url"     => "/uploads/videos/shops/shop/$shop_id/" . $filename,
                        "is_main" => 0,
                        "file_type" => "video"
                    ]);
                }
            }



            $stmt = $db_connect->update("shops", [
                "shop_name" => $_POST['shop_name'],
                "slug" => $_POST['slug'],
                "description" => $_POST['description'],
                "lat" => $_POST["location_lat"],
                "lng" => $_POST["location_lng"],
                "location" => $_POST["location_address"],
            ], ["shop_id" => $page_id]);

            $db_connect->delete("shop_cat_relations", ["shop_id" => (int)$shop_id]);

            if (!empty($_POST["category"])) {
                foreach ($_POST["category"] as $categoryId) {
                    $db_connect->insert("shop_cat_relations", [
                        "shop_id" => (int)$shop_id,
                        "category_id" => (int)$categoryId,
                    ]);
                }
            }


            if ($stmt) {
                header("Location: /admin?action=modules/shops/list");
                exit();
            } else {
                echo "Ошибка подготовки запроса: " . mysqli_error($db_connect);
                exit();
            }


        } else {
            echo "Ошибка: ID страницы не указан.";
            exit();
        }
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET" && $action == 'modules/shops/edit') {
        // Обработка GET-запроса для отображения страницы редактирования
        if (isset($_GET['id'])) {
            $page_id = $_GET['id'];
            // Подключаем дополнительные поля
            require_once(SYSTEM_DIR . '/plugins/extra_fields.php');
            require_once ENGINE_DIR.'/mods/get_module_categories.php';

            $stmt = $db_connect->select("shops", "*", ["shop_id" => $page_id]);

            if ($stmt) {
                $result = $stmt;
                if ($result) {
                    $page = $result[0];

                    $page["shop_images"] = $db_connect->select("shop_product_files", "*", ["shop_id" => $page_id, "file_type" => "image"]) ?? [];
                    $page["shop_videos"] = $db_connect->select("shop_product_files", "*", ["shop_id" => $page_id, "file_type" => "video"]) ?? [];

                    foreach ($page["shop_videos"] as &$video) {
                        $video["thumb"] = str_replace(["videos", "mp4", "shops/", "shop/", $page_id."/"], ["thumbs", "mp4.jpg", "", "", ""], $video["url"]);
                    }

                    $smarty->assign('page', $page);
                    $selectedCategories = getCategoriesIds($page["shop_id"], "shop");
                    $smarty->assign('selectedCategories', $selectedCategories);

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

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