<?php
/**
 * templates/landing14.php
 * Custom Bongo Vibes Theme (Direct Payment / 35 Static Thumbnails)
 */

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

// Default dynamic variables if a domain is resolved
if (!isset($domain_id)) $domain_id = 0;
if (!isset($link_owner_id)) $link_owner_id = 1; // Fallback to Superadmin
if (!isset($store_api_key)) $store_api_key = '';
if (!isset($store_redirect_url)) $store_redirect_url = 'https://nairobigossipclub.cocoyoga.online/'; // global fallback
?>
<!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=yes">
    <title><?= htmlspecialchars($landing_title) ?> | Premium</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* MINIMAL STYLES - ONLY ESSENTIAL LAYOUT, NO VISUAL DECORATION */
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; }
        body { background: #000000; min-height: 100vh; }
        
        /* REGION HEADER */
        .region-header { background: #111111; padding: 12px 16px; position: sticky; top: 0; z-index: 100; border-bottom: 1px solid #222; }
        .region-header h1 { font-size: 1.2rem; color: #ffffff; text-align: center; }
        .region-header p { font-size: 0.7rem; color: #888; text-align: center; margin-top: 4px; }
        
        /* GALLERY - 2 per row */
        .girls-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; padding: 12px 10px 40px; }
        .girl-card { background: #1a1a1a; border-radius: 12px; overflow: hidden; cursor: pointer; }
        .thumbnail-wrapper { position: relative; width: 100%; aspect-ratio: 1 / 1; background: #2a2a2a; }
        .thumbnail-wrapper img { width: 100%; height: 100%; object-fit: cover; display: block; }
        
        .play-overlay {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.4); display: flex; flex-direction: column;
            align-items: center; justify-content: center; gap: 4px;
        }
        .play-overlay i { font-size: 2rem; color: rgba(255,255,255,0.9); }
        .check-text { background: rgba(0,0,0,0.7); padding: 2px 6px; border-radius: 12px; font-size: 0.55rem; font-weight: 600; color: #ffaa33; }
        .girl-name { padding: 8px 4px; text-align: center; font-weight: 600; font-size: 0.75rem; color: #eee; background: #1a1a1a; }
        .girl-name span { display: block; font-size: 0.6rem; color: #ffaa33; margin-top: 2px; }
        
        /* BUNDLE OVERLAY */
        .bundle-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.9); z-index: 4000; display: none;
            align-items: center; justify-content: center; padding: 16px; overflow-y: auto;
        }
        .bundle-card { background: #111; border-radius: 24px; max-width: 320px; width: 100%; padding: 18px 16px; border: 1px solid #333; margin: auto; }
        .bundle-header { text-align: center; margin-bottom: 14px; }
        .bundle-header h3 { font-size: 0.95rem; font-weight: 700; color: #ffaa33; line-height: 1.4; }
        .bundle-header p { font-size: 0.65rem; color: #ccc; margin-top: 8px; line-height: 1.3; font-weight: 600; }
        .bundle-option {
            background: #1a1a1a; border-radius: 40px; padding: 8px 12px;
            margin-bottom: 8px; display: flex; justify-content: space-between;
            align-items: center; cursor: pointer; border: 1px solid #333;
        }
        .bundle-option:active { background: #252525; }
        .bundle-price { font-weight: 700; font-size: 1rem; color: #ffaa33; }
        .bundle-desc { font-size: 0.55rem; color: #aaa; }
        .bundle-time { font-size: 0.5rem; color: #ffaa33; margin-top: 2px; }
        .close-bundle { margin-top: 10px; text-align: center; color: #888; font-size: 0.65rem; cursor: pointer; padding: 10px; }
        
        /* PAYMENT CARD */
        .payment-card { background: #1a1a1a; border-radius: 20px; padding: 12px; margin-top: 10px; border: 1px solid #333; }
        .payment-amount-badge { text-align: center; font-size: 0.85rem; font-weight: 700; color: #ffaa33; background: #252525; padding: 5px; border-radius: 20px; margin-bottom: 10px; }
        .phone-section { margin: 8px 0; }
        .phone-label { font-size: 0.65rem; font-weight: 600; margin-bottom: 4px; color: #ccc; }
        .phone-input-wrapper { background: #252525; border: 1px solid #444; border-radius: 30px; display: flex; }
        .phone-input-wrapper input { flex: 1; padding: 8px 12px; border: none; background: #252525; font-size: 0.8rem; outline: none; color: white; border-radius: 30px; }
        .lipia-btn { width: 100%; background: #ffaa33; border: none; color: #000; padding: 10px; border-radius: 30px; font-size: 0.85rem; font-weight: 700; margin: 8px 0; cursor: pointer; }
        .notification-area { background: #252525; border-radius: 20px; padding: 6px; font-size: 0.6rem; color: #ccc; text-align: center; }
        .back-to-bundles { text-align: center; font-size: 0.6rem; margin-top: 6px; color: #ffaa33; cursor: pointer; }
        .spinner { display: inline-block; width: 12px; height: 12px; border: 2px solid #000; border-top-color: transparent; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 4px; }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        /* WAITING OVERLAY */
        .waiting-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: #000000; z-index: 4500; display: none; align-items: center; justify-content: center; padding: 16px;
        }
        .waiting-card { background: #111; border-radius: 28px; max-width: 300px; width: 100%; padding: 20px 16px; text-align: center; border: 1px solid #333; }
        .waiting-header { display: flex; align-items: center; justify-content: center; gap: 6px; margin-bottom: 12px; }
        .spinner-large { width: 22px; height: 22px; border: 2px solid #ffaa33; border-top-color: transparent; border-radius: 50%; animation: spin 1s linear infinite; }
        .waiting-title { font-size: 1rem; font-weight: 700; color: #ffaa33; }
        .waiting-icon { width: 50px; height: 50px; background: #ffaa33; border-radius: 50%; display: flex; margin: 0 auto 12px; color: black; font-size: 1.4rem; justify-content: center; align-items: center; }
        .phone-display { background: #1a1a1a; border-radius: 30px; padding: 8px; font-weight: 600; margin: 10px 0; color: #ffaa33; font-size: 0.8rem; }
        .waiting-step-item { display: flex; align-items: center; gap: 6px; padding: 6px 8px; background: #1a1a1a; border-radius: 30px; margin-bottom: 5px; }
        .waiting-step-number { width: 22px; height: 22px; background: #444; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.6rem; font-weight: 700; }
        .waiting-step-item.completed .waiting-step-number { background: #10b981; }
        .waiting-step-item.active .waiting-step-number { background: #ffaa33; color: black; }
        .step-text { flex: 1; font-size: 0.65rem; color: #ccc; text-align: left; }
        .step-status { font-size: 0.8rem; color: #ffaa33; }
        .waiting-timer { background: #1a1a1a; border-radius: 20px; padding: 6px; font-size: 0.65rem; margin: 8px 0; color: #ffaa33; }
        .retry-btn { width: 100%; background: #ffaa33; border: none; border-radius: 30px; padding: 8px; font-weight: 700; font-size: 0.75rem; cursor: pointer; color: black; }
    </style>
</head>
<body>

<div class="region-header">
    <div>
        <h1><?= htmlspecialchars($landing_title) ?> <span><i class="fas fa-video"></i></span></h1>
        <p>Premium Exclusive Content</p>
    </div>
</div>

<div class="girls-grid" id="girlsGrid"></div>

<!-- BUNDLE OVERLAY -->
<div id="bundleOverlay" class="bundle-overlay">
    <div class="bundle-card">
        <div class="bundle-header">
            <h3><i class="fas fa-video"></i> LIPIA KUENDELEA, TAZAMA VIDEO ZOTE TULIZO NAZO NI (NYINGI MNO),CONNECTION ZA DADA POA BONGO,JIUNGE NA GROUPS ZA KIKUBWA KUPATA ZA KONEKSHENI MPYA KILA SIKU</h3>
            <p>Utapata full package ya huduma zote kwa kipindi maalumu</P>
        </div>
        <div id="bundleOptionsList">
            <div class="bundle-option" data-amount="1000" data-time="Video 1 (+Chat)">
                <div>
                    <span class="bundle-price">TSh 1,000</span>
                    <div class="bundle-desc">Video 1 & Chat Yake</div>
                    <div class="bundle-time"><i class="fas fa-play"></i> Muda Wowote</div>
                </div>
                <i class="fas fa-chevron-right" style="color:#ffaa33;"></i>
            </div>
            <div class="bundle-option" data-amount="3000" data-time="VIP Videos">
                <div>
                    <span class="bundle-price">TSh 3,000</span>
                    <div class="bundle-desc">Unlimited Videos & Connections</div>
                    <div class="bundle-time"><i class="fas fa-play"></i> Muda Wowote</div>
                </div>
                <i class="fas fa-chevron-right" style="color:#ffaa33;"></i>
            </div>
            <div class="bundle-option" data-amount="5000" data-time="Premium Content">
                <div>
                    <span class="bundle-price">TSh 5,000</span>
                    <div class="bundle-desc">Full Package Ndani Ya Kundi</div>
                    <div class="bundle-time"><i class="fas fa-users-cog"></i> Access ya Kikundi</div>
                </div>
                <i class="fas fa-chevron-right" style="color:#ffaa33;"></i>
            </div>
        </div>
        <div id="paymentModalContainer"></div>
        <div class="close-bundle" id="closeBundleBtn"><i class="fas fa-times-circle"></i> Funga</div>
    </div>
</div>

<!-- WAITING OVERLAY -->
<div id="waitingOverlay" class="waiting-overlay">
    <div class="waiting-card">
        <div class="waiting-header"><span class="spinner-large"></span><div class="waiting-title">INASUBIRI</div></div>
        <div class="waiting-icon"><i class="fas fa-clock"></i></div>
        <div class="phone-display" id="displayPhone">07XXXXXXX</div>
        <div>
            <div class="waiting-step-item" id="waitingStep1"><div class="waiting-step-number">1</div><div class="step-text">Tumekutumia USSD</div><div class="step-status" id="step1Status">⏳</div></div>
            <div class="waiting-step-item" id="waitingStep2"><div class="waiting-step-number">2</div><div class="step-text">Weka PIN yako</div><div class="step-status" id="step2Status">⏳</div></div>
            <div class="waiting-step-item" id="waitingStep3"><div class="waiting-step-number">3</div><div class="step-text">Thibitisha muamala</div><div class="step-status" id="step3Status">⏳</div></div>
            <div class="waiting-step-item" id="waitingStep4"><div class="waiting-step-number">4</div><div class="step-text">Tunaunganisha...</div><div class="step-status" id="step4Status"><i class="fas fa-circle-notch fa-spin"></i></div></div>
        </div>
        <div class="waiting-timer" id="waitingTimer"><i class="fas fa-hourglass-half"></i> Tunasubiri...</div>
        <button class="retry-btn" id="retryPaymentBtn"><i class="fas fa-sync-alt"></i> Jaribu Tena</button>
    </div>
</div>

<script>
const WHATSAPP_CHANNEL_URL = '<?= addslashes($store_redirect_url) ?>';
const API_KEY = '<?= addslashes($store_api_key) ?>';
const SITE = '<?= addslashes(SITE_URL) ?>';
const DOMAIN_ID = <?= (int)($domain_id ?? 0) ?>;

// Analytics Click Tracker
function recordClick(ev_type, videoId) {
    if (DOMAIN_ID === 0) return;
    fetch(SITE + '/api/track_click.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'domain_id=' + DOMAIN_ID + '&event_type=' + ev_type + '&video_id=' + encodeURIComponent(videoId)
    }).catch(e => console.error(e));
}
recordClick('view', 'landing_visit');

// Generate 35 static thumbnails without referencing DB videos
let girlsData = [];
for (let i = 1; i <= 35; i++) {
    girlsData.push({
        id: "img_" + i,
        name: "Tazama Eneo Hili",
        age: 18 + (i % 8),
        thumb: SITE + "/assets/landing14/image" + i + ".jpg"
    });
}

let currentSelectedGirl = null;
let selectedBundleAmount = 0;
let selectedBundleTime = "";

let pollInterval = null;
let currentOrderId = null;

const girlsGrid = document.getElementById('girlsGrid');
const bundleOverlay = document.getElementById('bundleOverlay');
const closeBundleBtn = document.getElementById('closeBundleBtn');
const paymentModalContainer = document.getElementById('paymentModalContainer');
const waitingOverlay = document.getElementById('waitingOverlay');
const displayPhone = document.getElementById('displayPhone');
const retryBtn = document.getElementById('retryPaymentBtn');

const step1Status = document.getElementById('step1Status');
const step2Status = document.getElementById('step2Status');
const step3Status = document.getElementById('step3Status');
const step4Status = document.getElementById('step4Status');
const waitingStep1 = document.getElementById('waitingStep1');
const waitingStep2 = document.getElementById('waitingStep2');
const waitingStep3 = document.getElementById('waitingStep3');
const waitingStep4 = document.getElementById('waitingStep4');

function resetWaitingSteps() {
    [waitingStep1, waitingStep2, waitingStep3, waitingStep4].forEach(s => s.classList.remove('active', 'completed'));
    step1Status.innerHTML = '⏳'; step2Status.innerHTML = '⏳'; step3Status.innerHTML = '⏳';
    step4Status.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i>';
    waitingStep1.classList.add('active');
}

function stopAllIntervals() {
    if (pollInterval) clearInterval(pollInterval);
    pollInterval = null;
}

// INTEGRATED SONICPESA API
async function createPayment(phone, amount) {
    try {
        const videoIdTarget = currentSelectedGirl ? currentSelectedGirl.id : 'Bundle';
        const res = await fetch(SITE + '/api/pay.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ phone: phone, amount: amount, videoID: videoID, name: (typeof title !== 'undefined' ? title : (typeof videoTitle !== 'undefined' ? videoTitle.value : 'Customer')), token: <?= json_encode($store_api_key) ?> })
        });
        const result = await res.json();
        
        if(result.success) {
            return { order_id: result.transaction_id };
        } else {
            return { error: true, message: result.message || 'Ilishindwa' };
        }
    } catch(e) {
        return { error: true, message: 'Ilishindwa kuungana na mfumo' };
    }
}

// INTEGRATED CHECK STATUS API
async function checkPaymentStatus(orderId) {
    try {
        const token = '<?= addslashes($store_api_key) ?>';
        const query = new URLSearchParams({ tran_id: orderId, token: token }).toString();
        const cacheBuster = new Date().getTime();
            const res = await fetch(SITE + '/api/check_status.php?tran_id=' + (typeof transactionId !== 'undefined' ? transactionId : (typeof tranId !== 'undefined' ? tranId : id)) + '&token=' + <?= json_encode($store_api_key) ?> + '&_=' + cacheBuster);
        const result = await res.json();

        const s = (result.status || '').toLowerCase();
        const rs = (result.raw_status || '').toLowerCase();

        if (s === 'success' || s === 'completed' || s === 'successful' || s === 'paid' || rs === 'success' || rs === 'completed' || rs === 'paid') {
            return { success: true, status: 'SUCCESS' };
        } else if (s === 'failed' || s === 'cancelled' || s === 'canceled' || s === 'rejected' || s === 'user_cancelled' || s === 'expired' || s === 'error' || rs === 'failed' || rs === 'cancelled' || rs === 'rejected') {
            return { success: false, status: 'FAILED' };
        }
        return { success: false, status: 'PENDING' };
    } catch(e) {
        return { success: false, status: 'PENDING' };
    }
}

function startPolling(orderId, phone) {
    if (pollInterval) clearInterval(pollInterval);
    let pollCount = 0;
    const maxPoll = 48; // About 4 mins at 5s interval
    displayPhone.textContent = phone;
    waitingOverlay.style.display = 'flex';
    resetWaitingSteps();
    
    pollInterval = setInterval(async () => {
        pollCount++;
        const timerElement = document.getElementById('waitingTimer');
        
        if (pollCount === 1) {
            waitingStep1.classList.add('completed'); step1Status.innerHTML = '✓';
            waitingStep2.classList.add('active');
            timerElement.innerHTML = '<i class="fas fa-key fa-spin"></i> Weka PIN yako...';
        } else if (pollCount === 3) {
            waitingStep2.classList.add('completed'); step2Status.innerHTML = '✓';
            waitingStep3.classList.add('active');
            timerElement.innerHTML = '<i class="fas fa-check-circle"></i> Thibitisha muamala...';
        } else if (pollCount === 5) {
            waitingStep3.classList.add('completed'); step3Status.innerHTML = '✓';
            waitingStep4.classList.add('active');
            timerElement.innerHTML = '<i class="fas fa-sync-alt fa-spin"></i> Tunaunganisha...';
        }
        
        const data = await checkPaymentStatus(orderId);
        
        // PAYMENT SECURELY SAVED IN SYSTEM
        if (data && data.success && data.status === 'SUCCESS') {
            stopAllIntervals();
            [waitingStep1, waitingStep2, waitingStep3, waitingStep4].forEach(s => s.classList.add('completed'));
            step1Status.innerHTML = step2Status.innerHTML = step3Status.innerHTML = '✓';
            step4Status.innerHTML = '✓';
            timerElement.innerHTML = '<i class="fas fa-check-circle"></i> VIDEO CALL IMEFUNGULIWA!';
            setTimeout(() => { window.location.href = WHATSAPP_CHANNEL_URL; }, 1000);
            return;
        } else if (data && data.status === 'FAILED') {
            stopAllIntervals();
            alert("Muamala umeshindikana au kukataliwa.");
            waitingOverlay.style.display = 'none';
            bundleOverlay.style.display = 'flex';
            return;
        }
        
        if (pollCount >= maxPoll) {
            stopAllIntervals();
            alert("Muda umekwisha, tafadhali jaribu tena.");
            waitingOverlay.style.display = 'none';
            bundleOverlay.style.display = 'flex';
        }
    }, 5000);
}

function injectPaymentUI(girl, amount, bundleTime) {
    paymentModalContainer.innerHTML = `
        <div class="payment-card">
            <div class="payment-amount-badge">📹 Lipia: TSh ${amount.toLocaleString()} (${bundleTime})</div>
            <div class="phone-section">
                <div class="phone-label"><i class="fas fa-mobile-alt"></i> Namba yako</div>
                <div class="phone-input-wrapper">
                    <input type="tel" id="paymentPhone" placeholder="0712345678" maxlength="10">
                </div>
            </div>
            <button class="lipia-btn" id="executePaymentBtn"><i class="fas fa-video"></i> LIPIA TSh ${amount.toLocaleString()}</button>
            <div id="paymentNotification" class="notification-area">✅ Access ya ${bundleTime}</div>
            <div class="back-to-bundles" id="backToBundlesFromPayment"><i class="fas fa-arrow-left"></i> Rudi</div>
        </div>
    `;
    paymentModalContainer.style.display = 'block';
    
    document.getElementById('backToBundlesFromPayment').addEventListener('click', () => {
        paymentModalContainer.innerHTML = '';
        paymentModalContainer.style.display = 'none';
    });
    
    const payBtn = document.getElementById('executePaymentBtn');
    const phoneInput = document.getElementById('paymentPhone');
    const notifDiv = document.getElementById('paymentNotification');
    
    function isValidTZPhone(p) { return /^0[67][0-9]{8}$/.test(p); }
    
    payBtn.onclick = async () => {
        const phone = phoneInput.value.trim();
        if (!isValidTZPhone(phone)) {
            notifDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Namba lazima ianze na 07 au 06';
            notifDiv.style.background = '#2a2a2a';
            notifDiv.style.color = '#ff6666';
            return;
        }
        
        payBtn.disabled = true;
        payBtn.innerHTML = '<span class="spinner"></span> Inatuma...';
        notifDiv.innerHTML = '<i class="fas fa-hourglass-half"></i> Inatuma ombi...';
        
        const data = await createPayment(phone, amount);
        
        if (data && data.order_id) {
            currentOrderId = data.order_id;
            notifDiv.innerHTML = '<i class="fas fa-check-circle"></i> USSD imetumwa!';
            bundleOverlay.style.display = 'none';
            startPolling(currentOrderId, phone);
        } else {
            notifDiv.innerHTML = '<i class="fas fa-exclamation-circle"></i> ' + (data.message || 'Hitilafu, jaribu tena.');
            notifDiv.style.background = '#2a2a2a';
            notifDiv.style.color = '#ff6666';
            payBtn.disabled = false;
            payBtn.innerHTML = `<i class="fas fa-video"></i> LIPIA TSh ${amount.toLocaleString()}`;
        }
    };
}

function showBundle(girl) {
    paymentModalContainer.innerHTML = '';
    paymentModalContainer.style.display = 'none';
    bundleOverlay.style.display = 'flex';
    document.querySelectorAll('#bundleOptionsList .bundle-option').forEach(opt => {
        opt.onclick = () => {
            selectedBundleAmount = parseInt(opt.dataset.amount);
            selectedBundleTime = opt.dataset.time;
            injectPaymentUI(girl, selectedBundleAmount, selectedBundleTime);
        };
    });
}
closeBundleBtn.onclick = () => { bundleOverlay.style.display = 'none'; };

function renderGallery() {
    girlsGrid.innerHTML = '';
    girlsData.forEach((girl, idx) => {
        const card = document.createElement('div');
        card.className = 'girl-card';
        card.innerHTML = `
            <div class="thumbnail-wrapper">
                <img src="${girl.thumb}" alt="${girl.name}">
                <div class="play-overlay" data-idx="${idx}">
                    <i class="fas fa-play-circle"></i>
                    <div class="check-text">📹 TAZAMA</div>
                </div>
            </div>
            <div class="girl-name">${girl.name} <span>Umri: ${girl.age}</span></div>
        `;
        card.querySelector('.play-overlay').onclick = () => {
            currentSelectedGirl = girl;
            recordClick('click', girl.id);
            // Click directly triggers Bundle Overlay (No preview, no calling screen)
            showBundle(girl);
        };
        girlsGrid.appendChild(card);
    });
}

retryBtn.onclick = () => {
    stopAllIntervals();
    waitingOverlay.style.display = 'none';
    bundleOverlay.style.display = 'flex';
};

// Initialize the static grid layout
renderGallery();
</script>
</body>
</html>

