<?php
require_once 'config.php';

$productoSlug = isset($_GET['producto']) ? trim($_GET['producto']) : '';
$pc = isset($_GET['pc']) ? htmlspecialchars(trim($_GET['pc'])) : '';
$precioParam = isset($_GET['precio']) ? (float)$_GET['precio'] : 0;

$producto = null;
$precio = PRECIO_DEFAULT;
$qrImagen = 'qr/qr-general.jpg';

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

if ($producto) {
    $precio = (float)$producto['precio'];
    $qrImagen = 'qr/' . $producto['qr_imagen'];
    $nombreProducto = $producto['nombre'];
} else {
    $precio = $precioParam > 0 ? $precioParam : PRECIO_DEFAULT;
    $nombreProducto = $productoSlug ?: 'Producto';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Activar <?= htmlspecialchars($nombreProducto) ?> - Bolivia Impuestos</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Segoe UI', sans-serif; background: #f0f2f5; min-height: 100vh; display: flex; justify-content: center; align-items: flex-start; padding: 20px; }
        .container { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); max-width: 480px; width: 100%; overflow: hidden; }
        .header { background: linear-gradient(135deg, #1a5276, #2980b9); color: #fff; padding: 20px; text-align: center; }
        .header h1 { font-size: 18px; margin-bottom: 4px; }
        .header p { font-size: 13px; opacity: 0.9; }
        .body { padding: 20px; }
        .field { margin-bottom: 14px; }
        .field label { display: block; font-size: 13px; font-weight: 600; color: #555; margin-bottom: 4px; }
        .field input { width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
        .field input[readonly] { background: #f8f9fa; color: #666; }
        .field input:focus { outline: none; border-color: #2980b9; }
        .pc-badge { background: #e8f4fd; border: 2px solid #2980b9; border-radius: 8px; padding: 12px; text-align: center; margin-bottom: 16px; }
        .pc-badge .code { font-family: 'Courier New', monospace; font-size: 22px; font-weight: bold; color: #1a5276; letter-spacing: 2px; }
        .pc-badge .label { font-size: 11px; color: #666; margin-bottom: 4px; }
        .qr-section { text-align: center; margin: 20px 0; padding: 16px; background: #f8f9fa; border-radius: 8px; }
        .qr-section img { max-width: 250px; border-radius: 8px; }
        .monto-warning { background: #fff3cd; border: 2px solid #ffc107; border-radius: 8px; padding: 10px; margin: 12px 0; font-size: 13px; color: #856404; }
        .monto-warning b { font-size: 15px; }
        .status { text-align: center; padding: 16px; border-radius: 8px; margin-top: 16px; font-size: 14px; }
        .status.waiting { background: #fff3cd; color: #856404; }
        .status.error { background: #f8d7da; color: #721c24; }
        .password-display { text-align: center; margin: 20px 0; padding: 20px; background: #d4edda; border-radius: 8px; }
        .password-display .pass { font-size: 32px; font-weight: bold; letter-spacing: 4px; color: #155724; font-family: 'Courier New', monospace; user-select: all; }
        .instrucciones { background: #e8f4fd; border-radius: 8px; padding: 16px; margin-top: 16px; font-size: 13px; color: #1a5276; }
        .instrucciones h3 { font-size: 14px; margin-bottom: 8px; }
        .instrucciones ol { padding-left: 20px; }
        .instrucciones li { margin-bottom: 6px; }
        .btn { display: block; width: 100%; padding: 12px; background: #2980b9; color: #fff; border: none; border-radius: 6px; font-size: 15px; font-weight: 600; cursor: pointer; }
        .btn:hover { background: #1a5276; }
        .copy-btn { background: #27ae60; margin-top: 10px; }
        .copy-btn:hover { background: #1e8449; }
        .spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid #856404; border-top-color: transparent; border-radius: 50%; animation: spin 0.8s linear infinite; vertical-align: middle; margin-right: 6px; }
        @keyframes spin { to { transform: rotate(360deg); } }
        .hidden { display: none; }
        .footer { text-align: center; padding: 12px; font-size: 11px; color: #999; border-top: 1px solid #eee; }
        .warning-share { background: #f8d7da; border-radius: 6px; padding: 10px; margin-top: 12px; font-size: 12px; color: #721c24; text-align: center; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>Activar <?= htmlspecialchars($nombreProducto) ?></h1>
        <p>boliviaimpuestos.com</p>
    </div>
    <div class="body">
        <?php if ($pc): ?>
        <div class="pc-badge">
            <div class="label">Tu codigo de PC</div>
            <div class="code"><?= $pc ?></div>
        </div>
        <?php endif; ?>

        <div id="step-form">
            <input type="hidden" id="producto" value="<?= htmlspecialchars($productoSlug) ?>">
            <input type="hidden" id="pc" value="<?= $pc ?>">
            <div class="field"><label>Precio</label><input type="text" value="Bs. <?= number_format($precio, 2) ?>" readonly></div>
            <hr style="margin:16px 0;border:none;border-top:1px solid #eee">
            <div class="field"><label>Celular (WhatsApp) *</label><input type="tel" id="celular" placeholder="Ej: 70012345" required></div>
            <div class="field"><label>Nombre (opcional)</label><input type="text" id="nombre" placeholder="Tu nombre"></div>
            <div class="field"><label>NIT (para factura, opcional)</label><input type="text" id="nit" placeholder="Tu NIT"></div>
            <button class="btn" onclick="iniciarPago()">Continuar al pago</button>
        </div>

        <div id="step-pago" class="hidden">
            <div class="qr-section">
                <p style="margin-bottom:8px"><b>Escanea con Yape Bolivia</b></p>
                <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=%22250%22 height=%22250%22><rect fill=%22%23f0f0f0%22 width=%22250%22 height=%22250%22/><text x=%2250%%22 y=%2250%%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 font-size=%2214%22 fill=%22%23999%22>QR no disponible</text></svg>'">
            </div>
            <div class="monto-warning">
                Ingresa EXACTAMENTE este monto en Yape:<br>
                <b>Bs. <?= number_format($precio, 2) ?></b><br>
                <small>El sistema detecta el pago automaticamente por el monto exacto.</small>
            </div>
            <div id="status-pago" class="status waiting">
                <span class="spinner"></span> Esperando pago...
            </div>
        </div>

        <div id="step-password" class="hidden">
            <div class="password-display">
                <p style="margin-bottom:8px;font-size:13px">Tu contrasena de desbloqueo:</p>
                <div class="pass" id="password-value"></div>
            </div>
            <button class="btn copy-btn" onclick="copiarPassword()">Copiar contrasena</button>
            <div id="copy-msg" class="hidden" style="text-align:center;color:#27ae60;margin-top:8px;font-size:13px">Copiada!</div>

            <div class="instrucciones">
                <h3>Como desbloquear tu Excel:</h3>
                <ol>
                    <li>Abre tu archivo Excel</li>
                    <li>Ve a la pestana <b>Revisar</b> (o <b>Review</b>)</li>
                    <li>Haz clic en <b>Desproteger hoja</b></li>
                    <li>Pega la contrasena</li>
                    <li>Repite para cada hoja</li>
                </ol>
            </div>
            <div class="warning-share">
                Esta contrasena solo funciona en TU computadora.<br>
                Si cambias de PC debes activar de nuevo.
            </div>
        </div>
    </div>
    <div class="footer">&copy; <?= date('Y') ?> boliviaimpuestos.com</div>
</div>

<script>
let pollingInterval = null, pollingCount = 0;
const PRECIO = <?= $precio ?>;

function iniciarPago() {
    const cel = document.getElementById('celular').value.trim();
    if (!cel || cel.length < 7) { alert('Ingresa un numero de celular valido'); return; }
    document.getElementById('step-form').classList.add('hidden');
    document.getElementById('step-pago').classList.remove('hidden');
    pollingCount = 0;
    pollingInterval = setInterval(verificarPago, 4000);
}

function verificarPago() {
    if (++pollingCount > 150) {
        clearInterval(pollingInterval);
        document.getElementById('status-pago').className = 'status error';
        document.getElementById('status-pago').innerHTML = 'Tiempo agotado. Recarga la pagina.';
        return;
    }
    fetch('check.php?monto=' + PRECIO + '&t=' + Date.now()).then(r=>r.json()).then(d=>{
        if (d.pagado) { clearInterval(pollingInterval); confirmarPago(); }
    }).catch(()=>{});
}

function confirmarPago() {
    const fd = new FormData();
    fd.append('producto', document.getElementById('producto').value);
    fd.append('pc', document.getElementById('pc').value);
    fd.append('celular', document.getElementById('celular').value.trim());
    fd.append('nombre', document.getElementById('nombre').value.trim());
    fd.append('nit', document.getElementById('nit').value.trim());
    fetch('activar.php', {method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        if (d.ok) {
            document.getElementById('step-pago').classList.add('hidden');
            document.getElementById('step-password').classList.remove('hidden');
            document.getElementById('password-value').textContent = d.contrasena;
        } else {
            document.getElementById('status-pago').className = 'status error';
            document.getElementById('status-pago').innerHTML = 'Error: ' + (d.error||'Intenta de nuevo');
        }
    }).catch(()=>{
        document.getElementById('status-pago').className = 'status error';
        document.getElementById('status-pago').innerHTML = 'Error de conexion.';
    });
}

function copiarPassword() {
    navigator.clipboard.writeText(document.getElementById('password-value').textContent).then(()=>{
        document.getElementById('copy-msg').classList.remove('hidden');
        setTimeout(()=>document.getElementById('copy-msg').classList.add('hidden'), 3000);
    });
}
</script>
</body>
</html>
