<?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];

// Массив с запросами на создание таблиц
$createTablesPG = [
    "CREATE TABLE IF NOT EXISTS ads (
            id SERIAL PRIMARY KEY,
            autor VARCHAR(40),
            date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            language VARCHAR(190),
            title VARCHAR(255),
            image VARCHAR(255),
            alt_name VARCHAR(190),
            short_desc TEXT,
            full_desc TEXT,
            price DECIMAL(10, 2),
            authority VARCHAR(50),
            phone VARCHAR(255),
            email VARCHAR(255),
            meta_desc VARCHAR(300),
            meta_keys TEXT,
            views INT DEFAULT 0
        )",

    "CREATE TABLE IF NOT EXISTS ads_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 ads_field_values (
            id SERIAL PRIMARY KEY,
            ads_id INT NOT NULL,
            field_id INT NOT NULL,
            x_value TEXT NOT NULL,
            FOREIGN KEY (ads_id) REFERENCES ads(id) ON DELETE CASCADE,
            FOREIGN KEY (field_id) REFERENCES ads_fields(id) ON DELETE CASCADE
        )",

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

    'CREATE TABLE IF NOT EXISTS ads_cat_relations (
        ads_id INT NOT NULL,
        category_id INT NOT NULL,
        PRIMARY KEY (ads_id, category_id),
        CONSTRAINT fk_ads
            FOREIGN KEY (ads_id) REFERENCES ads(id)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
        CONSTRAINT fka_category
            FOREIGN KEY (category_id) REFERENCES ads_categories(id)
            ON DELETE CASCADE
            ON UPDATE CASCADE
    );'
];

$createTablesMySQL = [
    'CREATE TABLE IF NOT EXISTS `ads` (
			`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,
			`price` DECIMAL(10, 2) NOT NULL,
			`authority` VARCHAR(50) DEFAULT NULL,
			`phone` VARCHAR(255) DEFAULT NULL,
			`email` 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 `ads_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 `ads_field_values` (
			`id` INT(11) NOT NULL AUTO_INCREMENT, -- Уникальный идентификатор
			`ads_id` INT(11) NOT NULL, -- ID новости
			`field_id` INT(11) NOT NULL, -- ID поля из ads_fields
			`x_value` TEXT NOT NULL, -- Значение поля (универсальное хранилище)
			PRIMARY KEY (`id`),
			FOREIGN KEY (`ads_id`) REFERENCES `ads`(`id`) ON DELETE CASCADE,
			FOREIGN KEY (`field_id`) REFERENCES `ads_fields`(`id`) ON DELETE CASCADE
		) ENGINE=INNODB DEFAULT CHARSET=utf8',

    'CREATE TABLE IF NOT EXISTS `ads_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 `ads_cat_relations` (
        `ads_id` INT NOT NULL,
        `category_id` INT NOT NULL,
        PRIMARY KEY (`ads_id`, `category_id`),
        CONSTRAINT `fk_ads`
            FOREIGN KEY (`ads_id`) REFERENCES `ads`(`id`)
            ON DELETE CASCADE
            ON UPDATE CASCADE,
        CONSTRAINT `fka_category`
            FOREIGN KEY (`category_id`) REFERENCES `ads_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) {
    if (!$db_connect->query($sql)) {
        echo "Ошибка при добавлении таблицы.\n";
        exit;
    }
}

// Массив с запросами на добавление данных в таблицы
$insertData = [
    [
        'autor' => 'Admin',
        'date' => date('Y-m-d H:i:s'),
        'language' => 'russian',
        'title' => 'Продаю Toyota Camry 2018 года',
        'image' => 'uploads/images/ads/2024/2/1/image.jpg',
        'alt_name' => 'ad-1',
        'short_desc' => 'Отличное состояние, пробег 40 000 км, полная сервисная История.',
        'full_desc' => 'Продаю надежный и комфортабельный автомобиль Toyota Camry 2018 года выпуска. Автомобиль в идеальном состоянии, без аварий, пробег 40 000 км. Полная сервисная История, все ТО проводились своевременно.',
        'price' => 1200000.00,
        'authority' => 'Premium',
        'phone' => '100-000-0000',
        'email' => 'example-1@gmail.com',
        'meta_desc' => NULL,
        'meta_keys' => NULL,
        'views' => 0
    ],
    [
        'autor' => 'Admin',
        'date' => date('Y-m-d H:i:s'),
        'language' => 'russian',
        'title' => 'Куплю 2-комнатную квартиру в центре города',
        'image' => 'uploads/images/ads/2024/2/2/image.jpg',
        'alt_name' => 'ad-2',
        'short_desc' => 'Ищу уютное жилье с хорошим ремонтом, рассмотрю разные варианты.',
        'full_desc' => 'Ищу квартиру в центре города с ремонтом и удобствами. Предпочтение квартирам с двумя комнатами. Готов рассмотреть различные предложения. Агентов просьба не беспокоить.',
        'price' => 1225000.00,
        'authority' => 'Exclusive',
        'phone' => '200-000-0000',
        'email' => 'example-2@gmail.com',
        'meta_desc' => NULL,
        'meta_keys' => NULL,
        'views' => 0
    ],
    // Добавьте сюда остальные данные для вставки
];

$ads_categories = [
    ['id' => 1, 'parentid' => 0, 'position' => 1, 'language' => 'Russian', 'name' => 'Транспорт', 'alt_name' => 'transport', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 2, 'parentid' => 1, 'position' => 2, 'language' => 'Russian', 'name' => 'Автомобили', 'alt_name' => 'autos', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 3, 'parentid' => 1, 'position' => 3, 'language' => 'Russian', 'name' => 'Мотоциклы', 'alt_name' => 'moto', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 4, 'parentid' => 1, 'position' => 4, 'language' => 'Russian', 'name' => 'Другая техника', 'alt_name' => 'other-transport', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 5, 'parentid' => 0, 'position' => 5, 'language' => 'Russian', 'name' => 'Недвижимость', 'alt_name' => 'real-estate', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 6, 'parentid' => 5, 'position' => 6, 'language' => 'Russian', 'name' => 'Купить', 'alt_name' => 'buy', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 7, 'parentid' => 5, 'position' => 7, 'language' => 'Russian', 'name' => 'Продать', 'alt_name' => 'sell', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 8, 'parentid' => 5, 'position' => 8, 'language' => 'Russian', 'name' => 'Аренда', 'alt_name' => 'rent', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1],
    ['id' => 9, 'parentid' => 0, 'position' => 9, 'language' => 'Russian', 'name' => 'Работа', 'alt_name' => 'jobs', 'meta_desc' => '', 'meta_keys' => '', 'short_tpl' => 'short_ads.tpl', 'full_tpl' => 'full_ad.tpl', 'comments' => 1]
];

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

$successFlag = false;
    // Вставка данных в таблицу `ads`
    foreach ($insertData as $data) {
        $db_connect->insert('ads', $data);
        $successFlag = true;
    }



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