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

    $search = '';
    $results = [];
    // Устанавливаем состояние модулей с помощью флагов
    $search_activity = true;

    function searchController() {
        global $db_connect, $smarty, $search_activity, $config, $search, $results, $lang;

        if ($search_activity) {
            if (isset($_POST['searchbutton'])) {
                $search = trim($_POST['search']);
                if (!empty($search)) {
                    $tables = [
                        'static_pages' => true,
                        'ads' => isModuleActive('ads') && isModuleUsed('ads'),
                        'files' => isModuleActive('files') && isModuleUsed('files'),
                        'movies' => isModuleActive('movies') && isModuleUsed('movies'),
                        'news' => isModuleActive('news') && isModuleUsed('news'),
                        'products' => isModuleActive('products') && isModuleUsed('products'),
                        'events' => isModuleActive('events') && isModuleUsed('events') // Добавляем модуль events
                    ];
                    $existing_tables = array_keys(array_filter($tables));
                    $results = [];

                    foreach ($existing_tables as $table) {
                        $conditions = [
                            ['column' => 'title', 'operator' => 'LIKE', 'value' => "%$search%"],
                            ['column' => 'full_desc', 'operator' => 'LIKE', 'value' => "%$search%"]
                        ];
                        if (in_array($table, ['ads', 'files', 'movies', 'news', 'products', 'events'])) {
                            $conditions[] = ['column' => 'short_desc', 'operator' => 'LIKE', 'value' => "%$search%"];
                        }

                        $res = $db_connect->select($table, "*", [
                            "OR" => [
                                "title[~]" => "%$search%",
                                "full_desc[~]" => "%$search%"
                            ]
                        ]);

                        $res = array_map(function($item) {
                            return array_filter($item, function($key) {
                                return !is_numeric($key);
                            }, ARRAY_FILTER_USE_KEY);
                        }, $res);


                        foreach ($res as &$row) {
                            $row["source"] = $table;
                        }

                        $results = array_merge($res, $results);

                    }

                    if (empty($results)) {
                      //  echo "Нет доступных результатов для поиска.";
                    }
                }
            }
        }

        // Устанавливаем массив переменных в Smarty
        $smarty->assign('lang', $lang);
        $smarty->assign('search', $search);
        $smarty->assign('results', $results);
        $smarty->assign('title', $lang["general"]["search_button"].' - Skills Engine');
        $smarty->assign('page_name', '
            <li class="breadcrumb-item active">
        '.$lang["general"]["search_button"]."</li>");
        // Передаем данные в шаблон
        $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/searchresult.tpl'));

        // Проверяем, выключен ли сайт
        require_once(ENGINE_DIR . '/mods/offline.php');
    }

    function getRootUrl() {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $host = $_SERVER['HTTP_HOST'];
        return $protocol . $host;
    }

    // Передаем глобальные настройки Smarty
    $smarty->assign('root_url', getRootUrl());
    $smarty->assign($config);