<?php
require_once __DIR__ . '/config/bootstrap.php';

$email   = strtolower(Validator::clean((string)($_GET['email'] ?? ''), 190));
$purpose = Validator::clean((string)($_GET['purpose'] ?? 'signup'), 20);
if (!Validator::email($email) || !in_array($purpose, ['signup', 'login', 'forget'], true)) {
    redirect('/login');
}
$otpLen = (int)env('OTP_LENGTH', 6);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP — DroidTester</title>
    <meta name="robots" content="noindex,nofollow">
    <meta name="theme-color" content="#1B7A43">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/landing.css">
    <link rel="stylesheet" href="/assets/css/auth.css">
    <link rel="stylesheet" href="/assets/css/responsive.css">
    <style>
        .otp-input-group { display:flex; gap:10px; justify-content:center; margin: 24px 0; }
        .otp-box {
            width: 50px; height: 56px; text-align: center; font-size: 24px; font-weight: 700;
            border: 2px solid var(--card-border); border-radius: 12px;
            background: var(--card-bg); color: var(--text-primary);
            transition: all 0.15s ease;
        }
        .otp-box:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(27,122,67,0.15); }
        .otp-box.filled { border-color: var(--primary); }
        .resend-row { text-align:center; font-size:13px; color: var(--text-secondary); margin-top: 16px; }
        .resend-row a { color: var(--primary); font-weight: 600; text-decoration: none; }
        .resend-row a.disabled { color: var(--text-muted); pointer-events: none; }
        .timer-text { color: var(--secondary); font-weight: 600; }
    </style>
</head>
<body class="auth-page">

    <nav class="navbar navbar-expand-lg public-navbar">
        <div class="container">
            <a class="navbar-brand-custom" href="/">
                <div class="navbar-logo-icon"><i class="bi bi-gear-fill"></i></div>
                DroidTester
            </a>
        </div>
    </nav>

    <div class="auth-content">
        <div class="auth-container" style="max-width: 540px; margin: 0 auto;">
            <div class="auth-badge text-center">
                <span class="badge-green"><i class="bi bi-shield-check" style="color:#FFD700"></i> Verify Your Email</span>
            </div>
            <h1 class="auth-title text-center">Enter the OTP</h1>
            <p class="auth-subtitle text-center mx-auto">
                We sent a <strong><?= $otpLen ?>-digit code</strong> to<br>
                <strong style="color: var(--primary)"><?= e($email) ?></strong>
            </p>

            <form id="otpForm" autocomplete="off">
                <input type="hidden" name="email" value="<?= e($email) ?>">
                <input type="hidden" name="purpose" value="<?= e($purpose) ?>">
                <input type="hidden" name="otp" id="otpHidden">

                <div class="otp-input-group" id="otpGroup">
                    <?php for ($i = 0; $i < $otpLen; $i++): ?>
                        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1"
                               class="otp-box" autocomplete="one-time-code"
                               <?= $i === 0 ? 'autofocus' : '' ?>>
                    <?php endfor; ?>
                </div>

                <button type="submit" class="auth-btn-main" id="verifyBtn" disabled>
                    Verify & Continue <i class="bi bi-arrow-right"></i>
                </button>

                <div class="resend-row">
                    Didn't receive the code?
                    <a href="#" id="resendLink" class="disabled">Resend in <span class="timer-text" id="resendTimer">60s</span></a>
                </div>

                <div class="text-center mt-3" style="font-size:13px">
                    <a href="/<?= $purpose === 'signup' ? 'register' : 'login' ?>" style="color: var(--text-secondary)">
                        <i class="bi bi-arrow-left"></i> Back
                    </a>
                </div>
            </form>
        </div>
    </div>

    <div class="auth-mini-footer">
        <div>
            <a href="/privacy-policy">Privacy Policy</a>
            <span class="separator">|</span>
            <a href="/terms-condition">Terms &amp; Condition</a>
        </div>
        <span class="copyright">© <?= date('Y') ?> DroidTester | Zodroid Media</span>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
    const Toast = Swal.mixin({
        toast: true, position: 'top-end', showConfirmButton: false,
        timer: 3500, timerProgressBar: true
    });

    // ───── OTP box auto-advance / paste / backspace ─────
    const boxes = document.querySelectorAll('.otp-box');
    const hidden = document.getElementById('otpHidden');
    const verifyBtn = document.getElementById('verifyBtn');

    function syncOtp() {
        const val = Array.from(boxes).map(b => b.value).join('');
        hidden.value = val;
        verifyBtn.disabled = val.length !== boxes.length;
    }

    boxes.forEach((box, i) => {
        box.addEventListener('input', e => {
            box.value = box.value.replace(/\D/g, '').slice(0, 1);
            box.classList.toggle('filled', box.value !== '');
            if (box.value && i < boxes.length - 1) boxes[i + 1].focus();
            syncOtp();
        });
        box.addEventListener('keydown', e => {
            if (e.key === 'Backspace' && !box.value && i > 0) boxes[i - 1].focus();
        });
        box.addEventListener('paste', e => {
            e.preventDefault();
            const text = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, boxes.length);
            text.split('').forEach((ch, idx) => {
                if (boxes[idx]) {
                    boxes[idx].value = ch;
                    boxes[idx].classList.add('filled');
                }
            });
            (boxes[Math.min(text.length, boxes.length - 1)]).focus();
            syncOtp();
        });
    });

    // ───── Submit ─────
    document.getElementById('otpForm').addEventListener('submit', async e => {
        e.preventDefault();
        const orig = verifyBtn.innerHTML;
        verifyBtn.disabled = true;
        verifyBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Verifying...';
        try {
            const fd = new FormData(e.target);
            const res = await fetch('/api/auth/verify-otp', { method: 'POST', body: fd });
            const data = await res.json();
            if (data.status === 'success') {
                Toast.fire({ icon: 'success', title: data.message });
                setTimeout(() => { window.location.href = (data.data && data.data.redirect) || '/dashboard'; }, 600);
            } else {
                Toast.fire({ icon: 'error', title: data.message });
                verifyBtn.innerHTML = orig;
                syncOtp();
            }
        } catch {
            Toast.fire({ icon: 'error', title: 'Network error.' });
            verifyBtn.innerHTML = orig;
            syncOtp();
        }
    });

    // ───── Resend cooldown timer ─────
    let cooldown = 60;
    const resendLink = document.getElementById('resendLink');
    const resendTimer = document.getElementById('resendTimer');
    const tick = setInterval(() => {
        cooldown--;
        if (cooldown <= 0) {
            clearInterval(tick);
            resendLink.classList.remove('disabled');
            resendLink.innerHTML = 'Resend OTP';
        } else {
            resendTimer.textContent = cooldown + 's';
        }
    }, 1000);

    resendLink.addEventListener('click', async e => {
        e.preventDefault();
        if (resendLink.classList.contains('disabled')) return;
        resendLink.classList.add('disabled');
        try {
            const fd = new FormData();
            fd.append('email', '<?= e($email) ?>');
            fd.append('purpose', '<?= e($purpose) ?>');
            const res = await fetch('/api/auth/resend-otp', { method: 'POST', body: fd });
            const data = await res.json();
            if (data.status === 'success') {
                Toast.fire({ icon: 'success', title: 'OTP re-sent.' });
                cooldown = 60;
                resendLink.innerHTML = 'Resend in <span class="timer-text" id="resendTimer">60s</span>';
                const newTimer = document.getElementById('resendTimer');
                const t2 = setInterval(() => {
                    cooldown--;
                    if (cooldown <= 0) {
                        clearInterval(t2);
                        resendLink.classList.remove('disabled');
                        resendLink.innerHTML = 'Resend OTP';
                    } else newTimer.textContent = cooldown + 's';
                }, 1000);
            } else {
                Toast.fire({ icon: 'error', title: data.message });
                resendLink.classList.remove('disabled');
            }
        } catch {
            Toast.fire({ icon: 'error', title: 'Network error.' });
            resendLink.classList.remove('disabled');
        }
    });
    </script>
</body>
</html>
