<?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');
    require_once ENGINE_DIR . '/mods/convert_user_balance.php';

    function profileController($userId)
    {
        global $db_connect, $smarty, $config, $lang;

        $user = $db_connect->get("users", "*", ["email" => $_SESSION["user_email"]]);

        if (!$user) {
            // Пользователь не найден
            $smarty->assign('error_message', 'Пользователь не найден');
            $smarty->display(TEMPLATES_DIR . '/' . $config['skin'] . '/error.tpl');
        } else {

            if (hasPermission($_SESSION["user_id"], "referrals.view")) {
                require_once ENGINE_DIR . "/" . "mods/referral_statistics.php";
            }

            $role = $db_connect->get("roles", "*", [
                "id" => $user["role_id"] ?? 0
            ]);

            $coBuyings = [];
            if (isset($config['modules']["shops"]['used']) && $config['modules']['shops']['used']) {

                $coBuyings = $db_connect->select("co_buyings", [
                    "[>]shop_products" => ["product_id" => "id"],
                    "[>]shops" => ["owner_id" => "owner_id"]
                ], [
                    "co_buyings.id",
                    "co_buyings.goal_amount",
                    "co_buyings.current_amount",
                    "co_buyings.status",
                    "co_buyings.date_end",
                    "shop_products.name(product_title)",
                    "shop_products.price(product_price)",
                    "shops.shop_name",
                    "shops.shop_id"
                ], [
                    "co_buyings.status" => "active",
                    "ORDER" => ["co_buyings.date_start" => "DESC"],
                    "GROUP" => ["co_buyings.id", "co_buyings.goal_amount"]
                ]);

                // Добавляем прогресс
                foreach ($coBuyings as &$cb) {
                    $cb["progress"] = ($cb["goal_amount"] > 0) ? round(($cb["current_amount"] / $cb["goal_amount"]) * 100) : 0;
                }
                unset($cb);


            }

            $roleName = $db_connect->get("roles", "name", [
                "id" => $_SESSION["user_group_id"]
            ]);

            if (hasPermission($_SESSION["user_id"], "grades.view")) {
                if ($roleName == "Teacher") {
                    teacherGradesController();
                } else if ($roleName == "Parent") {
                    parentGradesController();
                }
            }

            if (hasPermission($_SESSION["user_id"], "schedules.view")) {
                if ($roleName == "Teacher") {
                    teacherSchedulesController();

                    $modalsHtml[] = $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/extensions/education/schedules/add_schedule.tpl');

                    $smarty->assign("modalsHtml", $modalsHtml);
                } else if ($roleName == "Parent") {
                    parentSchedulesController();

                }
            }
            if (hasPermission($_SESSION["user_id"], "students_progress.view")) {
                if ($roleName == "Teacher") {
                    teacherStudentProgressController();

                    $modalsHtml[] = $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/extensions/education/students_progress/add_student_progress.tpl');

                    $smarty->assign("modalsHtml", $modalsHtml);
                } else if ($roleName == "Parent") {
                    parentStudentProgressController();

                }
            }

            // Передаем в Smarty
            $smarty->assign("all_co_buyings", $coBuyings);

            $userBalanceInfo = getConvertedBalanceInfo();
            $smarty->registerPlugin('modifier', 'json_encode', function ($value) {
                return json_encode($value);
            });
            $smarty->assign('group', $roleName);
            $smarty->assign('balance', $userBalanceInfo["finalBalance"]);
            $smarty->assign('currency', $userBalanceInfo["currentCurrency"]);
            $smarty->assign('title', $user['name'] . ' - Профиль пользователя');
            $smarty->assign('page_name', '
                    <li class="breadcrumb-item active">' . $user['name'] . '</li>
                ');
            // Передаем данные в Smarty
            $smarty->assign('content', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/profile.tpl', ['user' => $user]));
            // Проверяем, выключен ли сайт
            require_once(ENGINE_DIR . '/mods/offline.php');
        }
    }

    $smarty->assign($config);