<?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 liveChatController() {
        require_once ENGINE_DIR . '/data/ws_config.php';
        require_once ENGINE_DIR . '/mods/language.php';

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

        if (isset($_GET['pages']) && $_GET["pages"] === "chat") {
            $user = $db_connect->get("users", "*", ["email" => $_SESSION["user_email"] ?? ""]) ?? [];

            if (empty($user) && empty($_SESSION["guest_id"])) {
               /* $smarty->assign('error_message', 'Авторизуйтесь для входа в чат');
                $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
                exit();*/

                $_SESSION['guest_id'] = 'guest_' . bin2hex(random_bytes(4));

                $db_connect->insert("users", [
                    "email" => "",
                    "password" => "",
                    "group" => 6,
                    "name" => "Guest",
                    "avatar" => "uploads/profiles/default.svg",
                ]);
                $user = $db_connect->get("users", "*", ["id" => $db_connect->id()]) ?? [];

                $_SESSION['user_id'] = $user["id"];

            }

            if (!empty($user)) {
                $existsInGroup = $db_connect->get("group_members", "*", ["user_id" => $user["id"], "group_id" => 1]) ?? [];
            }

            if (empty($existsInGroup)) {
                if (!empty($user)) {
                    $db_connect->insert("group_members", [
                        "user_id" => $user["id"],
                        "group_id" => 1,
                        "role" => "member",
                        "joined_at" => date("Y-m-d H:i:s")
                    ]);
                }
            }

            if (!empty($user) || !empty($_SESSION["guest_id"])) {

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


                if (empty($token)) {
                    $tokenStr = bin2hex(random_bytes(16));
                    if (!empty($user)) {
                        $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"]) ?? [];
                    }
                }

                $smarty->registerPlugin('modifier', 'json_encode', 'json_encode');
                $smarty->assign('status', $user["status"]);
                $smarty->assign('token', $token["token"]);
                $smarty->assign('wsConfig', $ws_config);
                $smarty->assign('langJson', json_encode($lang["chat"]));
                $smarty->assign('title', 'Live Чат');
                $smarty->assign('page_name', '<li class="breadcrumb-item active">' . "Live chat" . '</li>');
                $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/chat/live-chat.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();
        }

    }