<?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');

$enabledDatabase = $config["database_settings"]["enabled_database"];
$currentDatabaseSettings = $config["database_settings"][$enabledDatabase];

	// Флаг для отслеживания успешности выполнения запросов
	$successFlag = true;

	// Массив с запросами на создание таблиц
// Создание таблиц
$createTablesPG = [
    'news' => [
        'id' => ['SERIAL', 'NOT NULL', 'PRIMARY KEY'],
        'autor' => ['VARCHAR(40)', 'DEFAULT NULL'],
        'date' => ['TIMESTAMP', 'DEFAULT CURRENT_TIMESTAMP'],
        'category' => ['VARCHAR(255)', 'DEFAULT NULL'],
        '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'],
        'allow_comments' => ['SMALLINT', 'DEFAULT NULL'],
        'fixed' => ['SMALLINT', 'DEFAULT NULL'],
        'allow_br' => ['SMALLINT', 'DEFAULT NULL'],
        'tags' => ['VARCHAR(255)', 'DEFAULT NULL'],
        'rating' => ['SMALLINT', 'DEFAULT NULL'],
        'views' => ['INTEGER', 'DEFAULT 0']
    ],
    'news_fields' => [
        'id' => ['SERIAL', 'NOT NULL', 'PRIMARY KEY'],
        'x_name' => ['VARCHAR(255)', 'NOT NULL'],
        'column_type' => ['VARCHAR(255)', 'NOT NULL'],
        'column_length' => ['INTEGER', 'DEFAULT 0']
    ],
    'news_field_values' => [
        'id' => ['SERIAL', 'NOT NULL', 'PRIMARY KEY'],
        'news_id' => ['INTEGER', 'NOT NULL'],
        'field_id' => ['INTEGER', 'NOT NULL'],
        'x_value' => ['TEXT', 'NOT NULL']
    ],
    'news_categories' => [
        'id' => ['SERIAL', 'NOT NULL', 'PRIMARY KEY'],
        'parentid' => ['INTEGER', 'DEFAULT NULL'],
        'position' => ['INTEGER', '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' => ['SMALLINT', 'DEFAULT NULL'],
        'views' => ['INTEGER', 'DEFAULT 0']
    ],
    'news_cat_relations' => [
        'news_id' => ['INTEGER', 'NOT NULL'],
        'category_id' => ['INTEGER', 'NOT NULL'],
    ],
];

$createTablesMySQL = [
    'CREATE TABLE IF NOT EXISTS `news` (
			`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,
			`allow_comments` TINYINT(1) DEFAULT NULL,
			`fixed` TINYINT(1) DEFAULT NULL,
			`allow_br` TINYINT(1) DEFAULT NULL,
			`tags` VARCHAR(255) DEFAULT NULL,
			`rating` TINYINT DEFAULT NULL,
			`views` INT DEFAULT 0,
			PRIMARY KEY (`id`)
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

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

    'CREATE TABLE IF NOT EXISTS `news_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 `news_cat_relations` (
        `news_id` INT NOT NULL,
        `category_id` INT NOT NULL,
        PRIMARY KEY (`news_id`, `category_id`),
        CONSTRAINT `fk_news`
            FOREIGN KEY (`news_id`) REFERENCES `news`(`id`)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
        CONSTRAINT `fk_category`
            FOREIGN KEY (`category_id`) REFERENCES `news_categories`(`id`)
            ON DELETE CASCADE
            ON UPDATE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'
];

if ($enabledDatabase == "mysql") {
    foreach ($createTablesMySQL as $sql) {
        if ($db_connect->query($sql) !== TRUE) {
            echo "Ошибка при добавлении данных: " . $db_connect->error . "\n";
            $successFlag = false;
        }
    }
}


if ($enabledDatabase == "pgsql") {
    foreach ($createTablesPG as $table => $columns) {
        $sql = "CREATE TABLE IF NOT EXISTS \"$table\" (";
        foreach ($columns as $column => $attributes) {
            $sql .= "\"$column\" " . implode(' ', $attributes) . ', ';
        }

        // Добавление внешних ключей
        if ($table == 'news_field_values') {
            $sql .= 'CONSTRAINT fk_news_id FOREIGN KEY (news_id) REFERENCES news(id) ON DELETE CASCADE, ';
            $sql .= 'CONSTRAINT fk_field_id FOREIGN KEY (field_id) REFERENCES news_fields(id) ON DELETE CASCADE';
        } else if ($table == 'news_cat_relations') {
            $sql .= 'PRIMARY KEY (news_id, category_id), ';
            $sql .= 'CONSTRAINT fk_news FOREIGN KEY (news_id) REFERENCES news(id) ON DELETE CASCADE ON UPDATE CASCADE, ';
            $sql .= 'CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES news_categories(id) ON DELETE CASCADE ON UPDATE CASCADE';
        }

        $sql = rtrim($sql, ', ') . ')';
        try {
            $db_connect->query($sql);
        } catch (Exception $e) {
            echo "Ошибка создания таблицы $table: " . $e->getMessage();
        }
    }
}
// Создание таблиц

$insertData = [
    'news' => [
        [
            'autor' => 'Admin',
            'date' => date("Y-m-d H:i:s"),
            'language' => 'russian',
            'title' => 'Спортсменка перевернула представление о гибкости',
            'image' => 'uploads/images/news/2024/2/1/image.jpg',
            'alt_name' => 'news-1',
            'short_desc' => 'Молодая гимнастка установила новый мировой рекорд, продемонстрировав уникальную гибкость и сложные элементы в выступлении.',
            'full_desc' => 'В спортивном мире произошло потрясающее событие...',
            'meta_desc' => '1',
            'meta_keys' => '1',
            'allow_comments' => '1',
            'fixed' => '0',
            'allow_br' => '0',
            'tags' => '15',
            'rating' => 0,
            'views' => 0
        ],
        // Другие записи...
    ]
];

// Вставка данных
foreach ($insertData as $table => $rows) {
    foreach ($rows as $data) {
        $db_connect->insert($table, $data);
    }
}

// Данные для вставки
$data = [
    [
        'id' => 1,
        'parentid' => 0,
        'position' => 1,
        'language' => 'russian',
        'name' => 'Наука',
        'alt_name' => 'science',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 2,
        'parentid' => 0,
        'position' => 2,
        'language' => 'russian',
        'name' => 'Спорт',
        'alt_name' => 'sport',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 3,
        'parentid' => 0,
        'position' => 3,
        'language' => 'russian',
        'name' => 'Культура',
        'alt_name' => 'culture',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 4,
        'parentid' => 0,
        'position' => 4,
        'language' => 'russian',
        'name' => 'Гимнастика',
        'alt_name' => 'gym',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 5,
        'parentid' => 0,
        'position' => 5,
        'language' => 'russian',
        'name' => 'Этика',
        'alt_name' => 'ethics',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 6,
        'parentid' => 0,
        'position' => 6,
        'language' => 'russian',
        'name' => 'Природа',
        'alt_name' => 'nature',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 7,
        'parentid' => 0,
        'position' => 7,
        'language' => 'russian',
        'name' => 'Бизнес',
        'alt_name' => 'business',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 8,
        'parentid' => 0,
        'position' => 8,
        'language' => 'russian',
        'name' => 'Экономика',
        'alt_name' => 'economy',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ],
    [
        'id' => 9,
        'parentid' => 0,
        'position' => 9,
        'language' => 'russian',
        'name' => 'Медицина',
        'alt_name' => 'medicine',
        'meta_desc' => '',
        'meta_keys' => '',
        'short_tpl' => 'short_news.tpl',
        'full_tpl' => 'full_news.tpl',
        'comments' => 1
    ]
];

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


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