<?php
// templates/landing1.php
// Storefront 1 Template (Netflix-Style Premium Streaming)
// Payment powered by SONICPESA Gateway
$site_settings = get_site_settings($pdo);
$landing_title = $site_settings['landing_title'] ?? 'UTAMU';
$favicon = $site_settings['site_favicon'] ?? 'assets/images/favicon.png';

if (!$featured && !empty($videos)) {
    $featured = $videos[0];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= htmlspecialchars($landing_title) ?>+ | Premium Streaming</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&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="<?= SITE_URL ?>/<?= htmlspecialchars($favicon) ?>">
    <style>
        :root {
            --primary: #e50914;
            --primary-hover: #f40612;
            --bg: #0f0f0f;
            --card-bg: #181818;
            --text-main: #ffffff;
            --text-dim: #b3b3b3;
            --premium: #ffd700;
            --safe-top: env(safe-area-inset-top, 0px);
            --safe-bottom: env(safe-area-inset-bottom, 0px);
            --safe-left: env(safe-area-inset-left, 0px);
            --safe-right: env(safe-area-inset-right, 0px);
        }
        *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
        html { font-size: 16px; scroll-behavior: smooth; -webkit-text-size-adjust: 100%; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text-main); line-height: 1.5; -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent; overflow-x: hidden; padding-top: var(--safe-top); padding-bottom: var(--safe-bottom); }
        @media (max-width: 768px) { html { font-size: 14px; } }
        @media (max-width: 480px) { html { font-size: 13px; } }

        /* Navbar */
        .navbar { position: fixed; top: 0; left: 0; width: 100%; z-index: 1000; padding: 12px max(5%, 16px); display: flex; align-items: center; justify-content: space-between; background: linear-gradient(to bottom, rgba(15,15,15,0.95) 0%, rgba(15,15,15,0.8) 100%); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid rgba(255,255,255,0.1); padding-top: calc(12px + var(--safe-top)); }
        .logo { font-size: clamp(1.25rem, 4vw, 1.5rem); font-weight: 800; color: var(--primary); text-decoration: none; letter-spacing: -0.5px; }
        .nav-right { display: flex; align-items: center; gap: clamp(12px, 3vw, 20px); }
        .nav-right i { font-size: clamp(1rem, 3vw, 1.2rem); cursor: pointer; padding: 8px; border-radius: 50%; color: var(--text-main); }
        .avatar { width: clamp(32px, 8vw, 40px); height: clamp(32px, 8vw, 40px); background: var(--primary); border-radius: 4px; display: grid; place-items: center; font-weight: bold; font-size: clamp(0.7rem, 2vw, 0.8rem); cursor: pointer; }

        /* Hero */
        .hero { min-height: 80vh; max-height: 90vh; position: relative; display: flex; align-items: flex-end; padding: 80px max(5%, 16px) clamp(40px, 8vh, 60px); margin-top: calc(60px + var(--safe-top)); background: linear-gradient(to top, var(--bg) 0%, transparent 30%), linear-gradient(to right, rgba(0,0,0,0.9) 0%, transparent 50%), linear-gradient(to left, rgba(0,0,0,0.4) 0%, transparent 30%), url('<?= SITE_URL ?>/assets/landing2.jpg') center/cover no-repeat; }
        @media (max-width: 768px) { .hero { min-height: 70vh; padding: 60px max(4%, 12px) 30px; background: linear-gradient(to top, var(--bg) 0%, transparent 20%), linear-gradient(to right, rgba(0,0,0,0.8) 0%, transparent 40%), url('<?= SITE_URL ?>/assets/landing2.jpg') center/cover no-repeat; } }
        @media (max-width: 480px) { .hero { min-height: 60vh; padding: 50px max(3%, 8px) 20px; } }
        .hero-content { width: 100%; max-width: min(800px, 90vw); z-index: 2; }
        .hero-tag { background: var(--primary); padding: 6px 14px; border-radius: 4px; font-size: clamp(0.65rem, 1.5vw, 0.75rem); font-weight: 700; display: inline-flex; align-items: center; gap: 6px; margin-bottom: clamp(12px, 3vh, 20px); }
        .hero-title { font-size: clamp(2rem, 7vw, 3.5rem); font-weight: 800; margin-bottom: clamp(10px, 2vh, 15px); line-height: 1.1; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
        .hero-meta { color: var(--text-dim); font-size: clamp(0.8rem, 2vw, 0.95rem); margin-bottom: clamp(15px, 4vh, 25px); display: flex; flex-wrap: wrap; gap: clamp(10px, 2vw, 15px); align-items: center; }
        .hero-meta span { display: inline-flex; align-items: center; gap: 4px; }
        .hero-desc { color: var(--text-dim); font-size: clamp(0.85rem, 2vw, 1rem); margin-bottom: clamp(20px, 4vh, 30px); max-width: 600px; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
        .hero-btns { display: flex; gap: 12px; flex-wrap: wrap; }

        /* Buttons */
        .btn { padding: clamp(12px, 2.5vh, 16px) clamp(20px, 4vw, 30px); border-radius: 8px; font-weight: 700; border: none; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 10px; transition: all 0.3s ease; text-decoration: none; font-size: clamp(0.9rem, 2vw, 1rem); min-height: 44px; min-width: 44px; }
        .btn-play { background: #fff; color: #000; }
        .btn-play:hover { background: rgba(255,255,255,0.9); transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .btn-more { background: rgba(109,109,110,0.7); color: #fff; }
        .btn-more:hover { background: rgba(109,109,110,0.5); }
        @media (max-width: 480px) { .btn-play, .btn-more { flex: 1; } }

        /* Grid */
        .section-container { padding: clamp(30px, 5vw, 50px) max(5%, 16px); }
        .row-header { margin-bottom: clamp(15px, 3vw, 25px); display: flex; align-items: center; gap: 10px; }
        .row-title { font-size: clamp(1.1rem, 4vw, 1.5rem); font-weight: 700; }
        .row-title i { color: var(--primary); }
        .movie-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(180px, 45vw), 1fr)); gap: clamp(12px, 3vw, 20px); }
        @media (max-width: 1024px) { .movie-grid { grid-template-columns: repeat(auto-fill, minmax(min(150px, 40vw), 1fr)); } }
        @media (max-width: 768px)  { .movie-grid { grid-template-columns: repeat(auto-fill, minmax(min(140px, 45vw), 1fr)); gap: 12px; } }
        @media (max-width: 480px)  { .movie-grid { grid-template-columns: repeat(2, 1fr); gap: 10px; } }
        @media (max-width: 360px)  { .movie-grid { grid-template-columns: 1fr; max-width: 300px; margin: 0 auto; } }

        /* Movie Card */
        .movie-card { background: var(--card-bg); border-radius: 12px; overflow: hidden; transition: all 0.3s cubic-bezier(0.4,0,0.2,1); position: relative; aspect-ratio: 2/3; display: flex; flex-direction: column; cursor: pointer; }
        .movie-card:hover { transform: translateY(-8px) scale(1.02); box-shadow: 0 10px 25px rgba(0,0,0,0.5); }
        @media (hover: none) { .movie-card:hover { transform: none; box-shadow: none; } .movie-card:active { transform: scale(0.98); opacity: 0.9; } }
        .card-thumb { flex: 1; min-height: 0; background: #222; position: relative; overflow: hidden; }
        .card-thumb img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s ease; }
        .movie-card:hover .card-thumb img { transform: scale(1.05); }
        .badge { position: absolute; top: 10px; left: 10px; background: var(--primary); padding: 4px 10px; font-size: clamp(0.55rem, 1.5vw, 0.65rem); font-weight: 800; border-radius: 4px; z-index: 2; }
        .price-tag { position: absolute; bottom: 10px; right: 10px; background: rgba(0,0,0,0.85); color: var(--premium); padding: 4px 10px; border-radius: 6px; font-size: clamp(0.65rem, 1.5vw, 0.75rem); font-weight: 700; border: 1px solid var(--premium); z-index: 2; }
        .card-info { padding: clamp(10px, 2vw, 15px); background: var(--card-bg); flex-shrink: 0; }
        .card-info h3 { font-size: clamp(0.85rem, 2vw, 0.95rem); margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; line-height: 1.3; min-height: 2.4em; }
        .card-info p { font-size: clamp(0.7rem, 1.5vw, 0.8rem); color: var(--text-dim); display: flex; align-items: center; gap: 4px; }

        /* Modal */
        .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, var(--safe-top)) max(16px, var(--safe-left)) max(20px, var(--safe-bottom)) max(16px, var(--safe-right)); }
        .modal-content { background: var(--card-bg); 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; }
        @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); 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); 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); }

        /* Payment form */
        .input-group { margin-top: 20px; }
        .input-group label { display: block; font-size: clamp(0.75rem, 2vw, 0.85rem); color: var(--text-dim); margin-bottom: 8px; font-weight: 600; }
        .input-group input { width: 100%; background: #222; border: 1px solid #444; padding: clamp(12px, 3vw, 16px); color: #fff; border-radius: 8px; outline: none; font-size: clamp(0.9rem, 2vw, 1rem); transition: border-color 0.2s; -webkit-appearance: none; }
        .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; }
        .btn-full:hover:not(:disabled) { background: var(--primary-hover); transform: translateY(-2px); }
        .btn-full:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }

        /* Operator badges */
        .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; }

        /* Steps */
        .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); }
        .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 */
        .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; }

        /* Status */
        #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(--premium); }
        @keyframes statusPulse { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }

        /* Misc */
        .btn, .btn-full, .close-modal { -webkit-user-select: none; user-select: none; }
        .modal-content::-webkit-scrollbar { width: 4px; }
        .modal-content::-webkit-scrollbar-thumb { background: var(--primary); border-radius: 2px; }
        @media (min-width: 1600px) { .section-container { max-width: 1600px; margin: 0 auto; } .movie-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); } }
    </style>
</head>
<body>

<!-- ===================== NAVBAR ===================== -->
<nav class="navbar">
    <a href="<?= SITE_URL ?>" class="logo"><?= htmlspecialchars($landing_title) ?>+</a>
    <div class="nav-right">
        <i class="fas fa-search" title="Search"></i>
        <div class="avatar"><?= strtoupper(substr($landing_title, 0, 2)) ?></div>
    </div>
</nav>

<!-- ===================== HERO ===================== -->
<section class="hero">
    <div class="hero-content">
        <div class="hero-tag"><i class="fas fa-fire"></i> FEATURED</div>
        <h1 class="hero-title">
            <?= $featured ? htmlspecialchars($featured['title']) : htmlspecialchars($landing_title) ?>
        </h1>
        <div class="hero-meta">
            <?php if ($featured): ?>
                <?php if (!empty($featured['release_year'])): ?>
                    <span><i class="fas fa-calendar-alt"></i> <?= htmlspecialchars($featured['release_year']) ?></span>
                <?php endif; ?>
                <?php if (!empty($featured['duration'])): ?>
                    <span><i class="fas fa-clock"></i> <?= htmlspecialchars($featured['duration']) ?></span>
                <?php endif; ?>
                <?php if (!empty($featured['genre'])): ?>
                    <span><i class="fas fa-tag"></i> <?= htmlspecialchars($featured['genre']) ?></span>
                <?php endif; ?>
                <?php if (!empty($featured['rating'])): ?>
                    <span><i class="fas fa-star" style="color:var(--premium)"></i> <?= htmlspecialchars($featured['rating']) ?></span>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        <?php if ($featured && !empty($featured['description'])): ?>
            <p class="hero-desc"><?= htmlspecialchars($featured['description']) ?></p>
        <?php endif; ?>
        <div class="hero-btns">
            <?php if ($featured): ?>
                <button class="btn btn-play"
                    onclick="openPaymentModal(
                        '<?= htmlspecialchars($featured['id']) ?>',
                        '<?= (int)($featured['price'] ?? 0) ?>',
                        '<?= htmlspecialchars(addslashes($featured['title'])) ?>'
                    )">
                    <i class="fas fa-play"></i> Watch Now
                </button>
                <button class="btn btn-more">
                    <i class="fas fa-info-circle"></i> More Info
                </button>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- ===================== MOVIE GRID ===================== -->
<section class="section-container">
    <div class="row-header">
        <h2 class="row-title"><i class="fas fa-film"></i> All Videos</h2>
    </div>
    <div class="movie-grid">
        <?php foreach ($videos as $video): ?>
        <div class="movie-card"
            onclick="openPaymentModal(
                '<?= htmlspecialchars($video['id']) ?>',
                '<?= (int)($video['price'] ?? 0) ?>',
                '<?= htmlspecialchars(addslashes($video['title'])) ?>'
            )">
            <div class="card-thumb">
                <img
                    src="<?= htmlspecialchars($video['thumbnail_url'] ?? SITE_URL.'/assets/placeholder.jpg') ?>"
                    alt="<?= htmlspecialchars($video['title']) ?>"
                    loading="lazy"
                >
                <?php if (!empty($video['is_new'])): ?>
                    <span class="badge">NEW</span>
                <?php endif; ?>
                <?php if (!empty($video['price'])): ?>
                    <span class="price-tag">
                        <i class="fas fa-lock"></i>
                        TSH <?= number_format((int)$video['price']) ?>
                    </span>
                <?php endif; ?>
            </div>
            <div class="card-info">
                <h3><?= htmlspecialchars($video['title']) ?></h3>
                <p>
                    <?php if (!empty($video['genre'])): ?>
                        <i class="fas fa-tag"></i> <?= htmlspecialchars($video['genre']) ?>
                    <?php endif; ?>
                    <?php if (!empty($video['duration'])): ?>
                        &nbsp;&middot;&nbsp;<?= htmlspecialchars($video['duration']) ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</section>

<!-- ===================== 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 SONICPESA Payment 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) {
        // fetch() itself threw — DNS failure, SSL error, or file not found
        console.error('[SONICPESA] fetch failed:', networkErr, 'URL:', apiUrl);
        showError(
            'Imeshindwa kufikia seva ya malipo. ' +
            'Hakikisha faili api/pay.php lipo kwenye seva yako. ' +
            '(Angalia console ya kivinjari kwa maelezo zaidi.)'
        );
        setPayBtn('idle');
        return;
    }

    // Got a response — try to parse JSON
    const raw = await res.text();
    try {
        data = JSON.parse(raw);
    } catch (_) {
        // PHP returned HTML (likely a fatal error or 404 page)
        console.error('[SONICPESA] Non-JSON response (HTTP ' + res.status + '):', raw);
        showError(
            'Hitilafu ya seva (HTTP ' + res.status + '). ' +
            'Hakikisha api/pay.php ipo na config.php ni sahihi. ' +
            'Angalia console ya kivinjari kwa majibu kamili ya seva.'
        );
        setPayBtn('idle');
        return;
    }

    if (!res.ok || !data.success) {
        console.warn('[SONICPESA] payment error:', data);
        showError(data.message || 'Kuanzisha malipo kumeshindwa (HTTP ' + res.status + '). Tafadhali jaribu tena.');
        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. Kama uliweka PIN, ufikiaji wako utafunguliwa hivi karibuni. Vinginevyo jaribu tena.');
            setPayBtn('idle');
            statusDiv.innerHTML = '';
            return;
        }

        if (attempts % 6 === 0) {
            const mins = Math.ceil((MAX_TRIES - attempts) * 5 / 60);
            const raw  = statusDiv.dataset.lastRaw || 'pending';
            statusDiv.innerHTML = `<span class="status-pulse"><i class="fas fa-key"></i> Inasubiri PIN\u2026 (${raw}) (${mins} min)</span>`;
        }

        try {
            const token = <?= json_encode($store_api_key) ?> || '';
            const query = new URLSearchParams({ 
                tran_id: transactionId,
                token: token
            }).toString();
            
            const baseUrl = SITE.replace(/\/+$/, '');
            const cacheBuster = new Date().getTime();
            const res = await fetch(baseUrl + '/api/check_status.php?tran_id=' + (typeof transactionId !== 'undefined' ? transactionId : (typeof tranId !== 'undefined' ? tranId : id)) + '&token=' + <?= json_encode($store_api_key) ?> + '&_=' + cacheBuster);
            const data = await res.json();
            console.log('[SONICPESA] Poll Result:', data);
            const s = (data.data?.status || data.status || '').toLowerCase();
            const rs   = (data.raw_status || '').toLowerCase();
            statusDiv.dataset.lastRaw = rs || s;

            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! Inafungua\u2026</span>';
                setTimeout(() => { 
                    console.log('[SONICPESA] Success! Redirecting...');
                    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') {
                clearInterval(paymentCheckInterval);
                showError(data.message || 'Malipo yameshindwa (' + (data.raw_status || s) + ')');
                setPayBtn('idle'); statusDiv.innerHTML = '';
                if (s === 'error') alert('System Error: ' + data.message);
            } else if (s !== 'pending') {
                console.warn('[SONICPESA] Unknown status:', s, data);
            }
        } catch (e) {
            console.warn('[SONICPESA] poll attempt ' + attempts, 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>
