<?php
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/send_email.php';

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'] ?? '';
    $dni = $_POST['dni'] ?? '';

    // Validar que ambos campos estén completos
    if (empty($email) || empty($dni)) {
        $error = 'Por favor, complete todos los campos.';
    } else {
        global $db;
        // Buscar usuario por email y DNI
        $usuario = $db->fetchOne("SELECT id FROM usuarios WHERE email = ? AND dni = ?", [$email, $dni]);

        if ($usuario) {
            // Generar nueva contraseña temporal (8 caracteres)
            $nueva_password = bin2hex(random_bytes(4)); // Ej: a3f8d9e2
            $password_hash = password_hash($nueva_password, PASSWORD_DEFAULT);
            
            // Actualizar contraseña en la base de datos
            $db->update('usuarios', ['password' => $password_hash], ['id' => $usuario['id']]);
            
            // Enviar correo con la nueva contraseña
            $subject = 'Nueva contraseña - ' . APP_NAME;
            $message = "Estimado usuario,<br><br>"
                     . "Hemos generado una nueva contraseña para su cuenta:<br>"
                     . "Contraseña temporal: <strong>$nueva_password</strong><br><br>"
                     . "Le recomendamos cambiar esta contraseña después de iniciar sesión.<br><br>"
                     . "Atentamente,<br>"
                     . "El equipo de " . APP_NAME;

            if (sendEmail($email, $subject, $message, true)) {
                $success = 'Se ha enviado una nueva contraseña a su correo electrónico.';
            } else {
                $error = 'Error al enviar el correo. Por favor, intente más tarde.';
            }
        } else {
            $error = 'No se encontró una cuenta asociada a ese correo y DNI.';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Recuperar Contraseña | <?= APP_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
    :root {
        --primary-light: #e6f4ff;
        --primary-soft: #b3d9ff;
        --primary-medium: #66b2ff;
        --primary-dark: #1a75ff;
        --primary-deep: #0052cc;
        --light-color: #ffffff;
        --dark-color: #0a2e52;
        --success-color: #4cc9f0;
        --error-color: #f38d8d;
        --gray-medium: #e0e0e0;
    }
    
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        background: linear-gradient(135deg, var(--primary-soft) 0%, var(--primary-dark) 100%);
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        overflow-x: hidden;
        position: relative;
    }
    
    .floating-elements {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: 1;
        pointer-events: none;
    }
    
    .floating-element {
        position: absolute;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.3);
        animation: float 15s infinite linear;
        pointer-events: none;
        border: 2px solid rgba(102, 178, 255, 0.2);
    }
    
    .floating-element:nth-child(1) {
        width: 80px;
        height: 80px;
        top: 20%;
        left: 10%;
        animation-duration: 20s;
    }
    
    .floating-element:nth-child(2) {
        width: 120px;
        height: 120px;
        top: 60%;
        left: 80%;
        animation-duration: 25s;
        animation-delay: -5s;
    }
    
    .floating-element:nth-child(3) {
        width: 50px;
        height: 50px;
        top: 80%;
        left: 30%;
        animation-duration: 15s;
        animation-delay: -10s;
    }
    
    .floating-element:nth-child(4) {
        width: 90px;
        height: 90px;
        top: 40%;
        left: 70%;
        animation-duration: 30s;
        animation-delay: -7s;
    }
    
    .login-container {
        max-width: 420px;
        width: 100%;
        position: relative;
        z-index: 10;
    }
    
    .login-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 15px 35px rgba(10, 46, 82, 0.15);
        overflow: hidden;
        position: relative;
        z-index: 11;
    }
    
    .card-header {
        background: linear-gradient(120deg, var(--primary-medium), var(--primary-deep));
        padding: 30px 20px;
        text-align: center;
        color: white;
        position: relative;
        overflow: hidden;
    }
    
    .card-header::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
        transform: rotate(30deg);
        animation: shine 8s infinite;
    }
    
    .card-header h3 {
        font-size: 1.8rem;
        margin-bottom: 5px;
        position: relative;
        z-index: 2;
    }
    
    .card-body {
        padding: 30px;
    }
    
    .card-footer {
        background-color: var(--primary-light);
        padding: 20px;
        text-align: center;
        border-top: 1px solid var(--gray-medium);
        border-radius: 0 0 20px 20px;
    }
    
    .form-label {
        font-weight: 600;
        color: var(--dark-color);
        margin-bottom: 8px;
        display: block;
    }
    
    .input-group {
        position: relative;
        margin-bottom: 25px;
    }
    
    .input-group i {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--primary-dark);
        z-index: 1;
        pointer-events: none;
    }
    
    .form-control {
        border: none;
        border-bottom: 2px solid var(--gray-medium);
        padding: 12px 15px 12px 45px;
        width: 100%;
        font-size: 1rem;
        color: var(--dark-color);
        background: transparent;
    }
    
    .form-control:focus {
        border-color: var(--primary-dark);
        outline: none;
        background-color: rgba(26, 117, 255, 0.03);
    }
    
    .error-message {
        background-color: rgba(243, 141, 141, 0.1);
        border-left: 4px solid var(--error-color);
        padding: 12px 15px;
        margin-bottom: 20px;
        color: var(--error-color);
        border-radius: 4px;
        display: flex;
        align-items: center;
    }
    
    .success-message {
        background-color: rgba(76, 201, 240, 0.1);
        border-left: 4px solid var(--success-color);
        padding: 12px 15px;
        margin-bottom: 20px;
        color: var(--success-color);
        border-radius: 4px;
        display: flex;
        align-items: center;
    }
    
    .error-message i,
    .success-message i {
        margin-right: 10px;
    }
    
    .btn-login {
        background: linear-gradient(120deg, var(--primary-medium), var(--primary-deep));
        border: none;
        border-radius: 50px;
        padding: 12px;
        font-weight: 600;
        color: white;
        width: 100%;
        cursor: pointer;
    }
    
    .footer-link {
        color: var(--primary-deep);
        text-decoration: none;
        font-weight: 600;
    }
    
    .footer-link:hover {
        color: var(--primary-dark);
        text-decoration: underline;
    }
    
    .water-wave {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        overflow: hidden;
        line-height: 0;
        z-index: 0;
    }
    
    .water-wave svg {
        position: relative;
        display: block;
        width: calc(100% + 1.3px);
        height: 80px;
        transform: rotateY(180deg);
    }
    
    .water-wave .shape-fill {
        fill: var(--primary-light);
    }
    
    @keyframes float {
        0% {
            transform: translateY(0) rotate(0deg);
            opacity: 1;
        }
        100% {
            transform: translateY(-1000px) rotate(720deg);
            opacity: 0;
        }
    }
    
    @keyframes shine {
        0% {
            transform: rotate(30deg) translate(-10%, -10%);
        }
        100% {
            transform: rotate(30deg) translate(100%, 100%);
        }
    }
</style>
</head>
<body>
    <div class="floating-elements">
    <div class="floating-element"></div>
    <div class="floating-element"></div>
    <div class="floating-element"></div>
    <div class="floating-element"></div>
</div>
    <div class="login-container">
        <div class="login-card">
            <div class="card-header">
                <h3><i class="fas fa-graduation-cap me-2"></i><?= APP_NAME ?></h3>
                <p>Recuperación de contraseña</p>
            </div>
            
            <div class="card-body">
                <h4 style="text-align:center;color:var(--primary-deep);margin-bottom:25px;">
                    Recuperar Contraseña
                </h4>
                
                <?php if ($error): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
                </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                <div class="success-message">
                    <i class="fas fa-check-circle me-2"></i><?= $success ?>
                </div>
                <?php endif; ?>
                
                <form action="forgot_password.php" method="POST">
                    <div class="mb-4">
                        <label for="email" class="form-label">Correo Electrónico</label>
                        <div class="input-group">
                            <i class="fas fa-envelope"></i>
                            <input type="email" class="form-control" name="email" required placeholder="tucorreo@ejemplo.com">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label for="dni" class="form-label">DNI</label>
                        <div class="input-group">
                            <i class="fas fa-id-card"></i>
                            <input type="text" class="form-control" name="dni" required placeholder="Ingrese su DNI" maxlength="8">
                        </div>
                    </div>
                    
                    <div class="d-grid mt-4">
                        <button type="submit" class="btn btn-login">
                            Recuperar Contraseña
                        </button>
                    </div>
                </form>
            </div>
            
            <div class="card-footer">
                <p class="mb-0"><a href="login.php" class="footer-link">Volver al inicio de sesión</a></p>
            </div>
        </div>
    </div>
    
    <script>
        // Validar DNI: solo números y máximo 8 dígitos
        document.querySelector('input[name="dni"]').addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
            if (this.value.length > 8) {
                this.value = this.value.slice(0, 8);
            }
        });
    </script>
</body>
</html>