<?php
require_once 'config.php';

$slug = trim($_GET['producto'] ?? 'Control_CF_IVA');
$slug = preg_replace('/[^A-Za-z0-9_]/', '', $slug);

$db = getDB();
$stmt = $db->prepare("SELECT * FROM productos WHERE slug = ? AND activo = 1");
$stmt->bind_param('s', $slug);
$stmt->execute();
$producto = $stmt->get_result()->fetch_assoc();
$stmt->close();
$db->close();

if (!$producto) {
    echo "Producto no encontrado."; exit;
}

$precio = (float)$producto['precio'];
$qrImagen = 'qr/' . $producto['qr_imagen'];
$nombreProducto = $producto['nombre'];
$slugProducto = $producto['slug'];

// Verificar si existe demo
$demoExists = file_exists(__DIR__ . '/descargas/demos/' . $slugProducto . '.xlsx');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($nombreProducto) ?> - Bolivia Impuestos</title>
    <style>
        :root {
            --dark: #2c3e50;
            --gray: #7f8c8d;
            --blue: #2980b9;
            --green: #27ae60;
            --green-dark: #219a52;
            --red: #e74c3c;
            --light: #f8f9fa;
            --white: #fff;
            --radius: 12px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Segoe UI', -apple-system, sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            padding: 20px 16px;
            color: #333;
        }
        .container { max-width: 460px; width: 100%; }

        .header {
            background: var(--dark);
            color: var(--white);
            padding: 28px 24px;
            text-align: center;
            border-radius: var(--radius) var(--radius) 0 0;
        }
        .header h1 { font-size: 18px; font-weight: 700; margin-bottom: 4px; }
        .header p { font-size: 13px; opacity: 0.7; }

        .card {
            background: var(--white);
            padding: 24px;
            border-bottom: 1px solid #eee;
        }
        .card:last-child {
            border-bottom: none;
            border-radius: 0 0 var(--radius) var(--radius);
        }

        /* Demo download */
        .demo-section { text-align: center; }
        .btn-demo {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 14px 32px;
            background: var(--green);
            color: var(--white);
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.2s;
        }
        .btn-demo:hover { background: var(--green-dark); }
        .btn-demo svg { width: 20px; height: 20px; }
        .demo-note { font-size: 12px; color: var(--gray); margin-top: 8px; }

        /* Steps */
        .step { display: none; }
        .step.active { display: block; }

        .section-title {
            font-size: 16px;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 18px;
            text-align: center;
        }

        /* Form */
        .field { margin-bottom: 12px; }
        .field label {
            display: block;
            font-size: 12px;
            font-weight: 600;
            color: var(--gray);
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        .field label .required { color: var(--red); }
        .field label .optional { color: #bbb; font-weight: 400; text-transform: none; }
        .field input {
            width: 100%;
            padding: 11px 14px;
            border: 1.5px solid #e0e6ed;
            border-radius: 8px;
            font-size: 15px;
            transition: border-color 0.2s;
            background: var(--white);
        }
        .field input:focus {
            outline: none;
            border-color: var(--blue);
            box-shadow: 0 0 0 3px rgba(41,128,185,0.1);
        }
        .field input::placeholder { color: #ccc; }
        .field input.error { border-color: var(--red); }

        .btn-pay {
            display: block;
            width: 100%;
            padding: 14px;
            background: var(--blue);
            color: var(--white);
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: background 0.2s;
            margin-top: 8px;
        }
        .btn-pay:hover { background: #2471a3; }
        .btn-pay:disabled { background: #bdc3c7; cursor: not-allowed; }

        /* QR step */
        .qr-wrapper { text-align: center; margin: 16px 0; }
        .qr-wrapper img {
            max-width: 220px;
            width: 100%;
            border-radius: 10px;
            border: 1px solid #eee;
        }
        .qr-monto {
            font-size: 24px;
            font-weight: 700;
            color: var(--dark);
            margin-top: 10px;
        }
        .polling-status {
            text-align: center;
            font-size: 14px;
            color: var(--gray);
            margin-top: 16px;
        }
        .polling-status .dots::after {
            content: '';
            animation: dots 1.5s infinite;
        }
        @keyframes dots {
            0% { content: ''; }
            25% { content: '.'; }
            50% { content: '..'; }
            75% { content: '...'; }
        }
        .btn-back {
            display: block;
            width: 100%;
            padding: 10px;
            background: none;
            border: 1.5px solid #e0e6ed;
            border-radius: 8px;
            color: var(--gray);
            font-size: 13px;
            cursor: pointer;
            margin-top: 12px;
        }

        /* Download step */
        .success-icon {
            text-align: center;
            font-size: 48px;
            color: var(--green);
            margin-bottom: 8px;
        }
        .success-text {
            text-align: center;
            font-size: 16px;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 4px;
        }
        .generating-text {
            text-align: center;
            font-size: 14px;
            color: var(--gray);
            margin-bottom: 16px;
        }

        /* Progress bar */
        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e8ecef;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        .progress-bar .fill {
            height: 100%;
            background: var(--green);
            border-radius: 3px;
            width: 0%;
            transition: width 0.3s ease;
        }

        .btn-download {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            width: 100%;
            padding: 16px;
            background: var(--green);
            color: var(--white);
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.2s;
        }
        .btn-download:hover { background: var(--green-dark); }
        .btn-download svg { width: 22px; height: 22px; }
        .download-info {
            text-align: center;
            font-size: 13px;
            color: var(--gray);
            margin-top: 12px;
            line-height: 1.6;
        }

        .error-msg {
            display: none;
            background: #fdf0f0;
            color: var(--red);
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 13px;
            text-align: center;
            margin-top: 12px;
        }
        .error-msg.visible { display: block; }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-top-color: var(--white);
            border-radius: 50%;
            animation: spin 0.7s linear infinite;
            vertical-align: middle;
            margin-right: 6px;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }

        .footer {
            text-align: center;
            padding: 16px;
            font-size: 11px;
            color: #bbb;
            background: var(--white);
            border-radius: 0 0 var(--radius) var(--radius);
        }
        .divider {
            height: 1px;
            background: linear-gradient(to right, transparent, #e0e0e0, transparent);
            margin: 0;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1><?= htmlspecialchars($nombreProducto) ?></h1>
        <p>Herramienta Excel para contadores &middot; boliviaimpuestos.com</p>
    </div>

    <!-- Demo download -->
    <?php if ($demoExists): ?>
    <div class="card demo-section">
        <a href="descargas/demos/<?= htmlspecialchars($slugProducto) ?>.xlsx" class="btn-demo" download>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            DESCARGAR DEMO
        </a>
        <div class="demo-note">Excel completo, solo lectura &middot; Gratis</div>
    </div>
    <div class="divider"></div>
    <?php endif; ?>

    <!-- STEP 1: Form -->
    <div class="card step active" id="step-form">
        <div class="section-title">OBTENER EXCEL COMPLETO &mdash; Bs <?= number_format($precio, 0) ?></div>
        <form id="purchase-form" onsubmit="return iniciarPago(event)">
            <div class="field">
                <label>Celular <span class="required">*</span></label>
                <input type="tel" id="celular" placeholder="70012345" required>
            </div>
            <div class="field">
                <label>Nombre <span class="optional">(opcional)</span></label>
                <input type="text" id="nombre" placeholder="Juan Perez">
            </div>
            <div class="field">
                <label>NIT <span class="optional">(opcional)</span></label>
                <input type="text" id="nit" placeholder="1234567013">
            </div>
            <button type="submit" class="btn-pay" id="btn-pay">PAGAR CON QR</button>
        </form>
        <div class="error-msg" id="error-form"></div>
    </div>

    <!-- STEP 2: QR + polling -->
    <div class="card step" id="step-qr">
        <div class="section-title">Escanea el QR para pagar</div>
        <div class="qr-wrapper">
            <img src="<?= htmlspecialchars($qrImagen) ?>" alt="QR de pago"
                 onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22200%22 height=%22200%22><rect fill=%22%23f8f9fa%22 width=%22200%22 height=%22200%22 rx=%2210%22/><text x=%2250%%22 y=%2250%%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 font-size=%2213%22 fill=%22%23bbb%22>QR no disponible</text></svg>'">
            <div class="qr-monto">Bs <?= number_format($precio, 2) ?></div>
        </div>
        <div class="polling-status">
            <span class="spinner" style="border-color:rgba(41,128,185,0.2);border-top-color:var(--blue);width:14px;height:14px;border-width:2px"></span>
            Verificando pago<span class="dots"></span>
        </div>
        <button class="btn-back" onclick="volverForm()">Volver</button>
    </div>

    <!-- STEP 3: Generating + Download -->
    <div class="card step" id="step-download">
        <!-- Generating state -->
        <div id="generating-state">
            <div class="success-icon">&#10003;</div>
            <div class="success-text">&iexcl;Pago recibido!</div>
            <div class="generating-text">Generando tu Excel personalizado...</div>
            <div class="progress-bar"><div class="fill" id="progress-fill"></div></div>
        </div>
        <!-- Ready state -->
        <div id="ready-state" style="display:none; animation: fadeIn 0.4s ease;">
            <div class="success-icon">&#10003;</div>
            <div class="success-text">Tu Excel esta listo</div>
            <br>
            <a id="btn-final-download" href="#" class="btn-download" download>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                DESCARGAR EXCEL
            </a>
            <div class="download-info">
                Tu Excel incluye tu licencia.<br>
                No necesitas contrase&ntilde;as.
            </div>
        </div>
        <div class="error-msg" id="error-download"></div>
    </div>

    <div class="footer">&copy; <?= date('Y') ?> boliviaimpuestos.com</div>
</div>

<script>
const PRECIO = <?= $precio ?>;
const SLUG = '<?= $slugProducto ?>';
let pollingInterval = null;

function showStep(stepId) {
    document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
    document.getElementById(stepId).classList.add('active');
}

function iniciarPago(e) {
    e.preventDefault();
    const celular = document.getElementById('celular').value.trim();
    const errEl = document.getElementById('error-form');

    if (!celular) {
        document.getElementById('celular').classList.add('error');
        errEl.textContent = 'El celular es obligatorio.';
        errEl.classList.add('visible');
        return false;
    }
    document.getElementById('celular').classList.remove('error');
    errEl.classList.remove('visible');

    showStep('step-qr');
    iniciarPolling();
    return false;
}

function volverForm() {
    detenerPolling();
    showStep('step-form');
}

function iniciarPolling() {
    detenerPolling();
    pollingInterval = setInterval(verificarPago, 3000);
}

function detenerPolling() {
    if (pollingInterval) {
        clearInterval(pollingInterval);
        pollingInterval = null;
    }
}

async function verificarPago() {
    try {
        const resp = await fetch('check.php?monto=' + PRECIO);
        const data = await resp.json();
        if (data.pagado) {
            detenerPolling();
            procesarCompra();
        }
    } catch (e) {}
}

async function procesarCompra() {
    showStep('step-download');
    
    // Animate progress bar
    const fill = document.getElementById('progress-fill');
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 85) progress = 85;
        fill.style.width = progress + '%';
    }, 300);

    const celular = document.getElementById('celular').value.trim();
    const nombre = document.getElementById('nombre').value.trim();
    const nit = document.getElementById('nit').value.trim();
    const errEl = document.getElementById('error-download');

    try {
        const fd = new FormData();
        fd.append('celular', celular);
        fd.append('nombre', nombre);
        fd.append('nit', nit);
        fd.append('producto', SLUG);

        const resp = await fetch('activar.php', { method: 'POST', body: fd });
        const data = await resp.json();

        clearInterval(progressInterval);

        if (data.ok) {
            fill.style.width = '100%';
            setTimeout(() => {
                document.getElementById('generating-state').style.display = 'none';
                document.getElementById('ready-state').style.display = 'block';
                document.getElementById('btn-final-download').href = 'descargar.php?token=' + data.token;
            }, 600);
        } else {
            fill.style.width = '0%';
            errEl.textContent = data.error || 'Error procesando compra.';
            errEl.classList.add('visible');
        }
    } catch (err) {
        clearInterval(progressInterval);
        errEl.textContent = 'Error de conexion. Contacta soporte.';
        errEl.classList.add('visible');
    }
}
</script>
</body>
</html>
