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

    // Запуск сессии
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    // Подключение к базе данных
    require_once(ENGINE_DIR . '/data/dbconfig.php');

    // Установка пустых значений для сообщений
    $smarty->assign('error_message', '');
    $smarty->assign('success_message', '');

    // Генерация уникального токена для формы
    $form_token = md5(uniqid(rand(), true));
    $smarty->assign('form_token', $form_token);

    if ($config["database_settings"]["enabled_database"] == "pgsql") {
        $security_question = $db_connect->get("security_questions", [
            "id", "question"
        ], [
            "ORDER" => \Medoo\Medoo::raw("RANDOM()"),
            "LIMIT" => 1
        ]) ?? [];
    } else {
        $security_question = $db_connect->get("security_questions", [
            "id", "question"
        ], [
            "ORDER" => \Medoo\Medoo::raw("RAND()"),
            "LIMIT" => 1
        ]) ?? [];
    }

    if ($security_question) {
        $smarty->assign('security_question_id', $security_question['id']);
        $smarty->assign('security_question_text', $security_question['question']);
    } else {
        //$smarty->assign('error_message', 'Не удалось загрузить вопрос безопасности.');
    }

    $email = "";
    if (isset($_GET["subs_uniq_id"]) && !empty($_GET["subs_uniq_id"])) {
        $userSubscription = $db_connect->get("user_subscriptions", "*", ["uniq_id" => $_GET["subs_uniq_id"]]);
        if (!empty($userSubscription)) {
            if (!empty($userSubscription["user_id"])) {
                $smarty->assign('error_message', "Эта ссылка больше не дейсвует");
            } else {
                $email = $userSubscription["email"];
            }
        } else {
            $smarty->assign('error_message', "Вы пытались вручную изменить хеш код, ваши действия отслеживаются");
        }
    }

    // Проверка и обработка POST-запроса на регистрацию
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_submit'])) {
        // Получение и очистка данных из формы
        $email = trim($_POST['reg_email']);
        $password = trim($_POST['reg_password']);
        $name = $_POST['reg_name'] ?? '';
        $age = $_POST['reg_age'] ?? '';
        $phone = $_POST['reg_phone'] ?? '';
        $city = $_POST['reg_city'] ?? '';
        $gender = $_POST['reg_gender'] ?? '';
        $security_question_id = $_POST['security_question_id'] ?? '';
        $security_answer = $_POST['security_answer'] ?? '';
        $form_token = $_POST['form_token'] ?? '';

        $isValid = true;

        // Проверка, что все обязательные поля заполнены
        if (empty($email) || empty($password) || empty($name)
            || $config["captcha_settings"]["enabled_captcha"] !== "google" && empty($security_answer)) {

            $smarty->assign('error_message', 'Все обязательные поля должны быть заполнены.');
            $errorMessage = 'Все обязательные поля должны быть заполнены.';
            $isValid = false;

        }

        $result = $db_connect->get("users", "id", ["email" => $email]);

        if (!empty($result)) {
            $smarty->assign('error_message', 'Этот email уже используется.');
            $errorMessage = 'Этот email уже используется.';
            $isValid = false;
        }

        if (isset($_GET["subs_uniq_id"]) && !empty($_GET["subs_uniq_id"])) {
            $userSubscription = $db_connect->get("user_subscriptions", "*", ["uniq_id" => $_GET["subs_uniq_id"]]);
            if (!empty($userSubscription)) {
                if (!empty($userSubscription["user_id"])) {
                    $errorMessage = "Регистрация не прошла, эта ссылка больше не дейсвует";
                    $isValid = false;
                }
            } else {
                $errorMessage = "Вы пытались вручную изменить хеш код, ваши действия отслеживаются";
                $isValid = false;
            }
        }

        if ($config["captcha_settings"]["enabled_captcha"] === "google") {

            $recaptcha_secret = $config["captcha_settings"]["api_secret_key"];
            $recaptcha_response = $_POST['g-recaptcha-response'];

            $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$recaptcha_secret}&response={$recaptcha_response}");
            $responseKeys = json_decode($response, true);

            if (intval($responseKeys["success"]) !== 1) {
                $smarty->assign('error_message', 'Ошибка при проверки капчи, попробуйте еще раз.');
                $errorMessage = 'Ошибка при проверки капчи, попробуйте еще раз.';
                $isValid = false;
            } else {
                $isValid = true;
            }

        } else {
            $question = $db_connect->get("security_questions", "answer", ["id" => $_POST["security_question_id"]]);

            if ($question && $security_answer !== $question) {
                $smarty->assign('error_message', 'Неправильный ответ на вопрос безопасности.');
                $errorMessage = 'Неправильный ответ на вопрос безопасности.';
                $isValid = false;
            }

        }

        $insertedUser = [];
        if ($isValid) {
            // Хэширование пароля
            $hashed_password = password_hash($password, PASSWORD_BCRYPT);
            $lastRecord = $db_connect->get("users", "id", [
                "ORDER" => ["id" => "DESC"],
                "LIMIT" => 1
            ]);

            $image = "uploads/profiles/default.svg";

            if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
                $dir = 'uploads/profiles/'. date('Y') . '/' . date('m') . '/' . $lastRecord+1;
                $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;

                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $file_count = count(scandir($uploadDir)) - 1;
                $imageName = $p_id . '_' . $file_count . '_' . basename($_FILES['image']['name']);
                $imagePath = $uploadDir . $imageName;

                if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
                    $image = $dir . $imageName;
                } else {
                    $error_message = "Не удалось переместить загруженный файл.";
                }
            }

            $currentPerms = [];
            if (!empty($config["default_roles"][$_POST["selected_role"]])) {
                foreach ($config["default_roles"][$_POST["selected_role"]] as $key => $value) {
                    $currentPerms[$value] = true;
                }
            }

            $group_id = $db_connect->get("roles", "id", ["name[~]" => "User"]);

            if (!empty($config["default_roles"]["roles_from_confirm"])) {
                foreach ($config["default_roles"]["roles_from_confirm"] as $roleFromConfirm) {
                    $_POST["selected_role"] = str_replace("#", "", $_POST["selected_role"]);
                    if ($_POST["selected_role"] === $roleFromConfirm) {

                        $fromConfirmGroupId = $db_connect->get("roles", "id", ["name[~]" => $roleFromConfirm]);

                        if (empty($fromConfirmGroupId)) {
                            $fromConfirmGroupId = $db_connect->max("roles", "id") + 1;

                            $data = [
                                "id" => $fromConfirmGroupId,
                                "name" => $roleFromConfirm,
                            ];
                            $data = array_merge($data, $currentPerms);

                            $db_connect->insert("roles", $data);

                        }

                        if ($config["enable_payed_roles"] === true) {
                            $db_connect->insert("user_applications", [
                                "user_id" => $lastRecord + 1,
                                "group_id" => (int)$fromConfirmGroupId,
                                "status" => "progress",
                                "payed_status" => "progress"
                            ]);

                            $_POST["selected_role"] = "User";
                        } else {
                            $_POST["selected_role"] = $roleFromConfirm;
                            $group_id = $db_connect->get("roles", "id", ["name[~]" => $roleFromConfirm]);
                        }

                    }
                }
            }

            // Установите group в 8
            //$group_id = 7;
            $referralCode = bin2hex(random_bytes(6));

            $referralId = 0;
            $receivedReferralCode = !empty($_POST["referral_code"]) ? $_POST["referral_code"] : $_SESSION["referrer_code"];
            if (!empty($receivedReferralCode)) {
                $referralId = $db_connect->get("users", "id", ["referral_code" => $receivedReferralCode]);
            }

            $insertedUser = $db_connect->insert("users", [
                "id" => $lastRecord + 1,
                "email" => $email,
                "password" => $hashed_password,
                "name" => $name,
              //  "group" => (int)$group_id,
                "age" => (int)$age ?? 0,
                "phone" => $phone,
                "city" => $city,
                "gender" => $gender,
                "referral_code" => $referralCode,
                "referrer_id" => (int)$referralId,
                "balance" => 0,
                "regdate" => date("Y-m-d H:i:s"),
                "avatar" => $image
            ]);

            $db_connect->insert("users_roles", [
                "user_id" => $db_connect->id(),
                "role_id" => $group_id,
            ]);

            $otherFields = [];
            foreach ($_POST as $key => $value) {
                if (str_starts_with($key, 'other_field_')) {
                    $newKey = substr($key, strlen('other_field_'));
                    $fieldId = $db_connect->get("registration_custom_fields", "id", ["name" => $newKey]);

                    $otherFields[$newKey]["val"] = $value;
                    $otherFields[$newKey]["field_id"] = $fieldId;

                    unset($_POST[$key]);
                }
            }

            if (!empty($otherFields)) {
                $insertData = [];
                foreach ($otherFields as $key => $data) {
                    $db_connect->insert("user_custom_fields", [
                        "user_id" => $lastRecord + 1,
                        "field_id" => $data["field_id"] ?? "",
                        "value" => $data["val"],
                        "created_at" => date("Y-m-d H:i:s")
                    ]);
                }
            }
        }

        if ($insertedUser) {
            if (isset($_GET["subs_uniq_id"]) && !empty($_GET["subs_uniq_id"])) {
                $db_connect->update("user_subscriptions", [
                    "user_id" => $lastRecord + 1,
                ], ["uniq_id" => $_GET["subs_uniq_id"]]);
            }

            sendEmail($email, "", "Successfully registration", [
                "name" => $name,
                "email" => $email,
                "url" => $_SERVER["HTTP_ORIGIN"]
            ], "registration-notice");

            $db_connect->insert("notifications", [
                "user_id" => $lastRecord + 1,
                "sender_id" => 0,
                "module_id" => 0,
                "module_type" => "system",
                "language" => "-",
                "created_at" => date("Y-m-d H:i:s"),
                "module_url" => "",
                "content" => "%%you_successfully_registered%%",
                "status" => 0,
                "svg_ico" => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-envelope" viewBox="0 0 16 16">
                                  <path d="M0 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zm2-1a1 1 0 0 0-1 1v.217l7 4.2 7-4.2V4a1 1 0 0 0-1-1zm13 2.383-4.708 2.825L15 11.105zm-.034 6.876-5.64-3.471L8 9.583l-1.326-.795-5.64 3.47A1 1 0 0 0 2 13h12a1 1 0 0 0 .966-.741M1 11.105l4.708-2.897L1 5.383z"/>
                                </svg>'
            ]);

            // Авторизация пользователя
            $_SESSION['user_id'] = $lastRecord + 1;
            $_SESSION['user_name'] = $name;
            $_SESSION['user_email'] = $email;
            $_SESSION['user_authenticated'] = true;
            $_SESSION['user_group_id'] = $group_id; // Сохраните группу в сессии

            $db_connect->update("users", ["balance" => $config["registration_award"]], ["id" => $_SESSION["user_id"]]);

            // Определяем, куда перенаправить пользователя после авторизации
            $redirectUrl = '/?registrationStatus=success';

            // Перенаправляем пользователя
            header("Location: $redirectUrl");
            exit;
        } else {
            $smarty->assign('error_message', $errorMessage ?? 'Произошла ошибка при регистрации. Пожалуйста, попробуйте снова. ' .$db_connect->error);
        }
    }

    $userCustomFields = $db_connect->select("registration_custom_fields", "*");
    $fieldsFromForm = [];
    foreach ($userCustomFields as &$userCustomField) {
        $userCustomField["group"] = $db_connect->get("roles", "name", ["id" => $userCustomField["group_id"]]);

        $string = str_replace('_', ' ', $userCustomField["name"]);
        $string = ucfirst($string);

        $fieldsFromForm[$userCustomField["group"]][] = [
          "name" => $userCustomField["name"],
          "type" => $userCustomField["type"],
          "label" => $string
        ];
    }

    $smarty->assign("email", $email);

    $smarty->assign("fieldsFromForm", $fieldsFromForm);
    // Отображение страницы регистрации
    $smarty->assign('registration', $smarty->fetch(TEMPLATES_DIR . '/' . $config['skin'] . '/registration.tpl'));
    $smarty->assign($config);