<?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 `products` (
			`id` INT(11) NOT NULL AUTO_INCREMENT,
			`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` MEDIUMTEXT DEFAULT NULL,
			`full_desc` MEDIUMTEXT 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,
			PRIMARY KEY (`id`)
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    'CREATE TABLE IF NOT EXISTS `products_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 `products_field_values` (
			`id` INT(11) NOT NULL AUTO_INCREMENT, -- Уникальный идентификатор
			`products_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 (`products_id`) REFERENCES `products`(`id`) ON DELETE CASCADE,
			FOREIGN KEY (`field_id`) REFERENCES `products_fields`(`id`) ON DELETE CASCADE
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    'CREATE TABLE IF NOT EXISTS `products_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 `product_colors` (
			id INT AUTO_INCREMENT 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)
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    '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
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'


];

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

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

// Массив с запросами на добавление данных в таблицы
$addData = [
    [
        'autor' => 'Admin',
        'date' => 'NOW()',
        'language' => 'russian',
        'title' => 'Мощный смартфон XYZ-3000',
        'image' => 'uploads/images/products/2024/2/1/image.jpg',
        'alt_name' => 'product-1',
        'short_desc' => 'short description',
        'full_desc' => 'full description',
        'meta_desc' => '1',
        'meta_keys' => '1',
        'price' => 599.99,
        'stock_quantity' => 50,
        'measure_unit' => 'шт',
        'brand' => NULL,
        'model' => NULL,
        'sku' => 'MBH29182',
        'mass' => 0.15,
        'dimensions' => NULL,
        'color' => 'black',
        'material' => NULL,
        'warranty' => '1 year',
        'discount' => NULL,
        'promotion' => NULL,
        'min_order' => 10,
        'comments_numb' => 0,
        'views' => 0
    ],
    // Добавьте другие записи, аналогично выше
];

// Добавление данных в таблицу `products`
foreach ($addData as $data) {
    $db_connect->insert('products', $data);
}

$products_categories = [
    ['id' => 1, 'parentid' => 0, 'position' => 1, 'language' => 'Russian', 'name' => 'Электроника', 'alt_name' => 'electronic', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 2, 'parentid' => 1, 'position' => 2, 'language' => 'Russian', 'name' => 'Телефоны', 'alt_name' => 'phones', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 3, 'parentid' => 1, 'position' => 3, 'language' => 'Russian', 'name' => 'Компьютеры', 'alt_name' => 'computers', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 4, 'parentid' => 1, 'position' => 4, 'language' => 'Russian', 'name' => 'Аудио и Звуки', 'alt_name' => 'audio', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 5, 'parentid' => 1, 'position' => 5, 'language' => 'Russian', 'name' => 'Фото и Видео', 'alt_name' => 'media', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 6, 'parentid' => 1, 'position' => 6, 'language' => 'Russian', 'name' => 'Безопасность и защита', 'alt_name' => 'safety', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 7, 'parentid' => 0, 'position' => 7, 'language' => 'Russian', 'name' => 'Мебель', 'alt_name' => 'furniture', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 8, 'parentid' => 7, 'position' => 8, 'language' => 'Russian', 'name' => 'Домашняя', 'alt_name' => 'home', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 9, 'parentid' => 7, 'position' => 9, 'language' => 'Russian', 'name' => 'Офисная', 'alt_name' => 'office', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 10, 'parentid' => 0, 'position' => 10, 'language' => 'Russian', 'name' => 'Одежда', 'alt_name' => 'clothes', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 11, 'parentid' => 10, 'position' => 11, 'language' => 'Russian', 'name' => 'Женская', 'alt_name' => 'womans', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 12, 'parentid' => 10, 'position' => 12, 'language' => 'Russian', 'name' => 'Мужская', 'alt_name' => 'mans', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1],
    ['id' => 13, 'parentid' => 10, 'position' => 13, 'language' => 'Russian', 'name' => 'Детская', 'alt_name' => 'kids', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_products.tpl', 'full_tpl' => 'full_products.tpl', 'comments' => 1]
];

// Вставка данных в таблицу `products_categories`
foreach ($products_categories as $category) {
    $db_connect->insert('products_categories', $category);
}

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