<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="Registro de usuario - Paso 1">
        <link rel="icon" type="image/png" href="<?= BASE_HREF ?>assets/favicon.png">
        <title>Recuperar cuenta | Sistema de Trámite</title>
        <!-- CSS -->
        <link rel="stylesheet" href="<?= BASE_HREF ?>css/simplebar.css">
        <link rel="stylesheet" href="<?= BASE_HREF ?>css/feather.css">
        <link rel="stylesheet" href="<?= BASE_HREF ?>css/daterangepicker.css">
        <link rel="stylesheet" href="<?= BASE_HREF ?>css/app-light.css" id="lightTheme">
        <link rel="stylesheet" href="<?= BASE_HREF ?>css/app-dark.css" id="darkTheme" disabled>
    </head>

    <body class="d-flex align-items-center justify-content-center bg-light" style="min-height: 100vh;">
        <div class="container my-5">

            <?php if (isset($_SESSION['message'])): ?>
                <div class="alert alert-<?php echo $_SESSION['message_type']; ?>">
                    <?php 
                        echo $_SESSION['message']; 
                        unset($_SESSION['message']);
                    ?>
                </div>
            <?php endif; ?>

            <div class="row justify-content-center">
            <div class="col-md-10 col-lg-6">
                <div class="card shadow-lg">
                <div class="card-body p-4">
                    <form id="change-password-form" action="<?= BASE_ACTION ?>auth/reset-password" method="POST" >
                        <input type="hidden" name="token" value="<?= htmlspecialchars($_GET['token'] ?? '') ?>">

                        <div class="text-center mb-2">
                            <h4 class="mb-0 font-weight-bold">MESA DE PARTES DIGITAL</h4>
                            <small class="text">UGEL CORONGO</small>
                        </div>
                        <div class="d-flex justify-content-center mb-4">
                            <a href="<?= BASE_HREF ?>">
                                <img src="<?= BASE_SRC ?>assets/favicon.png" alt="Logo del sistema" class="navbar-brand-img brand-sm" style="height: 100px; width: auto;">
                            </a>
                        </div>

                        <h4 class="text-center mb-4">Recupera tu cuenta</h4>

                        <div class="mb-3">
                            <label for="password" class="form-label">Nueva Contraseña</label>
                            <input type="password" name="password" class="form-control" id="password" required>
                            <div id="password_requirements" class="mt-2 text-muted small">
                                <div id="req-length">✘ Mínimo 8 caracteres</div>
                                <div id="req-alphanumeric">✘ Contener letras y números</div>
                                <div id="req-no-special">✘ Sin caracteres especiales</div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="confirm_password" class="form-label">Confirmar Contraseña</label>
                            <input type="password" name="confirm_password" class="form-control" id="confirm_password" required>
                            <div id="password_feedback" class="form-text mt-1"></div>
                        </div>

                        <button type="submit" class="btn btn-primary btn-block">Actualizar Contraseña</button>
                    </form>
                </div>
                </div>
            </div>
            </div>
        </div>


        <script>
            document.addEventListener("DOMContentLoaded", function () {

                document.querySelectorAll("input[required], select[required], textarea[required]").forEach(function (input) {
                    let label = document.querySelector(`label[for="${input.id}"]`);
                    if (label && !label.innerHTML.includes("*")) {
                        label.innerHTML += ' <span class="text-danger">*</span>';
                    }
                });

                const fieldsToUpper = ["confirm_password", "password"];
                fieldsToUpper.forEach(id => {
                    const field = document.getElementById(id);
                    if (field) {
                        field.addEventListener("input", function (event) {
                            event.target.value = event.target.value.toUpperCase();
                        });
                    }
                });

                const newPassword = document.getElementById("password");
                const confirmPassword = document.getElementById("confirm_password");
                const passwordFeedback = document.getElementById("password_feedback");
                const form = document.querySelector("form");

                const reqLength = document.getElementById("req-length");
                const reqAlphaNum = document.getElementById("req-alphanumeric");
                const reqNoSpecial = document.getElementById("req-no-special");

                const minLength = 8;

                function updateRequirement(element, condition) {
                    element.textContent = (condition ? "✔" : "✘") + " " + element.textContent.slice(2);
                    element.classList.toggle("text-success", condition);
                    element.classList.toggle("text-danger", !condition);
                }

                function validatePassword() {
                    const password = newPassword.value;

                    const hasMinLength = password.length >= minLength;
                    const hasLetter = /[A-Z]/i.test(password);
                    const hasNumber = /\d/.test(password);
                    const noSpecialChars = /^[A-Z0-9]+$/i.test(password);

                    updateRequirement(reqLength, hasMinLength);
                    updateRequirement(reqAlphaNum, hasLetter && hasNumber);
                    updateRequirement(reqNoSpecial, noSpecialChars);

                    if (password.toUpperCase() !== confirmPassword.value.toUpperCase()) {
                        passwordFeedback.textContent = "Las contraseñas no coinciden";
                        passwordFeedback.classList.add("text-danger");
                        passwordFeedback.classList.remove("text-success");
                    } else {
                        passwordFeedback.textContent = "Las contraseñas coinciden";
                        passwordFeedback.classList.add("text-success");
                        passwordFeedback.classList.remove("text-danger");
                    }
                }

                newPassword.addEventListener("input", validatePassword);
                confirmPassword.addEventListener("input", validatePassword);

                document.getElementById("change-password-form").addEventListener("submit", function (e) {
                    const value = newPassword.value;

                    const hasMinLength = value.length >= minLength;
                    const hasLetterAndNumber = /[a-zA-Z]/.test(value) && /\d/.test(value);
                    const noSpecialChars = /^[a-zA-Z0-9]+$/.test(value);

                    const valid = hasMinLength && hasLetterAndNumber && noSpecialChars;

                    if (!valid) {
                        e.preventDefault();
                        passwordFeedback.textContent = "La contraseña no cumple con todos los requisitos.";
                        passwordFeedback.className = "text-danger";
                    }
                });

                validatePassword();
            });
        </script>
    </body>
</html>