<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

$page_title = 'Recuperar contraseña';
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = 'Token de seguridad inválido.';
    } else {
        $email = sanitize($_POST['email'] ?? '');
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Ingresa un correo válido.';
        } else {
            $db = db();
            $stmt = $db->prepare('SELECT id FROM usuarios WHERE email = ? AND activo = 1');
            $stmt->execute([$email]);
            $usuario = $stmt->fetch();
            if (!$usuario) {
                $success = 'Si el correo existe, recibirás instrucciones para recuperar tu contraseña.';
            } else {
                $token = bin2hex(random_bytes(32));
                $expiracion = date('Y-m-d H:i:s', strtotime('+1 hour'));
                $stmt = $db->prepare('INSERT INTO recuperacion_password (usuario_id, token, expiracion) VALUES (?, ?, ?)');
                $stmt->execute([$usuario['id'], $token, $expiracion]);
                $success = 'Si el correo existe, recibirás instrucciones para recuperar tu contraseña.';
            }
            csrf_regenerate();
        }
    }
}

require_once __DIR__ . '/../includes/header.php';
?>
<section class="py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="auth-card card shadow-sm border-0">
                    <div class="card-body p-4">
                        <div class="text-center mb-4">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width:72px;height:72px;">
                                <i class="bi bi-key-fill text-primary fs-1"></i>
                            </div>
                            <h1 class="h4 fw-bold mb-1">Recuperar Contraseña</h1>
                            <p class="text-muted small mb-0">Ingresa tu correo para restablecer la contraseña.</p>
                        </div>
                        <?php if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>
                        <?php if ($success): ?><div class="alert alert-success"><?= e($success) ?></div><?php endif; ?>
                        <form method="POST" novalidate>
                            <?= csrf_field() ?>
                            <div class="mb-3">
                                <label for="email" class="form-label fw-medium">Correo electrónico</label>
                                <input type="email" class="form-control" id="email" name="email" required placeholder="tucorreo@ejemplo.com">
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary btn-lg">Enviar instrucciones</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
