<?php
// templates/landing15.php
// Premium Bongo Feed Template (3-Second Preview)

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$site_settings = get_site_settings($pdo);
$landing_title = $site_settings['landing_title'] ?? 'BONGO · PREMIUM';
$favicon = $site_settings['site_favicon'] ?? 'assets/images/favicon.png';

// Defaults
if (!isset($domain_id)) $domain_id = 0;
if (!isset($store_api_key)) $store_api_key = '';
if (!isset($store_redirect_url)) $store_redirect_url = 'https://thathendwa.us/';

// Fetch ONLY videos uploaded in the system (Global fetch)
// This overrides any store-specific videos passed to the template
try {
    $stmt = $pdo->query("SELECT * FROM videos WHERE status = 'active' ORDER BY created_at DESC LIMIT 50");
    $videos = $stmt->fetchAll();
} catch (PDOException $e) {
    $videos = $videos ?? []; // fallback to passed videos if query fails
}

// Prepare a JSON array of videos for the player JS
$js_videos = [];
if (!empty($videos)) {
    foreach ($videos as $idx => $v) {
        // Handle fake views consistently
        if (empty($v['fake_views']) || $v['fake_views'] == 0) {
            $seed = crc32($v['id']);
            mt_srand($seed);
            $v['fake_views'] = mt_rand(12000, 65000);
            mt_srand(); 
        }

        $js_videos[] = [
            'id' => $v['id'],
            'title' => $v['title'],
            'videoUrl' => !empty($v['preview_url']) ? $v['preview_url'] : ($v['video_url'] ?? ''), // fallback to video_url
            'price' => $v['price'] ?? 1000
        ];
        
        // Update the video object in the array for the PHP loop below
        $videos[$idx] = $v;
    }
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title><?= htmlspecialchars($landing_title) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800;900&family=Crimson+Text:wght@400;600&display=swap" rel="stylesheet">
    <link rel="icon" type="image/png" href="<?= htmlspecialchars(SITE_URL . '/' . $favicon) ?>">
    <style>
        :root {
            --primary: #ffffff;
            --secondary: #0a0a0a;
            --accent: #ff6b35;
            --accent-light: #ffa366;
            --accent-dark: #cc4d28;
            --text: #1a1a1a;
            --text-light: #666666;
            --border: #e8e8e8;
            --surface: #f8f8f8;
            --premium-gold: #d4af37;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body {
            background: linear-gradient(135deg, #fafafa 0%, #f0f0f0 100%);
            font-family: 'Outfit', -apple-system, BlinkMacSystemFont, sans-serif;
            color: var(--text);
            line-height: 1.6;
            overflow-x: hidden;
            min-height: 100vh;
        }
        .nav-bar {
            position: sticky; top: 0; z-index: 1000;
            background: rgba(255,255,255,0.95); backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border);
            padding: 20px 28px;
            display: flex; justify-content: space-between; align-items: center;
            box-shadow: 0 2px 20px rgba(0,0,0,0.03);
        }
        .logo-section { display: flex; align-items: center; gap: 12px; }
        .logo-icon {
            width: 40px; height: 40px;
            background: linear-gradient(135deg, var(--accent) 0%, var(--accent-light) 100%);
            border-radius: 12px; display: flex; align-items: center; justify-content: center;
            color: white; font-size: 20px; font-weight: 700;
            box-shadow: 0 8px 24px rgba(255,107,53,0.25);
        }
        .logo-text {
            font-family: 'Crimson Text', serif; font-size: 18px; font-weight: 600;
            letter-spacing: 2px; color: var(--secondary);
        }
        .premium-badge {
            background: linear-gradient(135deg, var(--premium-gold) 0%, #e8c547 100%);
            color: var(--secondary); padding: 8px 16px; border-radius: 50px;
            font-size: 12px; font-weight: 700; letter-spacing: 1px;
            display: flex; align-items: center; gap: 6px;
            box-shadow: 0 8px 24px rgba(212,175,55,0.2); text-transform: uppercase;
        }
        .feed-container { max-width: 1400px; margin: 0 auto; padding: 40px 28px; }
        .feed-header { margin-bottom: 48px; animation: fadeInDown 0.8s ease-out; }
        .feed-title { font-family: 'Crimson Text', serif; font-size: 42px; font-weight: 600; color: var(--secondary); margin-bottom: 12px; letter-spacing: -1px; }
        .feed-subtitle { color: var(--text-light); font-size: 15px; font-weight: 400; }
        .feed-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 24px; }
        .pro-card {
            background: white; border-radius: 20px; overflow: hidden; position: relative;
            border: 1px solid var(--border); cursor: pointer;
            transition: all 0.3s cubic-bezier(0.34,1.56,0.64,1);
            box-shadow: 0 4px 16px rgba(0,0,0,0.04);
            animation: fadeInUp 0.6s ease-out backwards;
        }
        .pro-card:nth-child(1){animation-delay:.1s}.pro-card:nth-child(2){animation-delay:.2s}
        .pro-card:nth-child(3){animation-delay:.3s}.pro-card:nth-child(n+4){animation-delay:.4s}
        .pro-card:hover { transform: translateY(-12px) scale(1.02); box-shadow: 0 20px 48px rgba(0,0,0,0.12); border-color: var(--accent); }
        .media-container { position: relative; aspect-ratio: 9/14; background: linear-gradient(135deg,#f0f0f0,#e8e8e8); overflow: hidden; }
        .thumb-img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.4s ease-out; }
        .pro-card:hover .thumb-img { transform: scale(1.08); }
        .card-overlay {
            position: absolute; inset: 0;
            background: linear-gradient(180deg, transparent 0%, rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.85) 100%);
            padding: 16px; display: flex; flex-direction: column; justify-content: flex-end;
        }
        .overlay-badge {
            position: absolute; top: 12px; right: 12px;
            background: rgba(255,107,53,0.9); backdrop-filter: blur(10px);
            color: white; padding: 6px 10px; border-radius: 8px;
            font-size: 11px; font-weight: 700; letter-spacing: .5px; text-transform: uppercase;
        }
        .card-title { font-size: 13px; font-weight: 600; color: rgba(255,255,255,0.95); margin-bottom: 8px; }
        .card-stats { display: flex; gap: 14px; font-size: 11px; color: rgba(255,255,255,0.7); font-weight: 500; }
        .card-stats span { display: flex; align-items: center; gap: 5px; }
        .empty-state { text-align: center; padding: 80px 24px; color: var(--text-light); grid-column: 1 / -1; }
        .empty-state i { font-size: 64px; margin-bottom: 20px; display: block; opacity: .3; }

        /* PLAYER */
        #player-ui {
            position: fixed; inset: 0; background: var(--secondary); z-index: 2000;
            display: none; animation: fadeIn 0.3s ease-out;
        }
        #fs-video { width: 100%; height: 100%; object-fit: contain; }
        .video-ui-top {
            position: absolute; top: 0; left: 0; right: 0;
            padding: 20px 24px;
            background: linear-gradient(to bottom,rgba(0,0,0,0.6),transparent);
            display: flex; justify-content: space-between; align-items: center; z-index: 2001;
        }
        .close-btn {
            width: 44px; height: 44px; background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.2);
            border-radius: 12px; color: white; font-size: 18px; cursor: pointer;
            display: flex; align-items: center; justify-content: center; transition: all .3s;
        }
        .close-btn:hover { background: rgba(255,255,255,0.2); }
        .status-tag { font-size: 12px; font-weight: 700; color: rgba(255,255,255,0.8); letter-spacing: 1px; text-transform: uppercase; }
        .preview-bar { height: 3px; background: rgba(255,255,255,0.15); position: absolute; bottom: 0; left: 0; right: 0; }
        .preview-progress { height: 100%; background: linear-gradient(90deg,var(--accent),var(--accent-light)); width: 0%; transition: width linear; box-shadow: 0 0 10px rgba(255,107,53,.5); }

        /* MODAL */
        .modal-blur {
            position: fixed; inset: 0; background: rgba(10,10,10,0.85);
            backdrop-filter: blur(8px); z-index: 3000; display: none;
            align-items: center; justify-content: center; padding: 24px;
            animation: fadeIn 0.4s ease-out;
        }
        .modal-content {
            width: 100%; max-width: 420px; background: white; border-radius: 24px;
            padding: 48px 36px; text-align: center;
            box-shadow: 0 25px 60px rgba(0,0,0,0.25);
            animation: slideUp 0.5s cubic-bezier(0.34,1.56,0.64,1);
        }
        .icon-box {
            width: 88px; height: 88px;
            background: linear-gradient(135deg,var(--accent),var(--accent-light));
            border-radius: 20px; display: flex; align-items: center; justify-content: center;
            margin: 0 auto 28px; font-size: 40px; color: white;
            box-shadow: 0 12px 32px rgba(255,107,53,0.3);
        }
        .modal-title { font-family: 'Crimson Text', serif; font-size: 28px; font-weight: 600; color: var(--secondary); margin-bottom: 12px; }
        .modal-subtitle { color: var(--text-light); font-size: 14px; margin-bottom: 28px; line-height: 1.6; }
        .price-section { margin: 32px 0; }
        .price-tag { font-size: 48px; font-weight: 900; color: var(--secondary); margin-bottom: 4px; }
        .price-subtitle { font-size: 12px; color: var(--text-light); text-transform: uppercase; letter-spacing: 1px; font-weight: 600; }
        .phone-input {
            width: 100%; background: var(--surface); border: 2px solid var(--border);
            padding: 16px 18px; border-radius: 14px; color: var(--text); font-size: 16px;
            text-align: center; margin: 24px 0; outline: none; font-weight: 500;
            transition: all .3s; font-family: 'Outfit', sans-serif;
        }
        .phone-input:focus { border-color: var(--accent); background: white; box-shadow: 0 0 0 4px rgba(255,107,53,0.1); }
        .phone-input::placeholder { color: #999; }
        .btn-primary {
            width: 100%; background: linear-gradient(135deg,var(--accent),var(--accent-dark));
            color: white; padding: 16px 24px; border-radius: 14px; font-weight: 700;
            font-size: 15px; border: none; cursor: pointer; letter-spacing: .5px;
            text-transform: uppercase; transition: all .3s;
            box-shadow: 0 8px 24px rgba(255,107,53,0.3); font-family: 'Outfit', sans-serif;
        }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 12px 32px rgba(255,107,53,0.4); }
        .btn-secondary {
            background: transparent; color: var(--text-light); border: none;
            margin-top: 16px; font-size: 13px; font-weight: 600; cursor: pointer;
            transition: color .3s; text-transform: uppercase; letter-spacing: .5px;
            font-family: 'Outfit', sans-serif;
        }
        .btn-secondary:hover { color: var(--accent); }
        .pay-spinner { width: 72px; height: 72px; border: 3px solid #f0f0f0; border-top: 3px solid var(--accent); border-radius: 50%; animation: spin .9s linear infinite; margin: 0 auto 28px; }
        .waiting-steps { display: flex; flex-direction: column; gap: 10px; margin-bottom: 28px; text-align: left; }
        .w-step { display: flex; align-items: center; gap: 14px; background: var(--surface); padding: 14px 16px; border-radius: 12px; font-size: 13px; font-weight: 500; color: var(--text); border-left: 3px solid var(--accent); }
        .state-icon-circle { width: 88px; height: 88px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px; font-size: 36px; }
        .state-icon-circle.success { background: linear-gradient(135deg,#43e97b,#38f9d7); box-shadow: 0 12px 32px rgba(67,233,123,.3); }
        .state-icon-circle.failed  { background: linear-gradient(135deg,#f857a6,#ff5858); box-shadow: 0 12px 32px rgba(248,87,166,.3); }
        .state-icon-circle.timeout { background: linear-gradient(135deg,#f7971e,#ffd200); box-shadow: 0 12px 32px rgba(247,151,30,.3); }
        .btn-row { display: flex; gap: 10px; }
        .btn-row .btn-primary { flex: 1; }
        .btn-row .btn-ghost { flex: 1; background: var(--surface); color: var(--text-light); border: 1px solid var(--border); padding: 16px 24px; border-radius: 14px; font-weight: 600; font-size: 14px; cursor: pointer; text-transform: uppercase; letter-spacing: .5px; font-family: 'Outfit', sans-serif; transition: all .3s; }
        .btn-ghost:hover { background: #ececec; }

        #message-container { position: fixed; top: 80px; right: 20px; z-index: 4000; display: flex; flex-direction: column; gap: 10px; pointer-events: none; }
        .message { padding: 14px 20px; border-radius: 14px; font-size: 13px; font-weight: 600; max-width: 320px; pointer-events: all; animation: slideInRight .4s cubic-bezier(.34,1.56,.64,1); box-shadow: 0 8px 24px rgba(0,0,0,.08); }
        .message.success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
        .message.error   { background: #fff1f2; color: #881337; border: 1px solid #fecdd3; }
        .message.info    { background: #eff6ff; color: #1e3a8a; border: 1px solid #bfdbfe; }

        @keyframes fadeInDown { from{opacity:0;transform:translateY(-20px)} to{opacity:1;transform:translateY(0)} }
        @keyframes fadeInUp   { from{opacity:0;transform:translateY(20px)}  to{opacity:1;transform:translateY(0)} }
        @keyframes fadeIn     { from{opacity:0} to{opacity:1} }
        @keyframes slideUp    { from{opacity:0;transform:translateY(30px)} to{opacity:1;transform:translateY(0)} }
        @keyframes slideInRight { from{opacity:0;transform:translateX(20px)} to{opacity:1;transform:translateX(0)} }
        @keyframes spin { to{transform:rotate(360deg)} }
        @keyframes slideOutRight { from{opacity:1;transform:translateX(0)} to{opacity:0;transform:translateX(20px)} }

        @media(max-width:768px){.feed-grid{grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:16px}.feed-title{font-size:28px}.modal-content{padding:36px 24px}.nav-bar{padding:16px 20px}}
        @media(max-width:480px){.feed-grid{grid-template-columns:repeat(2,1fr);gap:12px}.feed-container{padding:24px 16px}.feed-title{font-size:24px}.price-tag{font-size:36px}}
    </style>
</head>
<body>

<div id="message-container"></div>

<nav class="nav-bar">
    <div class="logo-section">
        <div class="logo-icon"><i class="fas fa-play"></i></div>
        <div class="logo-text"><?= htmlspecialchars($landing_title) ?></div>
    </div>
    <div class="premium-badge">
        <i class="fas fa-crown"></i> Premium
    </div>
</nav>

<div class="feed-container">
    <div class="feed-header">
        <h1 class="feed-title">Connection Mpya</h1>
        <p class="feed-subtitle">Tazama preview bure, lipia kuendelea</p>
    </div>

    <div class="feed-grid" id="feed">
        <?php if (!empty($videos)): ?>
            <?php foreach ($videos as $idx => $v): ?>
                <div class="pro-card" onclick="openPlayer(<?= $idx ?>, '<?= htmlspecialchars($v['id']) ?>', <?= (int)($v['price'] ?? 1000) ?>)">
                    <div class="media-container">
                        <img src="<?= htmlspecialchars($v['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" class="thumb-img" loading="lazy" alt="<?= htmlspecialchars($v['title']) ?>">
                        <div class="overlay-badge"><i class="fas fa-lock-open"></i> Preview</div>
                        <div class="card-overlay">
                            <div class="card-title"><?= htmlspecialchars($v['title']) ?></div>
                            <div class="card-stats">
                                <span><i class="fas fa-eye"></i> <?= number_format($v['fake_views']) ?></span>
                                <span><i class="fas fa-heart"></i> <?= number_format($v['fake_views'] * 0.2) ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-video-slash"></i>
                <p>Hakuna video zilizopo kwa sasa.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<div id="player-ui">
    <div class="video-ui-top">
        <button class="close-btn" onclick="closeVideo()"><i class="fas fa-arrow-left"></i></button>
        <div class="status-tag">Preview Mode</div>
    </div>
    <video id="fs-video" playsinline muted></video>
    <div class="preview-bar"><div class="preview-progress" id="p-bar"></div></div>
</div>

<div class="modal-blur" id="pay-modal">
    <div class="modal-content" id="modal-inner">
        <div id="pay-form-state">
            <div class="icon-box"><i class="fas fa-lock"></i></div>
            <h2 class="modal-title">Lipia Sasa</h2>
            <p class="modal-subtitle">Lipia uendelee kuangalia video zote bila kikwazo</p>
            <div class="price-section">
                <div class="price-tag" id="display-price">TSh 1,000</div>
                <div class="price-subtitle">One-time payment · Instant access</div>
            </div>
            <input type="tel" class="phone-input" id="phone" placeholder="06xxxxxxxx / 07xxxxxxxx" maxlength="10">
            <button class="btn-primary" id="pay-btn" onclick="handlePayment()">
                <span class="btn-text">Lipia</span>
                <span class="loading-spinner" style="display:none"><i class="fas fa-circle-notch fa-spin"></i> Processing...</span>
            </button>
            <button class="btn-secondary" onclick="togglePay(false)">Maybe later</button>
        </div>
    </div>
</div>

<script>
const SITE = '<?= SITE_URL ?>';
const DOMAIN_ID = <?= (int)$domain_id ?>;
const API_TOKEN = '<?= addslashes($store_api_key) ?>';
const REDIRECT_URL = '<?= addslashes($store_redirect_url) ?>';

const videos = <?= json_encode($js_videos) ?>;
let currentVideoId = null;
let currentPrice = 1000;
let activeTimer;
let pollInterval = null;

function openPlayer(idx, videoId, price) {
    currentVideoId = videoId;
    currentPrice = price || 1000;
    document.getElementById('display-price').textContent = 'TSh ' + currentPrice.toLocaleString();
    
    // Track click
    if (DOMAIN_ID > 0) {
        fetch(SITE + '/api/track_click.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ domain_id: DOMAIN_ID, video_id: videoId })
        }).catch(err => console.error('Tracking failed:', err));
    }

    const v = videos[idx];
    if (!v) return;
    
    // If preview url exists, show it, otherwise just show pay modal immediately
    if (v.videoUrl) {
        const ui    = document.getElementById('player-ui');
        const video = document.getElementById('fs-video');
        const bar   = document.getElementById('p-bar');
        ui.style.display = 'flex';
        video.src = v.videoUrl;
        
        let playPromise = video.play();
        if (playPromise !== undefined) {
            playPromise.then(_ => {
                // Autoplay started
                bar.style.width = '0%';
                bar.style.transitionDuration = '3s';
                setTimeout(() => bar.style.width = '100%', 100);
                activeTimer = setTimeout(() => { closeVideo(); togglePay(true); }, 3000);
            }).catch(error => {
                // Auto-play was prevented
                console.log("Autoplay blocked, showing pay modal directly");
                closeVideo();
                togglePay(true);
            });
        }
    } else {
        togglePay(true);
    }
}

function closeVideo() {
    clearTimeout(activeTimer);
    const video = document.getElementById('fs-video');
    video.pause(); 
    video.src = '';
    document.getElementById('player-ui').style.display = 'none';
    document.getElementById('p-bar').style.width = '0%';
}

function togglePay(show) {
    document.getElementById('pay-modal').style.display = show ? 'flex' : 'none';
    if(show) {
        const modalInner = document.getElementById('modal-inner');
        if(!modalInner.querySelector('#pay-form-state')) {
            location.reload(); 
        }
    }
}

const msgBox = document.getElementById('message-container');
const payBtn = document.getElementById('pay-btn');

function validatePhone(p) { return /^0[67][0-9]{8}$/.test(p); }

function setLoading(on) {
    if(!payBtn) return;
    payBtn.disabled = on;
    payBtn.querySelector('.btn-text').style.display = on ? 'none' : 'inline';
    payBtn.querySelector('.loading-spinner').style.display = on ? 'inline' : 'none';
}

function showMsg(text, type = 'info') {
    const el = document.createElement('div');
    el.className = 'message ' + type;
    el.textContent = text;
    msgBox.appendChild(el);
    setTimeout(() => {
        el.style.animation = 'slideOutRight .3s ease forwards';
        setTimeout(() => el.remove(), 300);
    }, 5000);
}

async function handlePayment() {
    const phone = document.getElementById('phone').value.trim();
    if (!validatePhone(phone)) { showMsg('Nambari ya simu si sahihi (06XXXXXXXX au 07XXXXXXXX)', 'error'); return; }
    if (!currentVideoId) { showMsg('Tafadhali chagua video kwanza.', 'error'); return; }
    
    setLoading(true);
    msgBox.innerHTML = '';
    
    try {
        const res = await fetch(SITE + '/api/pay.php', {
            method: 'POST',
            headers: {'Content-Type':'application/json', 'Accept': 'application/json'},
            body: JSON.stringify({
                phone: phone, 
                amount: currentPrice,
                videoID: currentVideoId,
                token: API_TOKEN
            })
        });
        const data = await res.json();
        
        if (data.success) {
            showMsg(data.message, 'success');
            showWaiting(data.transaction_id || data.order_id);
            startPolling(data.transaction_id || data.order_id);
        } else {
            showMsg(data.message || 'Malipo yameshindwa.', 'error');
            setLoading(false);
        }
    } catch(e) {
        showMsg('Hitilafu ya mtandao. Jaribu tena.', 'error');
        setLoading(false);
    }
}

function showWaiting(id) {
    document.getElementById('modal-inner').innerHTML = `
    <div style="text-align:center">
        <div class="pay-spinner"></div>
        <h2 class="modal-title">Kamilisha Malipo</h2>
        <p class="modal-subtitle">Tafadhali thibitisha malipo kwa simu yako</p>
        <div class="waiting-steps">
            <div class="w-step"><span style="font-size:20px">📱</span> Angalia simu yako kwa USSD prompt</div>
            <div class="w-step"><span style="font-size:20px">🔐</span> Ingiza PIN yako kukamilisha</div>
            <div class="w-step"><span style="font-size:20px">⏳</span> Tunasubiri uthibitisho...</div>
        </div>
        <button class="btn-secondary" onclick="cancelPayment()">Ghairi</button>
    </div>`;
}

function showSuccess(id) {
    document.getElementById('modal-inner').innerHTML = `
    <div style="text-align:center">
        <div class="state-icon-circle success">✓</div>
        <h2 class="modal-title" style="color:#166534">Malipo Yamefanikiwa!</h2>
        <p class="modal-subtitle">Unakwenda kwenye ukurasa wa video...</p>
        <p style="font-size:12px;color:#aaa;font-weight:600">Order: ${id}</p>
    </div>`;
}

function showFailed() {
    document.getElementById('modal-inner').innerHTML = `
    <div style="text-align:center">
        <div class="state-icon-circle failed">✗</div>
        <h2 class="modal-title" style="color:#881337">Malipo Yameshindwa</h2>
        <p class="modal-subtitle">Malipo yako hayakukamilika. Jaribu tena.</p>
        <button class="btn-primary" onclick="location.reload()">Jaribu Tena</button>
    </div>`;
}

function showTimeout(id) {
    document.getElementById('modal-inner').innerHTML = `
    <div style="text-align:center">
        <div class="state-icon-circle timeout">⏰</div>
        <h2 class="modal-title" style="color:#92400e">Muda Umekwisha</h2>
        <p class="modal-subtitle">Bado tunasubiri uthibitisho.</p>
        <p style="font-size:12px;color:#aaa;font-weight:600;margin-bottom:24px">Order: ${id}</p>
        <div class="btn-row">
            <button class="btn-primary" onclick="continuePolling('${id}')">Endelea Kusubiri</button>
            <button class="btn-ghost" onclick="location.reload()">Anza Upya</button>
        </div>
    </div>`;
}

function startPolling(id) {
    let n = 0;
    pollInterval = setInterval(async () => {
        n++;
        try {
            const query = new URLSearchParams({ tran_id: id, token: API_TOKEN }).toString();
            const r = await fetch(SITE + '/api/check_status.php?' + query);
            const d = await r.json();
            
            const s = (d.status || '').toLowerCase();
            const rs = (d.raw_status || '').toLowerCase();
            
            if (s === 'success' || s === 'completed' || rs === 'success' || rs === 'completed') {
                clearInterval(pollInterval);
                showSuccess(id);
                setTimeout(() => window.location.href = REDIRECT_URL, 2000);
            } else if (s === 'failed' || s === 'cancelled' || s === 'error') {
                clearInterval(pollInterval); 
                showFailed();
            } else if (n >= 60) {
                clearInterval(pollInterval); 
                showTimeout(id);
            }
        } catch(e) {
            if (n >= 60) { clearInterval(pollInterval); showTimeout(id); }
        }
    }, 5000);
}

function continuePolling(id) { showWaiting(id); startPolling(id); }
function cancelPayment() { clearInterval(pollInterval); location.reload(); }

document.addEventListener('keydown', e => {
    if (e.key === 'Escape') togglePay(false);
});
</script>
</body>
</html>
