<?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.                                                      *
        *****************************************************************************
    */

    function liveNotificationsController() {
        require_once ENGINE_DIR . '/data/ws_config.php';
        require_once ENGINE_DIR . '/mods/language.php';

        global $db_connect, $smarty, $config, $lang;

        $perPage = 10;
        $page = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
        $offset = ($page - 1) * $perPage;

        if (isset($_GET['pages']) && $_GET["pages"] === "notifications") {
            $user = $db_connect->get("users", "*", ["id" => $_SESSION["user_id"] ?? 0]) ?? [];

            if (!empty($user)) {
                $token = $db_connect->get("tokens", "*", ["user_id" => $user["id"], "active" => 1, "target" => "chat"]) ?? [];

                if (empty($token)) {
                    $tokenStr = bin2hex(random_bytes(16));
                    $db_connect->insert("tokens", ["user_id" => $user["id"], "active" => 1, "target" => "chat", "token" => $tokenStr]);

                    $token = $db_connect->get("tokens", "*", ["user_id" => $user["id"], "active" => 1, "target" => "chat"]) ?? [];
                }

                $dateFrom = $_GET['from'] ?? null;
                $dateTo = $_GET['to'] ?? null;

                $conditions = [
                    "user_id" => $user["id"],
                ];

                if ($dateFrom && $dateTo) {
                    $conditions["created_at[<>]"] = [$dateFrom . " 00:00:00", $dateTo . " 23:59:59"];
                } elseif ($dateFrom) {
                    $conditions["created_at[>=]"] = $dateFrom . " 00:00:00";
                } elseif ($dateTo) {
                    $conditions["created_at[<=]"] = $dateTo . " 23:59:59";
                }

                $total = $db_connect->count("notifications", $conditions);
                $conditions["ORDER"] = ["created_at" => "DESC"];
                $conditions["LIMIT"] = [$offset, $perPage];

                $pages = ceil($total / $perPage);
                $smarty->assign('pages', $pages);

                $notifications = $db_connect->select("notifications", "*", $conditions);

                foreach ($notifications as &$notification) {
                    $notification["content"] = preg_replace_callback('/%%(.*?)%%/', function ($matches) {
                        global $lang;
                        $map = $lang["chat"];
                        return $map[$matches[1]] ?? $matches[0];
                    }, $notification["content"]);

                }
                unset($notification);


                $smarty->registerPlugin('modifier', 'json_encode', 'json_encode');
                $smarty->assign('status', $user["status"]);
                $smarty->assign('token', $token["token"]);
                $smarty->assign('notifications', $notifications);
                $smarty->assign('page', $page);
                $smarty->assign('perPage', $perPage);
                $smarty->assign('total', $total);
                $smarty->assign('from', $dateFrom);
                $smarty->assign('to', $dateTo);
                $smarty->assign('wsConfig', $ws_config);
                $smarty->assign('langJson', json_encode($lang["chat"]));
                $smarty->assign('title', $lang["chat"]["notifications"]);
                $smarty->assign('page_name', '<li class="breadcrumb-item active">' . $lang["chat"]["notifications"] . '</li>');
                $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/notifications.tpl', ['user' => $user]));

                require_once(ENGINE_DIR . '/mods/offline.php');
                exit();
            } else {
                $smarty->assign('error_message', 'У вас нету доступа к странице уведомлений');
                $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
            }

            require_once(ENGINE_DIR . '/mods/offline.php');
            exit();
        }

    }