<?php
/**
 * templates/landing10.php
 * Custom Bongo Live Theme
 */

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';
?>
<!DOCTYPE html>
<html lang="sw">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title><?= htmlspecialchars($landing_title) ?> | Premium</title>

<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>

<style>
body{
background:#0b0b0b;
color:#fff;
font-family:'Poppins',sans-serif;
}

.live-pulse{
animation:pulse 1.5s infinite;
}

@keyframes pulse{
0%{opacity:1;}
50%{opacity:0.4;}
100%{opacity:1;}
}

.loader{
border:3px solid rgba(255,255,255,0.1);
border-top:3px solid #10b981;
border-radius:50%;
animation:spin 0.8s linear infinite;
}

@keyframes spin{
to{transform:rotate(360deg);}
}
</style>

</head>

<body class="pb-24">

<header class="sticky top-0 z-50 bg-[#0b0b0b]/90 backdrop-blur-md border-b border-white/10 px-4 py-4 flex justify-between items-center">
<div class="flex items-center gap-2">
<div class="w-3 h-3 bg-red-600 rounded-full live-pulse"></div>
<h1 class="font-black italic text-xl tracking-tighter text-white">
<?= htmlspecialchars($landing_title) ?>
</h1>
</div>
<span class="text-[10px] bg-white/10 px-3 py-1 rounded-full text-gray-400 font-bold uppercase tracking-wider">
Join VIP 👑
</span>
</header>

<div class="px-4 mt-4">
<div class="w-full h-44 rounded-3xl overflow-hidden relative border border-white/10 shadow-2xl">
<img src="https://files.catbox.moe/f1w49y.png" class="w-full h-full object-cover brightness-50">
<div class="absolute inset-0 p-6 flex flex-col justify-end bg-gradient-to-t from-black/80 to-transparent">
<span class="bg-red-600 w-fit text-[10px] font-bold px-2 py-0.5 rounded mb-2 uppercase">
LIVE NOW
</span>
<h2 class="text-2xl font-bold italic">
KAICHAPA MNOO</h2>
<p class="text-xs text-gray-300">
Watu 1,200+ wanatazama sasa...
</p>
</div>
</div>
</div>

<div class="px-4 mt-8">
<h3 class="font-bold text-gray-400 text-[10px] uppercase tracking-[0.2em] mb-4">
Trending Live Videos
</h3>
<div class="grid grid-cols-2 gap-4" id="videoContainer"></div>
</div>

<!-- TOPUP MODAL -->
<div id="topupModal" class="fixed inset-0 z-[100] hidden flex items-center justify-center p-6 bg-black/95 backdrop-blur-md">
<div id="modalContent" class="bg-white rounded-[40px] w-full max-w-sm p-8 text-black relative shadow-2xl">
<button onclick="closeTopup()" class="absolute -top-2 -right-2 bg-black text-white w-10 h-10 rounded-full font-bold text-xl">
×
</button>

<div class="text-center">
<img src="https://i.postimg.cc/L4jJ9Zxb/sanpay-payment.png" class="w-full rounded-3xl mb-4">
<h2 class="text-2xl font-black mb-1 uppercase italic text-emerald-600">
MALIPO SALAMA
</h2>

<p class="text-[13px] text-gray-500 mb-6" id="modalPriceText">
Lipia <b>1,000 TZS</b><br>
kutazama <b>KAICHAPA MNOO</b>
</p>

<form onsubmit="initiatePayment(event)">
<input
type="number"
id="phoneInput"
placeholder="Namba: 07XXXXXXXX"
required
class="w-full bg-gray-100 rounded-2xl p-4 text-center text-xl font-bold mb-4 focus:ring-2 focus:ring-emerald-500 outline-none"
>

<button
type="submit"
id="payBtn"
class="w-full bg-emerald-500 text-white py-4 rounded-2xl font-black text-sm tracking-widest flex items-center justify-center gap-3 active:scale-95 shadow-xl shadow-emerald-500/30">
<span id="btnText">LIPIA TZS 1,000</span>
<div id="btnLoader" class="hidden loader w-5 h-5"></div>
</button>
</form>

<p class="text-[9px] mt-4 text-gray-400 uppercase tracking-widest font-bold italic">
Utapokea ujumbe wa PIN kwenye simu yako
</p>

</div>
</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) ?>;

let pollingInterval = null;
let currentVideoID = '';
let currentPrice = '';

function loadVideos(){
    const container = document.getElementById('videoContainer');
    const videos = [
    <?php foreach($videos as $v): ?>
    {
        id: "<?= $v['id'] ?>",
        price: "<?= $v['price'] ?>",
        title: "<?= addslashes(htmlspecialchars($v['title'])) ?>",
        img: "<?= htmlspecialchars($v['thumbnail_url'] ?: 'https://files.catbox.moe/f1w49y.png') ?>",
        views: "<?= number_format($v['views']) ?>"
    },
    <?php endforeach; ?>
    ];

    // If videos from DB are empty, fallback to the hardcoded ones
    if (videos.length === 0) {
        videos.push(
            {id: '1', price: '1000', title: "Bongo Private 1", img: "https://files.catbox.moe/f1w49y.png", views: "2.1k"},
            {id: '2', price: '1000', title: "Usiku wa Mahaba", img: "https://files.catbox.moe/6tva91.webp", views: "1.5k"},
            {id: '3', price: '1000', title: "VIP Romance", img: "https://files.catbox.moe/ff61kj.jpg", views: "3.2k"},
            {id: '4', price: '1000', title: "Secret Room", img: "https://files.catbox.moe/lgojza.jpg", views: "980"}
        );
    }

    videos.forEach(v => {
        container.innerHTML += `
        <div class="group relative active:scale-95 transition-transform" onclick="handleVideoClick('${v.id}', '${v.price}', '${v.title.replace(/'/g, "\\'")}')">
            <div class="relative overflow-hidden rounded-[2rem] aspect-[3/4] border border-white/5">
                <img src="${v.img}" class="w-full h-full object-cover">
                <div class="absolute bottom-0 inset-x-0 p-4 bg-gradient-to-t from-black/90 to-transparent">
                    <p class="text-[11px] font-bold truncate">${v.title}</p>
                    <p class="text-[9px] text-emerald-400 font-bold">👁️ ${v.views} watching</p>
                </div>
            </div>
        </div>`;
    });
}

function handleVideoClick(videoId, price, title){
    currentVideoID = videoId;
    currentPrice = price;
    
    // Update modal details
    const formattedPrice = Number(price).toLocaleString();
    document.getElementById('modalPriceText').innerHTML = `Lipia <b>${formattedPrice} TZS</b><br>kutazama <b>${title}</b>`;
    document.getElementById('btnText').textContent = `LIPIA TZS ${formattedPrice}`;
    
    openTopup(videoId);
}

function openTopup(videoId){
    document.getElementById('topupModal').classList.remove('hidden');
    // Track click for metrics
    fetch(SITE + '/api/track_click.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ domain_id: DOMAIN_ID, video_id: videoId || currentVideoID })
    }).catch(() => {});
}

function closeTopup(){
    document.getElementById('topupModal').classList.add('hidden');
    if(pollingInterval) clearInterval(pollingInterval);
    resetBtn();
    if(document.getElementById('modalContent').innerHTML.includes('WEKA PIN')) {
        window.location.reload();
    }
}

async function initiatePayment(e){
    e.preventDefault();
    const phone = document.getElementById('phoneInput').value;

    if(!/^0[0-9]{9}$/.test(phone)){
        alert("Ingiza namba sahihi ya Tanzania (mf. 07XXXXXXXX)!");
        return;
    }

    document.getElementById('btnText').textContent="INATUMA...";
    document.getElementById('btnLoader').classList.remove('hidden');
    document.getElementById('payBtn').disabled=true;

    try{
        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){
            showWaitingUI(currentPrice);
            startPolling(result.transaction_id);
        }else{
            alert("Tatizo: " + (result.message || "Imeshindikana."));
            resetBtn();
        }
    }catch(error){
        alert("Hitilafu ya mtandao!");
        resetBtn();
    }
}

function showWaitingUI(amount){
    const formattedPrice = Number(amount || 1000).toLocaleString();
    document.getElementById('modalContent').innerHTML=`
    <div class="text-center py-10">
        <div class="loader w-12 h-12 mx-auto mb-6"></div>
        <h2 class="text-2xl font-black mb-2 uppercase text-emerald-600">WEKA PIN...</h2>
        <p class="text-gray-500 text-sm italic">Tafadhali ingiza PIN yako kwenye simu yako kukamilisha malipo ya TZS ${formattedPrice}.</p>
        <div class="text-red-500 font-bold mt-4 animate-pulse">Usifunge ukurasa huu...</div>
    </div>`;
}

function startPolling(tranId){
    let attempts = 0;
    pollingInterval = setInterval(async()=>{
        attempts++;
        if(attempts > 30) {
            clearInterval(pollingInterval);
            alert("Muda wa malipo umeisha. Jaribu tena.");
            window.location.reload();
            return;
        }

        try{
            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();

            if(result.status === 'completed' || result.status === 'success'){
                clearInterval(pollingInterval);
                window.location.href = WHATSAPP_CHANNEL_URL;
            } else if(result.status === 'failed' || result.status === 'cancelled') {
                clearInterval(pollingInterval);
                alert("Malipo yamekataliwa.");
                window.location.reload();
            }
        }catch(e){
            console.log("Checking payment...");
        }
    },5000);
}

function resetBtn(){
    const formattedPrice = Number(currentPrice || 1000).toLocaleString();
    const btnText = document.getElementById('btnText');
    if(btnText) btnText.textContent=`LIPIA TZS ${formattedPrice}`;
    const btnLoader = document.getElementById('btnLoader');
    if(btnLoader) btnLoader.classList.add('hidden');
    const payBtn = document.getElementById('payBtn');
    if(payBtn) payBtn.disabled = false;
}

window.onload=function(){
    loadVideos();

    /* AUTO POPUP AFTER 3 SECONDS */
    <?php if(!isset($_GET['access'])): ?>
    setTimeout(()=>{
        // Select the first video to trigger for the auto popup
        <?php if(!empty($videos)): ?>
        handleVideoClick('<?= $videos[0]['id'] ?>', '<?= $videos[0]['price'] ?>', '<?= addslashes($videos[0]['title']) ?>');
        <?php else: ?>
        handleVideoClick('1', '1000', 'Bongo Private 1');
        <?php endif; ?>
    }, 3000);
    <?php endif; ?>
};
</script>

</body>
</html>

