<?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 . '/data/config.php');
    $module_entity = 'shop';
    require_once(SYSTEM_DIR . '/plugins/reserved_urls.php');
    require_once ENGINE_DIR.'/mods/get_module_categories.php';

    // Получаем категории
    $categories = [];
    $resultC = $db_connect->select("shop_categories", "*") ?? [];
    foreach ($resultC as $row) {
        $categories[] = $row;
    }

    // Инициализация переменных
    $error_message = '';
    $product_id = $_GET['product_id'] ?? null;
    $shop_id = $db_connect->get("shop_products", "shop_id", ["id" => $product_id]) ?? 0;

    // Получаем магазин
    $shop = $db_connect->get("shops", "*", ["shop_id" => $shop_id]);
    $categories = [];
    $result = $db_connect->select("shop_categories", "*") ?? [];
    if (!empty($result["id"])) {
        $categories[] = $result;
    } else {
        foreach ($result as $row) {
            $categories[] = $row;
        }
    }
    // Получаем данные товара для редактирования
    $product = [];
    if ($product_id) {
        $product = $db_connect->get("shop_products", "*", ["id" => $product_id]);
        $product_images = $db_connect->select("shop_product_files", "*", ["product_id" => $product_id]) ?? [];

        $product["attributes"] = $db_connect->select("shop_product_attributes", "*", ["product_id" => $product_id]);

        $selectedCategories = getCategoriesIds($product_id, "shop", "product");
        $smarty->assign('selectedCategories', $selectedCategories);
    }

    // Функция генерации артикула
    function generateSKU() {
        $letter = chr(random_int(65, 90));
        $numbers = str_pad((string)random_int(0, 9999999), 7, '0', STR_PAD_LEFT);
        return $letter . $numbers;
    }

    // Обработка формы
    if (isset($_POST['save_shop_product'])) {
        $data = [
            "shop_id" => $shop_id,
            "name" => $_POST['name'] ?? '',
            "slug" => $_POST['slug'] ?? '',
            "price" => $_POST['price'] ?? 0,
            "stock" => $_POST['stock'] ?? 0,
            "is_active" => $_POST['is_active'] ?? 0,
            "description" => $_POST['description'] ?? ''
        ];

        if (!$product_id) {
            $data['article'] = generateSKU();
            $db_connect->insert("shop_products", $data);
            $product_id = $db_connect->id();
        } else {
            $db_connect->update("shop_products", $data, ["id" => $product_id]);
        }

        $existingAttributes = $db_connect->select("shop_product_attributes", ["id"], ["product_id" => $product_id]);
        $existingIds = array_column($existingAttributes, "id");

        $postedAttributes = $_POST['attributes'] ?? [];
        $postedIds = array_column($postedAttributes, "id"); // если в форме добавим скрытое поле attribute_id для редактирования

        $toDelete = array_diff($existingIds, $postedIds);
        if (!empty($toDelete)) {
            $db_connect->delete("shop_product_attributes", ["id" => $toDelete]);
        }

        foreach ($postedAttributes as $attr) {
            if (!empty($attr['id'])) {
                $db_connect->update("shop_product_attributes", [
                    "name" => $attr['name'],
                    "value" => $attr['value']
                ], ["id" => $attr['id']]);
            } else {
                $db_connect->insert("shop_product_attributes", [
                    "product_id" => $product_id,
                    "name" => $attr['name'],
                    "value" => $attr['value']
                ]);
            }
        }
        $db_connect->delete("shop_cat_relations", ["product_id" => (int)$product_id]);

        if (!empty($_POST["category"])) {
            foreach ($_POST["category"] as $categoryId) {
                $db_connect->insert("shop_cat_relations", [
                    "product_id" => (int)$product_id,
                    "category_id" => (int)$categoryId,
                ]);
            }
        }
        if (!empty($_FILES['images']['name'][0])) {
            foreach ($_FILES['images']['name'] as $i => $originalName) {
                if ($_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) continue;

                $tmp_name = $_FILES['images']['tmp_name'][$i];
                $ext = pathinfo($originalName, PATHINFO_EXTENSION);
                $filename = time() . "_" . rand(1000, 9999) . "." . $ext;
                $uploadDir = $_SERVER["DOCUMENT_ROOT"] . "/uploads/images/shops/" . $product_id . "/";
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                move_uploaded_file($tmp_name, $uploadDir . $filename);

                $db_connect->insert("shop_product_files", [
                    "product_id" => $product_id,
                    "url" => "/uploads/images/shops/$product_id/".$filename
                ]);
            }
        }

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

    // Подключаем дополнительные поля
    require_once(SYSTEM_DIR . '/plugins/extra_fields.php');
    $groups = $db_connect->select("roles", "*") ?? [];
    $smarty->assign('groups', $groups);

    // Подготовка переменных для шаблона
    $smarty->assign('categories', $categories);
    $smarty->assign('shop', $shop);
    $smarty->assign('product', $product);
    $yourData = array('title' => 'Редактирование товара' . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('product_images', $product_images ?? []);
    $smarty->assign('error_message', $error_message);
    $smarty->assign('page_name', '
            <li class="breadcrumb-item active"><a href="/admin?action=shops/list">Онлайн магазины</a></li>
            <li class="breadcrumb-item active">' . ($product_id ? 'Редактировать товар' : 'Добавить товар') . '</li>
        ');
    $smarty->assign('edit_page', true);
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);
