<?php
require_once 'auth.php';

$auth = getAuth();
$message = null; // ['type' => 'error'|'success'|'info', 'text' => '...']
$verificationComplete = false;
$flash = $_SESSION['verification_flash'] ?? null;
unset($_SESSION['verification_flash']);

$prefillEmail = $flash['email'] ?? ($_SESSION['pending_verification_email'] ?? '');
if ($flash) {
    $message = [
        'type' => $flash['type'] ?? 'info',
        'text' => $flash['text'] ?? 'Verifica tu correo para continuar.'
    ];
}

$token = trim($_GET['token'] ?? '');
if ($token !== '') {
    $res = $auth->verifyAccountByToken($token);
    if (!empty($res['success']) && !empty($res['logged_in'])) {
        header('Location: ./');
        exit;
    }
    $message = [
        'type' => !empty($res['success']) ? 'success' : 'error',
        'text' => $res['message'] ?? 'No se pudo verificar la cuenta'
    ];
    $verificationComplete = !empty($res['success']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'verify_code';
    $email = trim($_POST['email'] ?? $prefillEmail);
    $code = trim($_POST['code'] ?? '');
    $prefillEmail = $email;

    if ($action === 'send_link' || $action === 'send_code' || $action === 'send_both') {
        $method = $action === 'send_link' ? 'link' : ($action === 'send_code' ? 'code' : 'both');
        $res = $auth->sendVerificationByEmail($email, $method);
        $message = [
            'type' => !empty($res['success']) ? 'success' : 'error',
            'text' => $res['message'] ?? 'No se pudo enviar la verificacion'
        ];
    } else {
        $res = $auth->verifyAccount($email, $code);
        if (!empty($res['success']) && !empty($res['logged_in'])) {
            header('Location: ./');
            exit;
        }
        $message = [
            'type' => !empty($res['success']) ? 'success' : 'error',
            'text' => $res['message'] ?? 'No se pudo verificar la cuenta'
        ];
        $verificationComplete = !empty($res['success']);
    }
}

$showVerificationForm = !$verificationComplete;
$headerTitle = $verificationComplete ? 'Cuenta verificada' : 'Verificar Cuenta';
$headerSubtitle = $verificationComplete
    ? 'Tu correo fue confirmado correctamente.'
    : 'Elige enlace o codigo para verificar tu correo';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <title>Verificar Cuenta</title>
    <style>
        * { box-sizing: border-box; }
        body { margin:0; min-height:100vh; display:grid; place-items:center; font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif; background:linear-gradient(135deg,#29648D 0%,#29648D 100%); }
        .card { width:100%; max-width:460px; background:#fff; border-radius:16px; box-shadow:0 20px 60px rgba(0,0,0,.3); overflow:hidden; }
        .header { padding:24px; text-align:center; color:#fff; background:linear-gradient(135deg,#29648D 0%,#29648D 100%); }
        .brand { font-weight:700; margin-top:6px; font-size:1.2rem; }
        .content { padding:22px; }
        label { display:block; color:#374151; font-size:.9rem; margin-top:14px; }
        .input { width:100%; padding:12px 14px; border:1px solid #e3e8ef; border-radius:10px; margin-top:8px; }
        .btn { width:100%; margin-top:12px; padding:12px 16px; border-radius:22px; border:none; background:linear-gradient(135deg,#1f6aa5,#29648D); color:#fff; font-weight:700; cursor:pointer; box-shadow:0 6px 18px rgba(41,100,141,.25); }
        .btn-secondary { background:#eef2f7; color:#274864; box-shadow:none; border:1px solid #d7dee8; }
        .actions { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:6px; }
        .actions .btn { margin-top:0; border-radius:12px; font-size:.88rem; padding:10px 12px; }
        .alert { padding:12px 14px; border-radius:10px; margin-bottom:12px; font-size:.9rem; }
        .alert.error { background:#fdecea; color:#b42318; border:1px solid #f1a7a1; }
        .alert.success { background:#ecfdf5; color:#027a48; border:1px solid #9ae6b4; }
        .alert.info { background:#eef2ff; color:#1e3a8a; border:1px solid #c7d2fe; }
        .footer { text-align:center; margin:14px 0 4px; }
        .footer a { color:#29648D; text-decoration:none; font-weight:600; }
        .hint { color:#6b7280; font-size:.85rem; line-height:1.45; margin-top:10px; }
        @media (max-width:520px) { .card { margin:16px; } .actions { grid-template-columns:1fr; } }
    </style>
</head>
<body>
    <div class="card">
        <div class="header">
            <div style="font-size:42px;">OK</div>
            <div class="brand"><?php echo htmlspecialchars($headerTitle); ?></div>
            <div><?php echo htmlspecialchars($headerSubtitle); ?></div>
        </div>
        <div class="content">
            <?php if ($message): ?>
                <div class="alert <?php echo htmlspecialchars($message['type']); ?>"><?php echo htmlspecialchars($message['text']); ?></div>
            <?php endif; ?>

            <?php if ($showVerificationForm): ?>
                <form method="post">
                    <label>Email
                        <input class="input" type="email" name="email" value="<?php echo htmlspecialchars($prefillEmail); ?>" required>
                    </label>
                    <label>Codigo de verificacion
                        <input class="input" type="text" name="code" maxlength="6" inputmode="numeric" autocomplete="one-time-code">
                    </label>
                    <button class="btn" type="submit" name="action" value="verify_code">Verificar con codigo</button>

                    <div class="hint">Tambien puedes solicitar un nuevo correo y elegir como recibir la verificacion.</div>
                    <div class="actions">
                        <button class="btn btn-secondary" type="submit" name="action" value="send_link" formnovalidate>Enviar enlace</button>
                        <button class="btn btn-secondary" type="submit" name="action" value="send_code" formnovalidate>Enviar codigo</button>
                    </div>
                    <button class="btn btn-secondary" type="submit" name="action" value="send_both" formnovalidate>Enviar enlace y codigo</button>
                </form>
            <?php endif; ?>

            <div class="footer">
                <a href="login">Volver al inicio de sesion</a>
            </div>
        </div>
    </div>
</body>
</html>
