<?php
$dbFile = __DIR__ . '/api/.db.db';
$downloadUrl = '';
$downloaderCode = '';
if (file_exists($dbFile)) {
    try {
        $sqlite = new SQLite3($dbFile);
        $result = $sqlite->query("SELECT value FROM settings WHERE key = 'app_download_url' LIMIT 1");
        $row = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
        $downloadUrl = $row['value'] ?? '';
        $result2 = $sqlite->query("SELECT value FROM settings WHERE key = 'app_downloader_code' LIMIT 1");
        $row2 = $result2 ? $result2->fetchArray(SQLITE3_ASSOC) : false;
        $downloaderCode = $row2['value'] ?? '';
    } catch (Throwable $e) {
        $downloadUrl = '';
        $downloaderCode = '';
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Consultar vencimiento de código</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-black text-white min-h-screen">
    <main class="max-w-2xl mx-auto px-6 py-14">
        <div class="bg-zinc-900 border border-zinc-800 rounded-3xl p-8 shadow-2xl">
            <div class="text-center mb-8">
                <div class="text-red-500 text-5xl mb-4"><i class="fa fa-key"></i></div>
                <h1 class="text-3xl font-black mb-2">Consultar código de acceso</h1>
                <p class="text-zinc-400">Ingresa tu código para ver la fecha y hora de expiración.</p>
            </div>

            <form id="checkForm" class="space-y-5">
                <div>
                    <label class="block text-sm font-semibold mb-2">Código</label>
                    <input id="codeInput" type="text" maxlength="12" class="w-full rounded-xl bg-zinc-950 border border-zinc-700 px-4 py-3 outline-none" placeholder="Ej: 123456" required>
                </div>
                <button id="checkBtn" class="w-full rounded-xl bg-red-600 hover:bg-red-700 py-3 font-bold" type="submit">
                    <i class="fa fa-search mr-2"></i>Consultar vencimiento
                </button>
            </form>

            <div id="result" class="hidden mt-8 rounded-2xl border border-emerald-700 bg-emerald-950/40 p-6">
                <div class="text-emerald-400 font-bold mb-2"><i class="fa fa-check-circle mr-2"></i>Código válido</div>
                <div class="text-2xl font-black tracking-widest" id="codeLabel">------</div>
                <p class="mt-4 text-zinc-200">Expira: <strong id="expiresAt"></strong></p>
                <p class="text-zinc-400 mt-2" id="timeLeft"></p>
            </div>

            <div id="errorBox" class="hidden mt-8 rounded-2xl border border-red-700 bg-red-950/40 p-6 text-red-300"></div>

            <?php if ($downloadUrl || $downloaderCode): ?>
            <div class="mt-8 text-center space-y-4">
                <?php if ($downloadUrl): ?>
                <div>
                    <a href="<?=htmlspecialchars($downloadUrl)?>" class="inline-flex items-center gap-2 rounded-full bg-white text-black px-5 py-3 font-bold">
                        <i class="fa fa-download"></i> Descargar app
                    </a>
                </div>
                <?php endif; ?>
                <?php if ($downloaderCode): ?>
                <div class="rounded-2xl border border-zinc-700 bg-zinc-950 p-4">
                    <div class="text-zinc-400 text-sm mb-1">Código downloader</div>
                    <div class="text-2xl font-black tracking-widest"><?=htmlspecialchars($downloaderCode)?></div>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <script>
    function formatDate(dateString) {
        const d = new Date(dateString.replace(' ', 'T'));
        if (isNaN(d.getTime())) return dateString;
        return d.toLocaleString();
    }

    function humanize(seconds) {
        if (seconds <= 0) return 'Expirado';
        const days = Math.floor(seconds / 86400);
        const hours = Math.floor((seconds % 86400) / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const parts = [];
        if (days) parts.push(days + ' día' + (days !== 1 ? 's' : ''));
        if (hours) parts.push(hours + ' hora' + (hours !== 1 ? 's' : ''));
        if (minutes) parts.push(minutes + ' minuto' + (minutes !== 1 ? 's' : ''));
        return parts.join(', ') || 'Menos de 1 minuto';
    }

    document.getElementById('checkForm').addEventListener('submit', async function (e) {
        e.preventDefault();
        const code = document.getElementById('codeInput').value.trim();
        const result = document.getElementById('result');
        const errorBox = document.getElementById('errorBox');
        result.classList.add('hidden');
        errorBox.classList.add('hidden');

        const formData = new FormData();
        formData.append('code', code);

        try {
            const response = await fetch('./api/check_code.php', { method: 'POST', body: formData });
            const data = await response.json();
            if (data.ok) {
                document.getElementById('codeLabel').textContent = code;
                document.getElementById('expiresAt').textContent = formatDate(data.expires_at);
                document.getElementById('timeLeft').textContent = 'Tiempo restante: ' + humanize(parseInt(data.seconds_left || 0, 10));
                result.classList.remove('hidden');
            } else {
                let message = 'Código no encontrado.';
                if (data.reason === 'expired') message = 'Este código ya expiró el ' + formatDate(data.expires_at || '');
                if (data.reason === 'blocked') message = 'Este código está bloqueado.';
                errorBox.textContent = message;
                errorBox.classList.remove('hidden');
            }
        } catch (err) {
            errorBox.textContent = 'No se pudo consultar el código. Intenta nuevamente.';
            errorBox.classList.remove('hidden');
        }
    });
    </script>
</body>
</html>
