{if $error_message}
    <div class="alert alert-danger" role="alert">
        {$error_message}
    </div>
{/if}

{if $success_message}
    <div class="alert alert-success" role="alert">
        {$success_message}
    </div>
{/if}


{if !$hideRegistrationForm }
<form id="registration-form" method="POST" class="needs-validation" novalidate enctype="multipart/form-data">
    <input type="hidden" name="form_token" value="{$form_token}">
    <input type="hidden" name="selected_role" id="selected_role" value="User"> <!-- Скрытое поле -->

    <!-- Навигация по ролям -->
    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
        {foreach $config.default_roles as $key => $role}
            {if $key != "roles_from_confirm"}
                <li class="nav-item" role="presentation">
                    <button class="nav-link {if $key == "User"} active {/if}" id="pills-{$key}"
                            data-bs-toggle="pill" data-bs-target="#pills-{$key}-content"
                            type="button" role="tab" aria-controls="pills-{$key}-content"
                            aria-selected="{if $key == "User"}true{else}false{/if}"
                            onclick="updateRole('{$key}')">
                        {$key}
                    </button>
                </li>
            {/if}
        {/foreach}
    </ul>
    <!-- Контент вкладок -->
    <div class="tab-content" id="pills-tabContent">
        {foreach $config.default_roles as $key => $role}
            {if $key != "roles_from_confirm"}
                <div class="tab-pane fade {if $key == "User"}show active{/if}"
                     id="pills-{$key}-content" role="tabpanel" aria-labelledby="pills-{$key}">
                    <div class="container px-0" id="{$key}">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_name">Name*:</label>
                                    <input type="text" name="reg_name" id="reg_name" class="form-control" required>
                                    <div class="invalid-feedback">Please provide your name.</div>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_email">Email*:</label>
                                    <input type="email" name="reg_email" id="reg_email" class="form-control" required>
                                    <div class="invalid-feedback">Please provide a valid email.</div>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_password">Password*:</label>
                                    <input type="password" name="reg_password" id="reg_password" class="form-control" required>
                                    <div class="invalid-feedback">Please provide a password.</div>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_password_repeat">Repeat password*:</label>
                                    <input type="password" name="reg_password_repeat" id="reg_password_repeat" class="form-control" required>
                                    <div class="invalid-feedback">Please repeat your password.</div>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_age">Age:</label>
                                    <input type="number" name="reg_age" id="reg_age" class="form-control">
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_phone">Phone:</label>
                                    <input type="text" name="reg_phone" id="reg_phone" class="form-control">
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_city">City:</label>
                                    <input type="text" name="reg_city" id="reg_city" class="form-control">
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="reg_gender">Gender:</label>
                                    <select name="reg_gender" id="reg_gender" class="form-control">
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-6 mb-3">
                                <div class="form-group">
                                    <label for="referral_code">Referral code:</label>
                                    <input type="text" name="referral_code" id="referral_code" class="form-control">
                                </div>
                            </div>

                            <label for="profileImage">Profile avatar</label>
                            <input id="profileImage" name="image" type="file" accept="image/*" style="margin-bottom: 10px" />
                            <p id="error" style="color: red; display: none;">Изображение должно быть минимум 300x300 пикселей.</p>

                            {foreach $fieldsFromForm as $group => $data}
                                {if $group == {$key}}
                                    {foreach $data as $dataAssoc}
                                        <div class="col-md-6 mb-3">
                                            <div class="form-group">
                                                <label for="referral_code">{$dataAssoc.label}:</label>
                                                <input type="{$dataAssoc.type}" name="other_field_{$dataAssoc.name}" id="{$dataAssoc.name}" class="form-control">
                                            </div>
                                        </div>
                                    {/foreach}
                                {/if}
                            {/foreach}

                            <div class="col-md-12 mb-3">
                                <div class="form-group">
                                    <label for="security_answer">Вопрос*: {$security_question_text}</label>
                                    <input type="text" name="security_answer" id="security_answer" class="form-control" placeholder="Только цифры" required>
                                    <input type="hidden" name="security_question_id" value="{$security_question_id}">
                                    <div class="invalid-feedback">Please provide an answer to the security question.</div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

            {/if}
        {/foreach}
    </div>
    <div class="col-md-12">
        <button type="submit" name="register_submit" class="btn btn-primary w-100">Register</button>
    </div>
</form>

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>

{literal}
    <script>
        function updateRole(role) {
            document.getElementById("selected_role").value = role;
        }

        document.addEventListener('DOMContentLoaded', function () {
            var form = document.getElementById('registration-form');

            form.addEventListener('submit', function (event) {
                let activeTab = document.querySelector(".tab-pane.active"); // Получаем активную вкладку
                let allTabs = document.querySelectorAll(".tab-pane");

                var activeForm;
                allTabs.forEach(tab => {
                    let isActive = tab.classList.contains("show") && tab.classList.contains("active");

                    tab.querySelectorAll("input, select, textarea").forEach(input => {
                        input.disabled = !isActive; // Отключаем только неактивные вкладки
                    });

                    if (isActive) {
                        activeForm = tab.querySelector("form");
                        if (activeForm) {
                            console.log("Активная форма:", activeForm);
                        }
                    }
                });

                var selectedRole = $("#selected_role").val();
                var userDiv = document.getElementById(selectedRole);
                var password = userDiv.querySelector('#reg_password');
                var passwordRepeat = userDiv.querySelector('#reg_password_repeat');

                let isValid = true;

                $("#"+selectedRole).find(".invalid-feedback").hide();

                $("#"+selectedRole).find("input[required], select[required]").each(function () {
                    if ($(this).val().trim() === "") {
                        isValid = false;
                        $(this).siblings(".invalid-feedback").show();
                    }
                });

                if (!isValid) {
                    event.preventDefault(); // Отменяет отправку формы
                }

                if (password.value !== passwordRepeat.value) {
                    event.preventDefault();
                    event.stopPropagation();
                    // Добавляем класс ошибки для отображения сообщения
                    passwordRepeat.classList.add('is-invalid');
                    passwordRepeat.nextElementSibling.textContent = 'Passwords do not match.';
                } else {
                    passwordRepeat.classList.remove('is-invalid');
                    passwordRepeat.classList.add('is-valid');
                }

                form.classList.add('was-validated');
            }, false);
        });
    </script>
{/literal}
{/if}


