<div class="m-y-0 hidden-sm-down"></div>
<div class="card rbLogin">
    <div class="card-block">
        <div class="card-title text-xs-center hidden">
            {{#logourl}}
                <h2><img src="{{logourl}}" title="{{sitename}}" alt="{{sitename}}"/></h2>
            {{/logourl}}
            {{^logourl}}
                <h2>{{sitename}}</h2>
            {{/logourl}}
        </div>

        {{#cansignup}}
            <div class="sr-only">
                <a href="{{signupurl}}">{{#str}} tocreatenewaccount {{/str}}</a>
            </div>
        {{/cansignup}}

        {{#error}}
            <div class="loginerrors m-t-1">
                <a href="#" id="loginerrormessage" class="accesshide">{{error}}</a>
                <div class="alert alert-danger" role="alert">{{error}}</div>
            </div>
        {{/error}}

        <div class="custom-login">
            <div class="login-container">
                <div class="left-column">
                    <div class="logo-section">
                        <img src="https://www.campuscrecer.pe/theme/eguru/img/icon-login.png" class="iconLogin" alt="Eguru">
                    </div>
                    <h2>Ingresa al Campus Crecer</h2>
                    <p class="login-subtitle">Ingresa tus credenciales para iniciar tu aprendizaje.</p>
                </div>

                <div class="right-column">
                    <form class="login-form" action="{{loginurl}}" method="post" id="login" {{^passwordautocomplete}}autocomplete="off"{{/passwordautocomplete}}>
                        <input id="anchor" type="hidden" name="anchor" value="">
                        <script>document.getElementById('anchor').value = location.hash;</script>
                        <input type="hidden" name="logintoken" value="{{logintoken}}">
                        <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response" value="">

                        <div id="policy-error" class="alert alert-danger" style="display: none;" role="alert">
                            Debe aceptar la política de privacidad
                        </div>

                        <div class="form-field">
                            <div class="input-container">
                              <span class="material-icons" style="color:#0e1d61">account_circle</span>
                                <input type="text"
                                       name="username"
                                       id="username"
                                       class="form-input"
                                       value="{{username}}"
                                       placeholder="Correo electrónico"
                                       required>
                            </div>
                        </div>

                        <div class="form-field">
                            <div class="input-container">
                              <span class="material-icons" style="color:#0e1d61">password</span>
                                <input type="password"
                                       name="password"
                                       id="password"
                                       class="form-input"
                                       placeholder="Contraseña"
                                       required
                                       {{^passwordautocomplete}}autocomplete="off"{{/passwordautocomplete}}>
                                <button type="button" class="password-toggle">
                                    <span class="material-icons">visibility</span>
                                </button>
                            </div>
                        </div>

                        <div id="privacy-policy-section" class="privacy-policy-section" style="display: none;">
                            <div class="form-check">
                                <input type="checkbox"
                                       name="privacy_policy"
                                       id="privacy-policy"
                                       value="1"
                                       class="form-check-input">
                                <label class="form-check-label" for="privacy-policy">
                                    Declaro que he leído y acepto expresamente la <a href="https://www.crecerseguros.pe/wp-content/uploads/2024/11/Politicas_de_datos_2024_V3.pdf" target="blank" class="policy-link">política de privacidad</a> de Crecer Seguros, y autorizo expresamente el <a href="https://www.crecerseguros.pe/wp-content/uploads/2025/01/Envio-de-Comunicaciones-con-fines-educativos_Usuarios-Nuevos-y-registrados-.pdf" target="blank">envío de comunicaciones</a> con fines educativos.
                                </label>
                            </div>
                        </div>

                        <button type="submit" class="login-button" id="loginbtn">Ingresar</button>

                        <div class="forgot-password">
                            <a href="{{forgotpasswordurl}}">¿Olvidaste tu contraseña?</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
        document.querySelector('.password-toggle')?.addEventListener('click', function() {
            const passwordInput = document.querySelector('#password');
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
        });
        </script>
    </div>
</div>

{{#js}}

require(['jquery', 'core/notification'], function($, Notification) {

    function checkPolicy() {
        var username = $('#username').val();
        if (username) {
            $.ajax({
                url: M.cfg.wwwroot + '/theme/eguru/login/check_policy.php',
                method: 'POST',
                data: { username: username },
                success: function(response) {
                    $('#privacy-policy-section').hide();
                    $('#privacy-policy').prop('required', false);
                    if (response === '0') {
                        $('#privacy-policy-section').show();
                        $('#privacy-policy').prop('required', true);
                    }
                }
            });
        }
    }

    function ejecutarReCaptcha() {
        return new Promise(function(resolve, reject) {
            if (typeof grecaptcha === 'undefined') {
                return reject('reCAPTCHA no está disponible');
            }
            grecaptcha.ready(function() {
                grecaptcha.execute('6LfQi4UrAAAAAF9q9g89R6B9OyKjFZXnZL4Sgq-y', {action: 'login'})
                    .then(resolve)
                    .catch(reject);
            });
        });
    }

    $('#login').on('submit', function(e) {
        e.preventDefault();

        var username = $('#username').val();
        var password = $('#password').val();
        var logintoken = $('input[name="logintoken"]').val();
        var privacyAccepted = $('#privacy-policy').is(':checked');
        var policyVisible = $('#privacy-policy-section').is(':visible');

        $('#policy-error').hide();

        if (!username || !password) {
            Notification.alert('Error', 'Por favor complete todos los campos');
            return false;
        }

        if (policyVisible && !privacyAccepted) {
            $('#policy-error').show();
            return false;
        }

        ejecutarReCaptcha().then(function(token) {
            $('#g-recaptcha-response').val(token);

            $.ajax({
                url: '{{{ config.wwwroot }}}/theme/eguru/login/index.php',
                method: 'POST',
                data: {
                    user: username,
                    pass: btoa(btoa(password) + logintoken),
                    privacy_policy: policyVisible ? (privacyAccepted ? 1 : 0) : undefined,
                    logintoken: logintoken,
                    'g-recaptcha-response': token
                },
                success: function(response) {
                    try {
                        if (response.status === 0) {
                            window.location.href = M.cfg.wwwroot + '/my/mycourses.php';
                        } else if (response.status === 2) {
                            $('#privacy-policy-section').show();
                            $('#policy-error').show();
                        } else if (response.status === 3) {
                            window.location.href = response.message;
                        } else {
                            Notification.alert('Error', response.message || 'Error en la autenticación');
                        }
                    } catch (e) {
                        console.error('Error processing response:', e);
                        Notification.alert('Error', 'Error en la respuesta del servidor');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Server error:', error);
                    console.error('Status:', status);
                    console.error('Response:', xhr.responseText);
                    Notification.alert('Error', 'Error de conexión con el servidor');
                }
            });

        }).catch(function(error) {
            console.error('Error ejecutando reCAPTCHA:', error);
            Notification.alert('Error', 'No se pudo verificar reCAPTCHA. Intente de nuevo.');
        });
    });

    $('.password-toggle').on('click', function() {
        var passwordInput = $('#password');
        var type = passwordInput.attr('type') === 'password' ? 'text' : 'password';
        passwordInput.attr('type', type);
    });

    checkPolicy();
    $('#username').on('change blur', checkPolicy);
});

{{/js}}
