<?php
// templates/landing7.php
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'] ?? 'UTAMU';
$favicon = $site_settings['site_favicon'] ?? 'assets/images/favicon.png';

// Handle rotating hero: Pick a random video if available
if (!empty($videos)) {
    $featured = $videos[array_rand($videos)];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($landing_title) ?>+ | Premium Streaming</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="icon" type="image/png" href="<?= htmlspecialchars($favicon) ?>">
    <style>
        :root {
            --primary: #e50914;
            --primary-hover: #b20710;
            --bg-dark: #0f0f0f;
            --card-bg: #1a1a1a;
            --text-main: #ffffff;
            --text-dim: #b3b3b3;
            --success: #2ecc71;
            --warning: #f39c12;
            --danger: #e74c3c;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-main);
            line-height: 1.6;
            overflow-x: hidden;
        }

        /* --- Navigation --- */
        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 5%;
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.9) 0%, transparent 100%);
        }

        .logo {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--primary);
            letter-spacing: 1px;
        }

        .user-badge {
            background: var(--primary);
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
        }

        /* --- Hero --- */
        .hero {
            height: 80vh;
            width: 100%;
            position: relative;
            display: flex;
            align-items: center;
            padding: 0 5%;
            background-size: cover;
            background-position: center;
        }

        .hero-content {
            max-width: 600px;
            z-index: 10;
        }

        .hero-content h1 {
            font-size: 3.5rem;
            font-weight: 700;
            margin-bottom: 15px;
        }

        /* --- Buttons --- */
        .btn {
            padding: 12px 25px;
            border-radius: 6px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            transition: 0.3s;
            border: none;
            font-family: inherit;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-hover);
            transform: translateY(-2px);
        }

        .btn-success {
            background: var(--success);
            color: white;
        }

        .btn-warning {
            background: var(--warning);
            color: white;
        }

        /* --- Grid --- */
        .container {
            padding: 40px 5%;
        }

        .movie-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .movie-card {
            background: var(--card-bg);
            border-radius: 10px;
            overflow: hidden;
            cursor: pointer;
            transition: 0.3s;
            border: 1px solid #222;
        }

        .movie-card:hover {
            transform: scale(1.02);
            border-color: var(--primary);
        }

        .poster-wrapper {
            position: relative;
            aspect-ratio: 2/3;
        }

        .poster-wrapper img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .price-tag {
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--primary);
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 700;
        }

        .card-details {
            padding: 12px;
        }

        

        /* --- MODERN MODAL --- */
        .modal { display: none; position: fixed; inset: 0; background: rgba(0, 0, 0, 0.9); z-index: 2000; align-items: center; justify-content: center; backdrop-filter: blur(8px); padding: 20px; }
        .modal.active { display: flex; animation: fadeIn 0.3s ease; }
        .modal-box { background: #1c1c1c; width: 100%; max-width: 400px; border-radius: 24px; position: relative; overflow: hidden; box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5); border: 1px solid #333; }
        .modal-header { background: linear-gradient(135deg, var(--primary), #800000); padding: 25px 20px; text-align: center; position: relative; }
        .modal-header h2 { font-size: 1.3rem; font-weight: 700; color: white; margin-bottom: 4px; }
        .modal-body { padding: 25px; text-align: center; }
        .amount-display { background: rgba(255, 215, 0, 0.1); color: gold; display: inline-block; padding: 6px 18px; border-radius: 30px; font-weight: 800; font-size: 1.4rem; margin-bottom: 20px; border: 1px solid rgba(255, 215, 0, 0.3); }
        .input-group { text-align: left; margin-bottom: 15px; }
        .input-group label { display: block; font-size: 0.75rem; color: var(--text-dim); margin-bottom: 6px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
        .input-field { width: 100%; padding: 14px 14px 14px 45px; background: #2a2a2a; border: 2px solid #333; border-radius: 12px; color: white; font-size: 1.1rem; transition: 0.3s; outline: none; }
        .input-field:focus { border-color: var(--primary); background: #333; box-shadow: 0 0 0 4px rgba(229, 9, 20, 0.1); }
        .phone-wrapper { position: relative; }
        .phone-wrapper i { position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--text-dim); font-size: 1.1rem; }
        .close-btn { position: absolute; top: 15px; right: 15px; color: white; font-size: 1.2rem; cursor: pointer; opacity: 0.7; transition: 0.3s; z-index: 10; }
        .close-btn:hover { opacity: 1; }
        
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }

        /* Payment Status Messages */
        .payment-status {
            display: none;
            padding: 15px;
            border-radius: 10px;
            margin: 15px 0;
            text-align: center;
            animation: fadeIn 0.3s ease;
        }
        .status-success { background: rgba(46, 204, 113, 0.1); border: 1px solid var(--success); color: var(--success); }
        .status-warning { background: rgba(243, 156, 18, 0.1); border: 1px solid var(--warning); color: var(--warning); }
        .status-error { background: rgba(231, 76, 60, 0.1); border: 1px solid var(--danger); color: var(--danger); }

        .countdown { font-size: 0.9rem; color: var(--text-dim); margin-top: 10px; }

        .spinner {
            width: 20px; height: 20px; border: 3px solid rgba(255, 255, 255, 0.3); border-top-color: white;
            border-radius: 50%; animation: spin 0.8s linear infinite; display: inline-block;
        }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes spin { to { transform: rotate(360deg); } }

        @media (max-width: 768px) {
            .hero-content h1 { font-size: 2.5rem; }
            .movie-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; }
            .modal-box { max-width: 95%; }
        }

        @media (max-width: 480px) {
            .hero { height: 60vh; }
            .hero-content h1 { font-size: 2rem; }
            .btn { padding: 10px 20px; font-size: 0.9rem; }
            .modal-body { padding: 20px 15px; }
        }
    
        /* --- Payment Modal Styles --- */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.95); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); display: none; justify-content: center; align-items: center; z-index: 2000; padding: max(20px, env(safe-area-inset-top, 0px)) max(16px, env(safe-area-inset-left, 0px)) max(20px, env(safe-area-inset-bottom, 0px)) max(16px, env(safe-area-inset-right, 0px)); }
        .modal-content { background: var(--card-bg, #1e1e1e); width: 100%; max-width: min(450px, 95vw); border-radius: 16px; position: relative; border: 1px solid rgba(255,255,255,0.1); animation: modalSlideUp 0.3s cubic-bezier(0.4,0,0.2,1); max-height: 90vh; overflow-y: auto; -webkit-overflow-scrolling: touch; color: var(--text-main, #fff); }
        @keyframes modalSlideUp { from { transform: translateY(50px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
        .modal-header { padding: clamp(20px, 4vw, 25px); border-bottom: 1px solid rgba(255,255,255,0.1); text-align: center; position: sticky; top: 0; background: var(--card-bg, #1e1e1e); z-index: 1; border-radius: 16px 16px 0 0; }
        .modal-body { padding: clamp(20px, 4vw, 25px); }
        .close-modal { position: absolute; top: 16px; right: 16px; color: var(--text-dim, #aaa); cursor: pointer; font-size: 1.5rem; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: background-color 0.2s; z-index: 2; }
        .close-modal:hover, .close-modal:active { background-color: rgba(255,255,255,0.1); }
        .input-group { margin-top: 20px; text-align: left; }
        .input-group label { display: block; font-size: clamp(0.75rem, 2vw, 0.85rem); color: var(--text-dim, #aaa); margin-bottom: 8px; font-weight: 600; }
        .input-group input { width: 100%; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.2); padding: clamp(12px, 3vw, 16px); color: var(--text-main, #fff); border-radius: 8px; outline: none; font-size: clamp(0.9rem, 2vw, 1rem); transition: border-color 0.2s; -webkit-appearance: none; box-sizing: border-box; }
        .input-group input:focus { border-color: var(--primary); }
        .btn-full { width: 100%; margin-top: 20px; background: var(--primary); color: white; font-size: clamp(0.9rem, 2vw, 1rem); padding: clamp(14px, 3vh, 16px); border-radius: 10px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px; font-weight: 700; transition: all 0.3s ease; min-height: 52px; box-sizing: border-box; }
        .btn-full:hover:not(:disabled) { filter: brightness(1.2); transform: translateY(-2px); }
        .btn-full:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
        .operator-badges { display: flex; gap: 8px; justify-content: center; margin-bottom: 20px; flex-wrap: wrap; }
        .op-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.65rem; font-weight: 700; color: white; opacity: 0.35; transition: all 0.3s; border: 1px solid transparent; }
        .op-badge.active { opacity: 1; transform: scale(1.1); border-color: rgba(255,255,255,0.5); box-shadow: 0 0 10px rgba(0,0,0,0.5); }
        .op-voda { background: #e60000; } .op-tigo { background: #003366; } .op-airtel { background: #ff0000; } .op-halo { background: #ff6600; }
        .payment-steps { margin: 15px 0; padding: 12px; background: rgba(255,255,255,0.05); border-radius: 8px; font-size: 0.75rem; color: var(--text-dim, #aaa); text-align: left; }
        .step { display: flex; gap: 10px; margin-bottom: 8px; align-items: flex-start; }
        .step:last-child { margin-bottom: 0; }
        .step-num { width: 18px; height: 18px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.6rem; font-weight: bold; flex-shrink: 0; margin-top: 2px; }
        .error-box { background: rgba(229,9,20,0.15); border: 1px solid rgba(229,9,20,0.4); border-radius: 8px; padding: 10px 14px; font-size: 0.8rem; color: #ff6b6b; margin-top: 12px; display: none; text-align: left; }
        #paymentStatus { text-align: center; margin-top: 15px; font-size: 0.85rem; font-weight: 600; min-height: 1.2em; }
        .status-pulse { animation: statusPulse 1.5s infinite; color: var(--primary); }
        @keyframes statusPulse { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
        .modal-content::-webkit-scrollbar { width: 4px; }
        .modal-content::-webkit-scrollbar-thumb { background: var(--primary); border-radius: 2px; }

    </style>
</head>

<body>

    <nav class="navbar">
        <div class="logo"><?= htmlspecialchars($landing_title) ?>+</div>
        <div class="nav-right">
            <div class="user-badge">PREMIUM VIP</div>
        </div>
    </nav>

    <?php if ($featured): ?>
    <section class="hero"
        style="background-image: linear-gradient(to right, rgba(0,0,0,0.9) 20%, transparent 100%), url('<?= htmlspecialchars($featured['thumbnail_url'] ?: SITE_URL.'/assets/landing5.jpg') ?>');">
        <div class="hero-content">
            <h1 id="heroTitle"><?= htmlspecialchars($featured['title']) ?></h1>
            <div class="hero-actions">
                <button class="btn btn-primary"
                    onclick="openPaymentModal('<?= htmlspecialchars($featured['id'] ?? '') ?>', '<?= (int)($featured['price'] ?? 0) ?>', '<?= htmlspecialchars(addslashes($featured['title'] ?? '')) ?>'); return false;">
                    <i class="fas fa-play"></i> UNLOCK NOW
                </button>
            </div>
        </div>
    </section>
    <?php else: ?>
    <section class="hero" style="background:#111;">
        <div class="hero-content">
            <h1>Welcome to the Premium Storefront</h1>
        </div>
    </section>
    <?php endif; ?>

    <div class="container">
        <div class="movie-grid">
            <?php if(!empty($videos)): ?>
                <?php foreach($videos as $vid): ?>
                <a href="#"
                    onclick="openPaymentModal('<?= htmlspecialchars($vid['id'] ?? '') ?>', '<?= (int)($vid['price'] ?? 0) ?>', '<?= htmlspecialchars(addslashes($vid['title'] ?? '')) ?>'); return false;"
                    style="text-decoration:none;color:inherit;">
                
                <div class="movie-card">
                    <div class="poster-wrapper">
                        <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'assets/placeholder.jpg') ?>" alt="Thumb">
                        <span class="price-tag">TSH <?= number_format($vid['price']) ?></span>
                    </div>

                    <div class="card-details">
                        <h3 style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-size:0.95rem; margin-bottom:5px;">
                            <?= htmlspecialchars($vid['title']) ?>
                        </h3>
                        <p style="color:var(--text-dim); font-size:0.8rem;">
                            <?= number_format($vid['fake_views'] ?? 0) ?> views • Premium
                        </p>
                    </div>
                </div>
                </a>
                <?php endforeach; ?>
            <?php else: ?>
                <p style="text-align:center;width:100%;color:var(--text-dim);grid-column: 1 / -1;padding:40px;">No trending videos available at the moment.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- ===================== PAYMENT MODAL ===================== -->
<div class="modal-overlay" id="paymentModal" role="dialog" aria-modal="true" aria-labelledby="modalHeading">
    <div class="modal-content">
        <i class="fas fa-times close-modal" onclick="closePaymentModal()" aria-label="Close"></i>

        <div class="modal-header">
            <h2 id="modalHeading" style="color:var(--premium)">
                <i class="fas fa-shield-alt"></i> Malipo Salama
            </h2>
            <p style="font-size:0.8rem;color:var(--text-dim)">Fungua Huduma ya Premium kwa Pesa za Simu</p>
        </div>

        <div class="modal-body">
            <input type="hidden" id="videoID"    value="">
            <input type="hidden" id="videoTitle" value="">

            <div class="operator-badges">
                <span class="op-badge op-voda"   id="badge-voda">M-PESA</span>
                <span class="op-badge op-tigo"   id="badge-tigo">TIGO PESA</span>
                <span class="op-badge op-airtel" id="badge-airtel">AIRTEL</span>
                <span class="op-badge op-halo"   id="badge-halo">HALOPESA</span>
            </div>

            <div style="text-align:center;margin-bottom:15px;">
                <span style="font-size:0.8rem;color:var(--text-dim)">Jumla ya Kulipa:</span>
                <h1 id="modalPrice" style="font-size:2rem;letter-spacing:-1px;">TSH 0</h1>
            </div>

            <div class="input-group">
                <label for="phoneNumber">Nambari ya Simu (Ombi la PIN litatumwa hapa)</label>
                <div style="position:relative;">
                    <i class="fas fa-phone-alt" style="position:absolute;left:15px;top:50%;transform:translateY(-50%);color:var(--text-dim);"></i>
                    <input
                        type="tel"
                        id="phoneNumber"
                        placeholder="07xx xxx xxx"
                        inputmode="tel"
                        maxlength="13"
                        style="padding-left:45px;"
                        oninput="detectOperator(this.value)"
                    >
                </div>
            </div>

            <div class="payment-steps">
                <div class="step"><div class="step-num">1</div><div>Weka nambari yako ya simu inayofanya kazi hapo juu.</div></div>
                <div class="step"><div class="step-num">2</div><div>Bonyeza <strong>Lipa Sasa</strong> — utapata <strong>ombi la PIN</strong> kwenye simu yako.</div></div>
                <div class="step"><div class="step-num">3</div><div>Weka PIN yako ya Pesa za Simu kukamilisha malipo.</div></div>
            </div>

            <div class="error-box" id="errorBox"></div>

            <button class="btn-full" id="mainPayBtn" onclick="processPayment()">
                <i class="fas fa-lock" id="payBtnIcon"></i>
                <span id="payBtnText">LIPA SASA</span>
            </button>

            <div id="paymentStatus"></div>

            <p style="font-size:0.65rem;color:var(--text-dim);text-align:center;margin-top:15px;opacity:0.6;">
                <i class="fas fa-lock"></i> Inalindwa na Kindamba Pay Gateway
            </p>
        </div>
    </div>
</div>
<script>
const SITE = '<?= SITE_URL ?>';
let paymentCheckInterval = null;
let paymentAborted       = false;

function openPaymentModal(videoId, price, title) {
    paymentAborted = false;
    document.getElementById('videoID').value    = videoId;
    document.getElementById('videoTitle').value = title || '';
    document.getElementById('modalPrice').textContent = 'TSH ' + Number(price).toLocaleString();
    document.getElementById('paymentModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
    resetUI();

    // Track the click/view
    fetch(SITE + '/api/track_click.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ domain_id: <?= (int)$domain_id ?>, video_id: videoId })
    }).catch(err => console.error('Tracking failed:', err));
}

function closePaymentModal() {
    paymentAborted = true;
    if (paymentCheckInterval) clearInterval(paymentCheckInterval);
    document.getElementById('paymentModal').style.display = 'none';
    document.body.style.overflow = '';
    document.getElementById('videoID').value    = '';
    document.getElementById('videoTitle').value = '';
    document.getElementById('modalPrice').textContent = 'TSH 0';
    resetUI();
}

document.getElementById('paymentModal').addEventListener('click', function(e) {
    if (e.target === this) closePaymentModal();
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closePaymentModal();
});

function detectOperator(val) {
    const phone = val.replace(/[\s-]/g, '');
    document.querySelectorAll('.op-badge').forEach(b => b.classList.remove('active'));
    const map = {
        'badge-voda':   ['075','076','074'],
        'badge-tigo':   ['071','065','067','077'],
        'badge-airtel': ['078','068','069'],
        'badge-halo':   ['062','061'],
    };
    for (const [id, prefixes] of Object.entries(map)) {
        if (prefixes.some(p => phone.startsWith(p))) {
            document.getElementById(id).classList.add('active');
            break;
        }
    }
}

function showError(msg) {
    const b = document.getElementById('errorBox');
    b.textContent = msg; b.style.display = 'block';
}
function clearError() {
    const b = document.getElementById('errorBox');
    b.style.display = 'none'; b.textContent = '';
}

function setPayBtn(state) {
    const btn  = document.getElementById('mainPayBtn');
    const icon = document.getElementById('payBtnIcon');
    const lbl  = document.getElementById('payBtnText');
    const states = {
        idle:    { icon: 'fa-lock',            text: 'LIPA SASA',                    disabled: false, color: '' },
        loading: { icon: 'fa-spinner fa-spin', text: 'INAANZA\u2026',                disabled: true,  color: '' },
        waiting: { icon: 'fa-mobile-alt',      text: 'ANGALIA SIMU YAKO',            disabled: true,  color: '' },
        success: { icon: 'fa-check-circle',    text: 'IMETHIBITISHWA \u2014 INAFUNGUA\u2026', disabled: true, color: '#28a745' },
    };
    const s = states[state] || states.idle;
    icon.className            = 'fas ' + s.icon;
    lbl.textContent           = s.text;
    btn.disabled              = s.disabled;
    btn.style.backgroundColor = s.color;
}

function resetUI() {
    document.getElementById('phoneNumber').value = '';
    document.querySelectorAll('.op-badge').forEach(b => b.classList.remove('active'));
    document.getElementById('paymentStatus').innerHTML = '';
    clearError();
    setPayBtn('idle');
    if (paymentCheckInterval) { clearInterval(paymentCheckInterval); paymentCheckInterval = null; }
}

async function processPayment() {
    clearError();
    const phone   = document.getElementById('phoneNumber').value.replace(/[\s-]/g, '');
    const videoID = document.getElementById('videoID').value;
    const title   = document.getElementById('videoTitle').value || 'Customer';
    const rawAmt  = document.getElementById('modalPrice').textContent.replace('TSH','').replace(/,/g,'').trim();
    const amount  = parseInt(rawAmt, 10);

    if (!phone || !/^0[0-9]{9}$/.test(phone)) {
        showError('Tafadhali weka nambari sahihi ya simu yenye tarakimu 10 inayoanza na 0.');
        document.getElementById('phoneNumber').focus();
        return;
    }
    if (!videoID)               { showError('Hakuna maudhui yaliyochaguliwa. Tafadhali funga na ujaribu tena.'); return; }
    if (!amount || amount <= 0) { showError('Kiasi cha malipo si sahihi.'); return; }

    setPayBtn('loading');
    document.getElementById('paymentStatus').innerHTML = '';
    paymentAborted = false;

    const apiUrl = SITE + '/api/pay.php';

    let res, data;
    try {
        res = await fetch(apiUrl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body:    JSON.stringify({ 
                phone: phone, amount: parseInt(amount)||1000, videoID: videoID, 
                name: title,
                token: <?= json_encode($store_api_key) ?> || ''
            }),
        });
    } catch (networkErr) {
        console.error('[KindambaPay] fetch failed:', networkErr, 'URL:', apiUrl);
        showError('Imeshindwa kufikia seva ya malipo.');
        setPayBtn('idle');
        return;
    }

    const raw = await res.text();
    try {
        data = JSON.parse(raw);
    } catch (_) {
        showError('Hitilafu ya seva (HTTP ' + res.status + ').');
        setPayBtn('idle');
        return;
    }

    if (!res.ok || !data.success) {
        showError(data.message || 'Kuanzisha malipo kumeshindwa.');
        setPayBtn('idle');
        return;
    }

    setPayBtn('waiting');
    document.getElementById('paymentStatus').innerHTML =
        '<span class="status-pulse"><i class="fas fa-key"></i> Inasubiri Uwekaji wa PIN\u2026</span>';
    pollStatus(data.transaction_id, videoID);
}

function pollStatus(transactionId, videoID) {
    if (paymentCheckInterval) clearInterval(paymentCheckInterval);
    let attempts    = 0;
    const MAX_TRIES = 30;
    const statusDiv = document.getElementById('paymentStatus');

    paymentCheckInterval = setInterval(async () => {
        if (paymentAborted) { clearInterval(paymentCheckInterval); return; }
        attempts++;

        if (attempts > MAX_TRIES) {
            clearInterval(paymentCheckInterval);
            showError('Muda wa malipo umeisha.');
            setPayBtn('idle');
            statusDiv.innerHTML = '';
            return;
        }

        try {
            const cacheBuster = Date.now();
            const res = await fetch(SITE + '/api/check_status.php?tran_id=' + encodeURIComponent(transactionId) + '&token=' + encodeURIComponent(<?= json_encode($store_api_key) ?> || '') + '&_=' + cacheBuster);
            const data = await res.json();
            const s = (data.data?.status || data.status || '').toLowerCase();
            const rs   = (data.raw_status || '').toLowerCase();

            if (s === 'success' || s === 'completed' || s === 'successful' || s === 'paid' || rs === 'success' || rs === 'completed' || rs === 'paid') {
                clearInterval(paymentCheckInterval);
                setPayBtn('success');
                statusDiv.innerHTML = '<span style="color:#28a745"><i class="fas fa-unlock"></i> Malipo Yamethibitishwa!</span>';
                setTimeout(() => { 
                    window.location.href = <?= json_encode($store_redirect_url) ?>; 
                }, 1500);
            } else if (s === 'failed' || s === 'cancelled' || s === 'canceled' || s === 'rejected' || s === 'user_cancelled' || s === 'expired' || s === 'error' || rs === 'failed' || rs === 'cancelled' || rs === 'rejected' || rs === 'user_cancelled') {
                clearInterval(paymentCheckInterval);
                showError(data.message || 'Malipo yameshindwa');
                setPayBtn('idle'); statusDiv.innerHTML = '';
            }
        } catch (e) {}
    }, 5000);
}

// Prevent double-tap zoom on iOS
let lastTouchEnd = 0;
document.addEventListener('touchend', function(e) {
    const now = Date.now();
    if (now - lastTouchEnd <= 300) e.preventDefault();
    lastTouchEnd = now;
}, false);
</script>
</body>
</html>

