<?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 files (
        id SERIAL PRIMARY KEY,
        autor VARCHAR(40) DEFAULT NULL,
        date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        language VARCHAR(190) DEFAULT NULL,
        title VARCHAR(255) DEFAULT NULL,
        file_path 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,
        price NUMERIC(10, 2) DEFAULT 0.00,
        version VARCHAR(50) DEFAULT NULL,
        license VARCHAR(255) DEFAULT NULL,
        contact_info VARCHAR(255) DEFAULT NULL,
        meta_desc VARCHAR(300) DEFAULT NULL,
        meta_keys TEXT DEFAULT NULL,
        views INT DEFAULT 0
    )",
    "CREATE TABLE IF NOT EXISTS files_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 files_field_values (
        id SERIAL PRIMARY KEY,
        files_id INT NOT NULL,
        field_id INT NOT NULL,
        x_value TEXT NOT NULL,
        FOREIGN KEY (files_id) REFERENCES files(id) ON DELETE CASCADE,
        FOREIGN KEY (field_id) REFERENCES files_fields(id) ON DELETE CASCADE
    )",
    "CREATE TABLE IF NOT EXISTS files_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 files_cat_relations (
        files_id INT NOT NULL,
        category_id INT NOT NULL,
        PRIMARY KEY (files_id, category_id),
        CONSTRAINT fk_files
            FOREIGN KEY (files_id) REFERENCES files(id)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
        CONSTRAINT fkf_category
            FOREIGN KEY (category_id) REFERENCES files_categories(id)
            ON DELETE CASCADE
            ON UPDATE CASCADE
    );'
];

$createTablesMySQL = [
    'CREATE TABLE IF NOT EXISTS `files` (
			`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,
			`file_path` VARCHAR(255) DEFAULT NULL,
			`image` VARCHAR(255) DEFAULT NULL,
			`alt_name` VARCHAR(190) DEFAULT NULL, -- Альтернативное имя (URL)
			`short_desc` MEDIUMTEXT DEFAULT NULL,
			`full_desc` MEDIUMTEXT DEFAULT NULL,
			`price` DECIMAL(10, 2) DEFAULT 0.00,
			`version` VARCHAR(50) DEFAULT NULL,
			`license` VARCHAR(255) DEFAULT NULL,
			`contact_info` VARCHAR(255) DEFAULT NULL,
			`meta_desc` VARCHAR(300) DEFAULT NULL,
			`meta_keys` TEXT DEFAULT NULL,
			`views` INT DEFAULT 0,
			PRIMARY KEY (`id`)
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    'CREATE TABLE IF NOT EXISTS `files_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 `files_field_values` (
			`id` INT(11) NOT NULL AUTO_INCREMENT, -- Уникальный идентификатор
			`files_id` INT(11) NOT NULL, -- ID новости
			`field_id` INT(11) NOT NULL, -- ID поля из files_fields
			`x_value` TEXT NOT NULL, -- Значение поля (универсальное хранилище)
			PRIMARY KEY (`id`),
			FOREIGN KEY (`files_id`) REFERENCES `files`(`id`) ON DELETE CASCADE,
			FOREIGN KEY (`field_id`) REFERENCES `files_fields`(`id`) ON DELETE CASCADE
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    'CREATE TABLE IF NOT EXISTS `files_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 `files_cat_relations` (
        `files_id` INT NOT NULL,
        `category_id` INT NOT NULL,
        PRIMARY KEY (`files_id`, `category_id`),
        CONSTRAINT `fk_files`
            FOREIGN KEY (`files_id`) REFERENCES `files`(`id`)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
        CONSTRAINT `fkf_category`
            FOREIGN KEY (`category_id`) REFERENCES `files_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) {
    try {
        $db_connect->query($sql);
    } catch (Exception $e) {
        echo "Ошибка при добавлении данных: " . $e->getMessage() . "\n";
        $successFlag = false;
    }
}

$files_categories = [
    ['id' => 1, 'parentid' => 0, 'position' => 1, 'language' => 'Russian', 'name' => 'PC', 'alt_name' => 'pc', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 2, 'parentid' => 1, 'position' => 2, 'language' => 'Russian', 'name' => 'Аудио и Видео', 'alt_name' => 'media', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 3, 'parentid' => 1, 'position' => 3, 'language' => 'Russian', 'name' => 'Безопасность', 'alt_name' => 'safety', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 4, 'parentid' => 1, 'position' => 4, 'language' => 'Russian', 'name' => 'Игры', 'alt_name' => 'games', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 5, 'parentid' => 1, 'position' => 5, 'language' => 'Russian', 'name' => 'Дизайн', 'alt_name' => 'design', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 6, 'parentid' => 1, 'position' => 6, 'language' => 'Russian', 'name' => 'Деловые программы', 'alt_name' => 'business', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 7, 'parentid' => 1, 'position' => 7, 'language' => 'Russian', 'name' => 'Разработчикам', 'alt_name' => 'developers', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 8, 'parentid' => 1, 'position' => 8, 'language' => 'Russian', 'name' => 'Серверы', 'alt_name' => 'servers', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 9, 'parentid' => 1, 'position' => 9, 'language' => 'Russian', 'name' => 'Сети и Интернет', 'alt_name' => 'networks', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 10, 'parentid' => 1, 'position' => 10, 'language' => 'Russian', 'name' => 'Система', 'alt_name' => 'system', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 11, 'parentid' => 0, 'position' => 11, 'language' => 'Russian', 'name' => 'Android и iOS', 'alt_name' => 'mobiles', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 12, 'parentid' => 11, 'position' => 12, 'language' => 'Russian', 'name' => 'Приложения', 'alt_name' => 'apps', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
    ['id' => 13, 'parentid' => 11, 'position' => 13, 'language' => 'Russian', 'name' => 'Игры', 'alt_name' => 'games', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_news.tpl', 'full_tpl' => 'full_news.tpl', 'comments' => 1],
];

// Массовая вставка данных
$db_connect->insert('files_categories', $files_categories);

// Массив с запросами на добавление данных в таблицы
$addData = [
    "files" => [
        [
            'autor' => 'Admin',
            'date' => date('Y-m-d H:i:s'),
            'language' => 'russian',
            'title' => 'Microsoft Office Suite',
            'file_path' => 'uploads/files/2024/2/1/file.zip',
            'image' => 'uploads/images/files/2024/2/1/image.jpg',
            'alt_name' => 'pc-business-1',
            'short_desc' => 'Офисный пакет для PC с текстовым редактором, таблицами, и презентациями.',
            'full_desc' => 'Microsoft Office Suite предоставляет полный набор офисных приложений, включая Word, Excel и PowerPoint, обеспечивая эффективную работу с документами, таблицами и презентациями.',
            'price' => NULL,
            'version' => NULL,
            'license' => NULL,
            'contact_info' => NULL,
            'meta_desc' => NULL,
            'meta_keys' => NULL,
            'views' => 0
        ],
        [
            'autor' => 'Admin',
            'date' => date('Y-m-d H:i:s'),
            'language' => 'russian',
            'title' => 'Visual Studio Code',
            'file_path' => 'uploads/files/2024/2/2/file.zip',
            'image' => 'uploads/images/files/2024/2/2/image.jpg',
            'alt_name' => 'pc-developers-1',
            'short_desc' => 'Удобный и эффективный кодовый редактор с расширенной функциональностью.',
            'full_desc' => 'Visual Studio Code - это легкий и гибкий редактор кода, созданный для повышения производительности разработчиков. С поддержкой множества языков программирования, расширенными возможностями и открытым исходным кодом, он обеспечивает удобную среду для написания и отладки кода.',
            'price' => NULL,
            'version' => NULL,
            'license' => NULL,
            'contact_info' => NULL,
            'meta_desc' => NULL,
            'meta_keys' => NULL,
            'views' => 0
        ],
        // Добавьте другие записи...
    ]
];

foreach ($addData as $table => $rows) {
    foreach ($rows as $data) {
        $db_connect->insert($table, $data);
    }
}
	// Проверяем флаг и выводим сообщение
	if ($successFlag) {
		echo "
			<script>
				alert('Данные модуля файлов успешно добавлены');
				window.location.href = window.location.href;
			</script>
		";
		exit();
	}