<?php
namespace engine\eventSubscribers\smarty;

use Subscribers\AbstractEventSubscriber;
class SmartyWidgetsRenderingSubscriber extends AbstractEventSubscriber
{

    public function wallWidgetData($eventData, $metaParams)
    {

        $wallWidget = $this->db->get("walls", "*", ["uniq_name" => $eventData["uniq_name"]]);

        if ($wallWidget) {
            $wallWidget["settings"] = json_decode($wallWidget['settings'], true);

            $wallWidget["followersCount"] = $this->db->count("wall_followers", "user_id", ["wall_id" => $wallWidget['id']]) ?? 0;
            $wallWidget["followersData"] = $this->db->select("wall_followers", "*", ["wall_id" => $wallWidget['id']]) ?? [];
            $wallWidget["posts"] = $this->db->select("posts", "*", ["wall_id" => $wallWidget['id']]) ?? [];

            foreach ($wallWidget["posts"] ?? [] as &$post) {
                $post["media"] = $this->db->select("post_media", "*", ["post_id" => $post['id']]);
            }

            if (!empty($_SESSION["user_id"]) && $wallWidget["owner_id"] == $_SESSION["user_id"]) {
                $wallWidget["isOwner"] = true;
            } else {
                $wallWidget["isOwner"] = false;
            }

            $wallWidget["usrToken"] = $this->db->select("tokens", "*", ["user_id" => $_SESSION["user_id"] ?? 0]);
            $wallWidget["usrAvatar"] = $this->db->get("users", "avatar", ["id" => $_SESSION["user_id"] ?? 0]);


        }


        return [
            "widgetData" => $wallWidget
        ];

    }

    public function paymentWidgetData($eventData, $metaParams)
    {

        $paymentWidget = $this->db->get("payment_widgets", "*", ["uniq_name" => $eventData["uniq_name"]]);

        $currency = getCurrentCurrency();
        $paymentWidget["handleUrl"] = "/?payment&price={$paymentWidget["price"]}&currency=$currency&action=redirect-payment&widget={$paymentWidget["id"]}";
        $paymentWidget["settings"] = json_decode($paymentWidget['settings'], true);


        return [
            "widgetData" => $paymentWidget
        ];

    }

    public function counterWidgetData($eventData, $metaParams)
    {

        $session_lang_key = $this->config['lang_union'] ? 'lang' : 'language';

        $lang_code = $_SESSION[$session_lang_key] ?? $this->config['default_lang'];

        // Преобразуем язык в нижний регистр
        $lang_code = strtolower($lang_code);

        // Загружаем языковой файл
        $lang = load_language($lang_code);

        $counterWidget = $this->db->get("counters", "*", ["uniq_name" => $eventData["uniq_name"], "active" => 1]);

        $objectData = [
            "objectCount" => 0,
            "totalCount" => 0
        ];

        if (empty($counterWidget)) {
            $helpName = $this->db->get("counters", "uniq_name", ["uniq_name[~]" => $eventData["uniq_name"], "active" => 1]);
            /*if (!empty($helpName)) {
                echo "Ошибка: Счетчик {$eventData["uniq_name"]} не найден, возможно вы хотели ввести $helpName";
            }*/
        }

        if (!empty($counterWidget) && $counterWidget["active"] === true || !empty($counterWidget) && $counterWidget["active"] == 1) {
            $countObjectParentName = $counterWidget["name"];
            $fromCount = $counterWidget["from_count"];
            $toCount = $counterWidget["to_count"];
            $counterSubObjectType = $counterWidget["counter_sub_object"];

            $modules = [];
            foreach ($this->config['modules'] as $name => $mConfig) {
                if ($mConfig['used'] === true) {
                    $modules[] = $name;
                }
            }

            if ($counterSubObjectType == "views") {
                if ($counterWidget["name"] == "all_modules") {
                    foreach ($modules as $module) {
                        $objectData["objectCount"] += $this->db->sum($module, "views");
                    }
                } else {
                    $objectData["objectCount"] = $this->db->sum($counterWidget["name"], "views");
                }
            } elseif ($counterSubObjectType == "comments") {
                if ($counterWidget["name"] == "all_modules") {
                    foreach ($modules as $module) {
                        $objectData["objectCount"] += $this->db->count("comments", ["entity_type" => $module, "status" => 1]);
                    }
                } else {
                    $objectData["objectCount"] = $this->db->count("comments", ["entity_type" => $counterWidget["name"], "status" => 1]);
                }
            } elseif ($counterSubObjectType == "user_groups_count") {
                if ($counterWidget["name"] == "all_groups") {
                    $objectData["objectCount"] = $this->db->count("users");
                } else {
                    $groupId = $this->db->get("roles", "id", ["name" => $counterWidget["name"]]);
                    $objectData["objectCount"] = $this->db->count("users", ["group" => $groupId]);
                }

                if ($fromCount == 0 && !empty($toCount)) {
                    $objectData["totalCount"] = (int)$toCount - (int)$objectData["objectCount"];
                }

            } elseif ($counterSubObjectType == "all_rows") {
                if ($counterWidget["name"] == "all_modules") {
                    foreach ($modules as $module) {
                        $objectData["objectCount"] += $this->db->count($module);
                    }
                } else {
                    $objectData["objectCount"] = $this->db->count($counterWidget["name"]);
                }
            } elseif ($counterSubObjectType == "category_count") {
                if ($counterWidget["name"] == "all_modules") {
                    foreach ($modules as $module) {
                        $objectData["objectCount"] += $this->db->count($module."_categories");
                    }
                } else {
                    $objectData["objectCount"] = $this->db->count($counterWidget["name"]."_categories");
                }
            }

            $text = ""; //;
            $moduleName = $lang['module_name'] ?? $lang['topmenu'];
            if ($counterWidget["object_type"] == "modules") {
                if ($counterWidget["name"] != "all_modules") {
                    if ($_POST["showTypeName"] == true) {
                        $text .= $lang['datatable'][$counterWidget["counter_sub_object"]]." ({$moduleName[$counterWidget["name"]]}): ". "<b>{$objectData["objectCount"]}</b>";
                    } else {
                        $text .= $lang['datatable'][$counterWidget["counter_sub_object"]]." ". "<b>{$objectData["objectCount"]}</b>";
                    }
                } else {
                    $text .= $lang['datatable'][$counterWidget["counter_sub_object"]]." всех модулей: ". "<b>{$objectData["objectCount"]}</b>";
                }
            } elseif ($counterWidget["object_type"] == "user_groups") {
                if ($counterWidget["name"] != "all_groups") {
                    $text .= "Группа: ".$counterWidget["name"] . " количество: ". "<b>{$objectData["objectCount"]}</b>";
                } else {
                    if ($_POST["showTypeName"] == true) {
                        $text .= $lang['datatable'][$counterWidget["counter_sub_object"]] . " ({$lang['datatable'][$counterWidget["name"]]}): " . "<b>{$objectData["objectCount"]}</b>";
                    } else {
                        $text .= $lang['datatable'][$counterWidget["counter_sub_object"]]." ". "<b>{$objectData["objectCount"]}</b>";
                    }
                }
            }

            if (!empty($objectData["totalCount"])) {
                $prefix = !empty($_POST["prefix"]) ? $_POST["prefix"] : "-";
                $residueCount = $counterWidget["counter_type"] == "from" ? $toCount : $fromCount;
                $text = "Осталось мест в группе {$counterWidget["name"]}: ".$objectData["totalCount"] ." $prefix $residueCount";
            }

        }

        $counterWidget["text"] = $text ?? "";
        $counterWidget["total_count"] = $objectData["totalCount"];
        return [
            "widgetData" => $counterWidget
        ];

    }

    public function participationWidgetData($eventData, $metaParams)
    {

        $uniqName = $eventData["uniq_name"];

        $participationWidget = $this->db->get("participations", "*", ["uniq_name" => $uniqName]);
        if (!empty($participationWidget)) {
            $participationUsers = $this->db->select("participation_users", "*", ["participation_id" => $participationWidget["id"]]) ?? [];
            $placesLeft = $participationWidget["max_user_count"] - count($participationUsers);

            $settings = json_decode($participationWidget["settings"], true);

            $existsParent = !empty($settings["parent_widget_id"]) ? $settings["parent_widget_id"] : false;
            if (!empty($existsParent)) {
                if ($this->db->get("participation_users", "id", ["participation_id" => $existsParent, "winned" => 1])) {
                    $existsParent = false;
                } else {
                    $parentWidget = $this->db->get("participations", "*", ["id" => $existsParent]);
                    $parentWidgetText = "Будет доступно после (" . $parentWidget["name"] . ")";
                }
            }

            $maxUsers = $participationWidget["max_user_count"];
            $currentUsers = count($participationUsers);

            $progress = ($currentUsers / $maxUsers) * 100;
            $progress = min(100, max(0, $progress)); // Ограничиваем от 0 до 100

            $progress = round($progress, 2) . "%";

            if ($placesLeft == 0) {
                $userWinner = $this->db->get("participation_users", "*", [
                    "participation_id" => $participationWidget["id"],
                    "winned" => 1
                ]);
                if (empty($userWinner)) {
                    $winner = $this->db->query("SELECT user_id FROM `participation_users` ORDER BY RAND() LIMIT 1")->fetch();
                    if ($winner) {
                        $userName = $this->db->get("users", "name", ["id" => $winner]);


                        if (!$userWinner) {
                            $this->db->update("participation_users", [
                                "winned" => 1,
                            ], [
                                "participation_id" => $participationWidget["id"],
                                "user_id" => $winner
                            ]);
                        }

                        $placesLeftText =  "Победитель ".$userName;
                        $winnerExists = true;
                    }
                } else {
                    $userName = $this->db->get("users", "name", ["id" => $userWinner["user_id"]]);
                    $placesLeftText =  "Победитель ".$userName;
                    $winnerExists = true;
                }

            } else {
                $placesLeftText = "Осталось мест ".$placesLeft." из ".$maxUsers;
            }

        }
        $participationWidget["settings"] = json_decode($participationWidget["settings"], true);

        $participationWidget["places_left_text"] = $placesLeftText ?? "";
        $participationWidget["winner_exists"] = $winnerExists ?? "";
        $participationWidget["current_users"] = $currentUsers ?? [];
        $participationWidget["progress"] = $progress ?? "";
        $participationWidget["handleUrl"] = "/widgets/handle?uniq_name=" . $uniqName . "&widget=participation";

        return [
           "widgetData" => $participationWidget
        ];

    }

    public function quizWidgetData($eventData, $metaParams)
    {

        $quiz = $this->db->get("quiz", "*", ["uniq_name" => $eventData["uniq_name"]]);
        if (!empty($quiz)) {
            $quizQuestions = $this->db->select("quiz_questions", "*", ["quiz_id" => $quiz["id"]]);
            if (!empty($quizQuestions)) {
                foreach ($quizQuestions as &$quizQuestion) {
                    $quizAnswers = $this->db->select("quiz_answers", "*", ["quiz_question_id" => $quizQuestion["id"]]);
                    $quizParticipations = $this->db->select("quiz_participations", "*", ["quiz_question_id" => $quizQuestion["id"]]);

                    foreach ($quizParticipations as $quizParticipation) {
                        if ($quizParticipation["user_id"] == $_SESSION["user_id"] ?? 0) {
                            $quizQuestion["answered"] = $quizParticipation["selected_option"];
                        }
                    }

                    foreach ($quizAnswers as &$quizAnswer) {
                        $quizAnswer["handleUrl"] = "/widgets/handle?uniq_name=" . $eventData["uniq_name"] . "&quiz_question_id=".$quizAnswer["quiz_question_id"]."&answer_id=".$quizAnswer["id"]."&widget=quiz";
                    }

                    $quizQuestion["answers"] = $quizAnswers;
                    $quizQuestion["participations"] = $quizParticipations;
                    $quizQuestion["participations_count"] = count($quizParticipations ?? []);
                }
            }
        }

        $quiz["user_id"] = $_SESSION["user_id"] ?? null;
        $quiz["questions"] = $quizQuestions ?? [];

        return [
            "widgetData" => $quiz
        ];
    }

}