<?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.                                                      *
            *****************************************************************************
        */

    function addObjectShopController()
    {
        global $smarty, $config, $db_connect, $lang, $user_authenticated;

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

        $user = $db_connect->get("users", "*", ["email" => $_SESSION["user_email"] ?? null]);

        if (!$user) {
            // Пользователь не найден
            $smarty->assign('error_message', 'У вас нет доступа к этой странице');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
        } else {

            $module_entity = "shop";
            require_once(SYSTEM_DIR . '/plugins/reserved_urls.php');

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

            $error_message = '';

            // Обработка формы добавления файла
            if (isset($_POST['addshop'])) {
                $folder = $_POST['folder'] ?? '';
                $p_id = (int)$db_connect->max("shops", "shop_id") + 1;

                // Подготовка запроса на добавление в таблицу coupons_field_values
                $x_values = isset($_POST['x_value']) ? implode(', ', $_POST['x_value']) : '';
                $field_ids = $_POST['field_ids'] ?? [];
                $shop_id = $p_id;
                if (!empty($_FILES['shop_images']['name'][0])) {
                    $mainIndex = isset($_POST['is_main_image']) ? (int)$_POST['is_main_image'] : 0;

                    require_once ENGINE_DIR."/mods/compress_images.php";

                    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);
                        }

                        // Флаг главного фото
                        $isMain = ($i === $mainIndex) ? 1 : 0;

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

                    // ----------------- ВИДЕО -----------------
                    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;
                            }

                            // 1) ПРОВЕРКА РАЗМЕРА (<= 300MB)
                            $size = (int)$_FILES['shop_videos']['size'][$i];
                            if ($size > $maxVideoSize) {
                                // Можно записать ошибку в лог / показать сообщение
                                // например: "Видео превышает 300MB"
                                continue;
                            }

                            // 2) ПРОВЕРКА ТИПА ФАЙЛА (расширение + MIME по-хорошему)
                            $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                            $allowedExt = ['mp4','mov','webm','avi','mkv'];

                            if (!in_array($ext, $allowedExt, true)) {
                                continue;
                            }

                            // 4) Сохранение файла
                            $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;
                            }

                            // 5) Запись в БД
                            // Если у тебя отдельная таблица для видео – поменяй название.
                            // Если всё хранится в той же shop_product_files, можно пометить как видео через отдельное поле, если оно есть.
                            $db_connect->insert("shop_product_files", [
                                "shop_id" => $shop_id,
                                "url"     => "/uploads/videos/shops/shop/$shop_id/" . $filename,
                                "is_main" => 0,
                                "file_type" => "video"
                            ]);
                        }
                    }

                }



                $result = $db_connect->insert("shops", [
                    "owner_id" => $_SESSION['user_id'],
                    "shop_name" => $_POST['shop_name'],
                    "slug" => $_POST['slug'],
                    "description" => $_POST['description'],
                    "lat" => $_POST["location_lat"],
                    "lng" => $_POST["location_lng"],
                    "location" => $_POST["location_address"],
                ]);

                $shopData = $db_connect->get("shops", "*", ["shop_id" => $db_connect->id()]) ?? [];

                header("Location: /shops/{$shopData['slug']}");

            }


            $lastRow = $db_connect->get("shops", ['shop_id'], [
                "ORDER" => ["shop_id" => "DESC"] // Сортировка по убыванию id
            ]);

            require_once(SYSTEM_DIR . '/plugins/extra_fields.php');
            $smarty->assign("selectedModuleAdd", "shops");

            $smarty->assign('title', 'Add shop - MDS');
            $smarty->assign('page_name', '
                                        <li class="breadcrumb-item active"><a href="/shops/products">Shop</a></li>
                                    ');
            $smarty->assign('add_page', 'add_page');
            $smarty->assign('page_id', $lastRow["id"] ?? 0 + 1);
            $smarty->assign('max_id', 0 + 1);
            /*        $smarty->assign('theme', SYSTEM_DIR);*/
            $smarty->assign('config', $config);
            $smarty->assign('categories', $categories);
            /*        $smarty->assign('error_message', $error_message);*/
            $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/modules/shops/add.tpl'));
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/main.tpl');

            exit;

        }
    }