<?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/dbconfig.php');

	// Флаг для отслеживания успешности выполнения запросов
	$successFlag = true;
    $enabledDatabase = $config["database_settings"]["enabled_database"];
    $currentDatabaseSettings = $config["database_settings"][$enabledDatabase];
    $createTablesPG = [
        'CREATE TABLE IF NOT EXISTS products (
                id SERIAL PRIMARY KEY,
                autor VARCHAR(40) DEFAULT NULL,
                date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                language VARCHAR(190) DEFAULT NULL,
                title VARCHAR(255) DEFAULT NULL,
                image VARCHAR(255) DEFAULT NULL,
                alt_name VARCHAR(190) DEFAULT NULL,
                short_desc TEXT DEFAULT NULL,
                full_desc TEXT DEFAULT NULL,
                meta_desc VARCHAR(300) DEFAULT NULL,
                meta_keys TEXT DEFAULT NULL,
                price DECIMAL(10, 2) NOT NULL,
                stock_quantity INT NOT NULL,
                measure_unit VARCHAR(50) DEFAULT NULL,
                brand VARCHAR(100) DEFAULT NULL,
                model VARCHAR(100) DEFAULT NULL,
                sku VARCHAR(100) DEFAULT NULL,
                mass DECIMAL(10, 2) DEFAULT NULL,
                dimensions VARCHAR(100) DEFAULT NULL,
                color VARCHAR(50) DEFAULT NULL,
                material VARCHAR(100) DEFAULT NULL,
                warranty VARCHAR(100) DEFAULT NULL,
                discount DECIMAL(5, 2) DEFAULT NULL,
                promotion VARCHAR(255) DEFAULT NULL,
                min_order INT DEFAULT NULL,
                comments_numb INT DEFAULT NULL,
                views INT DEFAULT 0
            )',

        'CREATE TABLE IF NOT EXISTS products_fields (
                id SERIAL PRIMARY KEY,
                x_name VARCHAR(255) NOT NULL,
                column_type VARCHAR(255) NOT NULL,
                column_length INT DEFAULT 0
            )',

        'CREATE TABLE IF NOT EXISTS products_field_values (
                id SERIAL PRIMARY KEY,
                products_id INT NOT NULL,
                field_id INT NOT NULL,
                x_value TEXT NOT NULL,
                FOREIGN KEY (products_id) REFERENCES products(id) ON DELETE CASCADE,
                FOREIGN KEY (field_id) REFERENCES products_fields(id) ON DELETE CASCADE
            )',

        'CREATE TABLE IF NOT EXISTS products_categories (
                id SERIAL PRIMARY KEY,
                parentid INT DEFAULT NULL,
                position INT DEFAULT NULL,
                language VARCHAR(190) DEFAULT NULL,
                name VARCHAR(50) DEFAULT NULL,
                alt_name VARCHAR(50) DEFAULT NULL,
                meta_desc VARCHAR(300) DEFAULT NULL,
                meta_keys TEXT DEFAULT NULL,
                short_tpl VARCHAR(40) DEFAULT NULL,
                full_tpl VARCHAR(40) DEFAULT NULL,
                comments BOOLEAN DEFAULT NULL,
                views INT DEFAULT 0
            )',

        'CREATE TABLE IF NOT EXISTS product_colors (
                id SERIAL PRIMARY KEY,
                product_id INT NOT NULL,
                color_name VARCHAR(50) NOT NULL,
                color_hex VARCHAR(7) NOT NULL,
                image_url VARCHAR(255) NOT NULL,
                FOREIGN KEY (product_id) REFERENCES products(id)
            )',

        'CREATE TABLE IF NOT EXISTS products_cat_relations (
            products_id INT NOT NULL,
            category_id INT NOT NULL,
            PRIMARY KEY (products_id, category_id),
            CONSTRAINT fk_products
                FOREIGN KEY (products_id) REFERENCES products(id)
                ON DELETE CASCADE
                ON UPDATE CASCADE,
            CONSTRAINT fkp_category
                FOREIGN KEY (category_id) REFERENCES products_categories(id)
                ON DELETE CASCADE
                ON UPDATE CASCADE
        );'
    ];

    $createTablesMySQL = [
        'CREATE TABLE IF NOT EXISTS shops (
            shop_id INT AUTO_INCREMENT,
            shop_name VARCHAR(255) NOT NULL,
            slug VARCHAR(255) UNIQUE NOT NULL,  -- для URL
            description TEXT,
            language VARCHAR(255) DEFAULT NULL,
            owner_id INT,  -- владелец магазина (связка с users)
            location VARCHAR(255) DEFAULT NULL,
            lat VARCHAR(255) DEFAULT NULL,
            lng VARCHAR(255) DEFAULT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (shop_id)
        ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS shop_product_attributes (
            id INT AUTO_INCREMENT,
            product_id INT NOT NULL,
            name VARCHAR(255) NOT NULL,   -- например "Цвет", "Размер"
            value VARCHAR(255) NOT NULL,  -- например "Красный", "XL"
            PRIMARY KEY (id)
        ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS `shop_coupons` (
            `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
            `shop_id` INT UNSIGNED NOT NULL,                -- ID магазина, к которому привязан купон
            `code` VARCHAR(50) NOT NULL UNIQUE,            -- сам код купона
            `description` TEXT DEFAULT NULL,               -- описание купона
            `discount_type` VARCHAR(10) DEFAULT NULL, -- percent , ...
            `discount_value` DECIMAL(10,2) NOT NULL,      -- значение скидки
            `min_order_amount` DECIMAL(10,2) DEFAULT 0,   -- минимальная сумма заказа для использования купона
            `max_uses` INT UNSIGNED DEFAULT 0,            -- максимальное количество использований (0 = без лимита)
            `used_count` INT UNSIGNED DEFAULT 0,          -- сколько раз уже использован
            `start_date` DATETIME DEFAULT NULL,           -- дата начала действия
            `end_date` DATETIME DEFAULT NULL,             -- дата окончания действия
            `active` TINYINT(1) DEFAULT 1,                -- активен или нет
            `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
            `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`)
        ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS shop_products (
            id INT AUTO_INCREMENT,
            shop_id INT NOT NULL,
            category_id INT DEFAULT NULL,  -- категория, может быть NULL
            name VARCHAR(255) NOT NULL,
            slug VARCHAR(255) UNIQUE NOT NULL,
            description TEXT,
            price DECIMAL(10,2) NOT NULL,
            discount DECIMAL(10,2) DEFAULT NULL,
            language VARCHAR(255) DEFAULT NULL,
            stock INT DEFAULT 0,
            article VARCHAR(255) UNIQUE NOT NULL,
            is_active TINYINT(1) DEFAULT 1,  -- видим ли товар
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS shop_product_files (
            id INT AUTO_INCREMENT,
            product_id INT DEFAULT NULL,
            shop_id INT DEFAULT NULL,
            url VARCHAR(255) NOT NULL,
            is_main TINYINT(1) DEFAULT 0,
            file_type VARCHAR(255) NOT NULL,
            sort_order INT DEFAULT 0,
            PRIMARY KEY (id)
        ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS `shop_fields` (
                `id` INT(11) NOT NULL AUTO_INCREMENT, -- Уникальный идентификатор
                `x_name` VARCHAR(255) NOT NULL, -- Заголовок столбца в таблице
                `column_type` VARCHAR(255) NOT NULL, -- Тип столбца в таблице
                `column_length` INT DEFAULT 0, -- Длина
                PRIMARY KEY (`id`)
            ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS `shop_field_values` (
                `id` INT(11) NOT NULL AUTO_INCREMENT, -- Уникальный идентификатор
                `shop_id` INT(11) NOT NULL, -- ID новости
                `field_id` INT(11) NOT NULL, -- ID поля из products_fields
                `x_value` TEXT NOT NULL, -- Значение поля (универсальное хранилище)
                PRIMARY KEY (`id`),
                FOREIGN KEY (`shop_id`) REFERENCES `shops`(`shop_id`) ON DELETE CASCADE,
                FOREIGN KEY (`field_id`) REFERENCES `shop_fields`(`id`) ON DELETE CASCADE
            ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS `shop_categories` (
                `id` INT(11) NOT NULL AUTO_INCREMENT,
                `parentid` INT(11) DEFAULT NULL,
                `position` INT(11) DEFAULT NULL,
                `language` VARCHAR(190) DEFAULT NULL,
                `name` VARCHAR(50) DEFAULT NULL,
                `alt_name` VARCHAR(50) DEFAULT NULL,
                `meta_desc` VARCHAR(300) DEFAULT NULL,
                `meta_keys` TEXT DEFAULT NULL,
                `short_tpl` VARCHAR(40) DEFAULT NULL,
                `full_tpl` VARCHAR(40) DEFAULT NULL,
                `comments` TINYINT(1) DEFAULT NULL,
                `views` INT DEFAULT 0,
                PRIMARY KEY (`id`)
            ) ENGINE=INNODB DEFAULT CHARSET=utf8',

        'CREATE TABLE IF NOT EXISTS `shop_cat_relations` (
            `shop_id` INT DEFAULT NULL,
            `product_id` INT DEFAULT NULL, 
            `category_id` INT DEFAULT NULL,
            CONSTRAINT `fk_shop`
                FOREIGN KEY (`shop_id`) REFERENCES `shops`(`shop_id`)
                ON DELETE CASCADE
                ON UPDATE CASCADE,
            CONSTRAINT `fk_shop_product`
                FOREIGN KEY (`product_id`) REFERENCES `shop_products`(`id`)
                ON DELETE CASCADE
                ON UPDATE CASCADE,
            CONSTRAINT `fkshop_category`
                FOREIGN KEY (`category_id`) REFERENCES `shop_categories`(`id`)
                ON DELETE CASCADE
                ON UPDATE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'


    ];

    $createTables = [];
    if ($enabledDatabase == "mysql") {
        $createTables = $createTablesMySQL;
    } elseif ($enabledDatabase == "pgsql") {
        $createTables = $createTablesPG;
    }

    // Выполняем запросы на создание таблиц
    foreach ($createTables as $sql) {
        $db_connect->query($sql);
    }


    /* =======================
       1. МАГАЗИНЫ
    ======================= */
    $shops = [
        [
            'shop_name' => 'Tech Store',
            'slug' => 'tech-store',
            'description' => 'Магазин электроники',
            'language' => 'ru',
            'owner_id' => 1,
            'location' => 'Москва'
        ],
        [
            'shop_name' => 'Fashion Hub',
            'slug' => 'fashion-hub',
            'description' => 'Одежда и стиль',
            'language' => 'ru',
            'owner_id' => 2,
            'location' => 'Ереван'
        ]
    ];

    $shopIds = [];
    foreach ($shops as $shop) {
        $db_connect->insert('shops', $shop);
        $shopIds[] = $db_connect->id();
    }

    /* =======================
       2. КАТЕГОРИИ
    ======================= */
    $categories = [
        ['name' => 'Смартфоны', 'language' => 'ru'],
        ['name' => 'Ноутбуки', 'language' => 'ru'],
        ['name' => 'Одежда', 'language' => 'ru']
    ];

    $categoryIds = [];
    foreach ($categories as $cat) {
        $db_connect->insert('shop_categories', $cat);
        $categoryIds[] = $db_connect->id();
    }

    /* =======================
       3. ТОВАРЫ
    ======================= */
    $products = [
        [
            'shop_id' => $shopIds[0],
            'category_id' => $categoryIds[0],
            'name' => 'iPhone 15 Pro',
            'slug' => 'iphone-15-pro',
            'description' => 'Флагман Apple',
            'price' => 1200,
            'discount' => 100,
            'language' => 'ru',
            'stock' => 10,
            'article' => 'APL-IP15PRO'
        ],
        [
            'shop_id' => $shopIds[1],
            'category_id' => $categoryIds[2],
            'name' => 'Куртка зимняя',
            'slug' => 'winter-jacket',
            'description' => 'Тёплая зимняя куртка',
            'price' => 180,
            'discount' => null,
            'language' => 'ru',
            'stock' => 25,
            'article' => 'FSH-JCKT-01'
        ]
    ];

    $productIds = [];
    foreach ($products as $p) {
        $db_connect->insert('shop_products', $p);
        $productIds[] = $db_connect->id();
    }

    /* =======================
       4. СВЯЗИ (shop_cat_relations)
    ======================= */
    foreach ($productIds as $i => $pid) {
        $db_connect->insert('shop_cat_relations', [
            'shop_id' => $products[$i]['shop_id'],
            'product_id' => $pid,
            'category_id' => $products[$i]['category_id']
        ]);
    }

    /* =======================
       5. АТРИБУТЫ ТОВАРОВ
    ======================= */
    $attributes = [
        ['product_id' => $productIds[0], 'name' => 'Цвет', 'value' => 'Чёрный'],
        ['product_id' => $productIds[0], 'name' => 'Память', 'value' => '256GB'],
        ['product_id' => $productIds[1], 'name' => 'Размер', 'value' => 'L'],
        ['product_id' => $productIds[1], 'name' => 'Материал', 'value' => 'Полиэстер']
    ];

    foreach ($attributes as $attr) {
        $db_connect->insert('shop_product_attributes', $attr);
    }

    /* =======================
       6. ФАЙЛЫ / ИЗОБРАЖЕНИЯ
    ======================= */
    $files = [
        [
            'product_id' => $productIds[0],
         //   'shop_id' => $shopIds[0],
            'url' => '/uploads/images/shops/iphone-main.jpg',
            'is_main' => 1,
            'file_type' => 'image',
            'sort_order' => 1
        ],
        [
            'product_id' => $productIds[1],
          //  'shop_id' => $shopIds[1],
            'url' => '/uploads/images/shops/jacket-main.jpg',
            'is_main' => 1,
            'file_type' => 'image',
            'sort_order' => 1
        ],
        [
            'shop_id' => $shopIds[0],
            'url' => '/uploads/images/shops/shop-0.jpg',
            'is_main' => 1,
            'file_type' => 'image',
            'sort_order' => 1
        ],
        [
            'shop_id' => $shopIds[1],
            'url' => '/uploads/images/shops/shop-1.jpg',
            'is_main' => 1,
            'file_type' => 'image',
            'sort_order' => 1
        ]
    ];

    foreach ($files as $file) {
        $db_connect->insert('shop_product_files', $file);
    }

    /* =======================
       7. КУПОНЫ
    ======================= */
    $coupons = [
        [
            'shop_id' => $shopIds[0],
            'code' => 'TECH10',
            'description' => 'Скидка 10%',
            'discount_type' => 'percent',
            'discount_value' => 10,
            'min_order_amount' => 500,
            'max_uses' => 100,
            'start_date' => date('Y-m-d H:i:s'),
            'end_date' => date('Y-m-d H:i:s', strtotime('+30 days'))
        ],
        [
            'shop_id' => $shopIds[1],
            'code' => 'STYLE20',
            'description' => 'Минус 20%',
            'discount_type' => 'percent',
            'discount_value' => 20,
            'min_order_amount' => 100,
            'max_uses' => 50,
            'start_date' => date('Y-m-d H:i:s'),
            'end_date' => date('Y-m-d H:i:s', strtotime('+20 days'))
        ]
    ];

    foreach ($coupons as $coupon) {
        $db_connect->insert('shop_coupons', $coupon);
    }


// Проверяем флаг и выводим сообщение
	if ($successFlag) {
		echo "
			<script>
				alert('Данные модуля товаров успешно добавлены');
				window.location.href = window.location.href;
			</script>
		";
		exit();
	}
