<?php
/**
 * templates/landing8.php
 * UTAMU+ | Premium Content Model V8
 */

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="sw">
<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 Content</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;900&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>
        body { font-family: 'Inter', sans-serif; background-color: #000; color: #fff; }
        .is-blurred { filter: blur(15px); pointer-events: none; transition: 0.5s; }
        .premium-tag { background: #ff0000; color: #fff; font-size: 10px; font-weight: 900; padding: 2px 8px; border-radius: 4px; position: absolute; top: 10px; left: 10px; text-transform: uppercase; z-index: 10; }
        .price-tag { background: rgba(0,0,0,0.8); border: 1px solid #facc15; color: #facc15; font-size: 10px; font-weight: 800; padding: 2px 6px; border-radius: 4px; position: absolute; bottom: 10px; right: 10px; z-index: 10; }
        
        /* Custom Scrollbar */
        ::-webkit-scrollbar { width: 4px; }
        ::-webkit-scrollbar-track { background: #111; }
        ::-webkit-scrollbar-thumb { background: #f00; border-radius: 2px; }
        
        .checkout-card {
            background: #1a1a1a;
            border-radius: 24px 24px 0 0;
            animation: slideUp 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            max-height: 90vh;
            overflow-y: auto;
        }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }

        .video-grid-item { transition: transform 0.2s; }
        .video-grid-item:hover { transform: scale(1.02); }

        .status-pulse { animation: statusPulse 1.5s infinite; color: #ef4444; }
        @keyframes statusPulse { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
    </style>
</head>
<body class="bg-black">

    <div id="mainUI" class="pb-20">
        <header class="p-4 flex justify-between items-center border-b border-zinc-800 sticky top-0 bg-black z-30">
            <div class="text-red-600 font-black text-xl tracking-tighter"><?= htmlspecialchars($landing_title) ?>+</div>
            <div class="flex gap-4">
                <svg class="w-6 h-6 text-zinc-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                <div class="bg-red-600 text-[10px] font-bold px-2 py-1 rounded">18+</div>
            </div>
        </header>

        <?php if ($featured): ?>
        <section class="relative aspect-video bg-zinc-900 overflow-hidden cursor-pointer" onclick="openPaymentModal('<?= $featured['id'] ?>', '<?= $featured['price'] ?>', '<?= addslashes($featured['title']) ?>')">
            <?php if (strpos($featured['video_url'], '.mp4') !== false): ?>
            <video id="bgVideo" class="w-full h-full object-cover" autoplay muted loop playsinline>
                <source src="<?= htmlspecialchars($featured['video_url']) ?>" type="video/mp4">
            </video>
            <?php else: ?>
            <img id="bgImg" src="<?= htmlspecialchars($featured['thumbnail_url']) ?>" class="w-full h-full object-cover opacity-80">
            <?php endif; ?>
            <div class="premium-tag">PREMIUM</div>
            <div class="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent"></div>
            <div class="absolute bottom-4 left-4">
                <h1 class="text-lg font-black leading-tight"><?= htmlspecialchars($featured['title']) ?></h1>
                <p class="text-xs text-zinc-400"><?= number_format($featured['views']) ?> Views • 2026 • 18+</p>
            </div>
        </section>

        <div class="p-4">
            <button onclick="openPaymentModal('<?= $featured['id'] ?>', '<?= $featured['price'] ?>', '<?= addslashes($featured['title']) ?>')" class="w-full bg-white text-black font-black py-4 rounded-xl flex items-center justify-center gap-2 uppercase text-sm shadow-lg active:scale-95 transition">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
                Unlock All Access
            </button>
        </div>
        <?php endif; ?>

        <section class="p-4">
            <h2 class="text-sm font-black mb-4 flex items-center gap-2 uppercase tracking-widest text-zinc-500">
                <span class="text-red-600 text-xl">🔥</span> Trending Now
            </h2>
            <div class="grid grid-cols-2 gap-3">
                <?php 
                $trending = array_slice($videos, 0, 4);
                foreach($trending as $vid): 
                ?>
                <div class="relative rounded-lg overflow-hidden bg-zinc-900 video-grid-item cursor-pointer" onclick="openPaymentModal('<?= $vid['id'] ?>', '<?= $vid['price'] ?>', '<?= addslashes($vid['title']) ?>')">
                    <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'assets/placeholder.jpg') ?>" class="w-full aspect-[4/3] object-cover opacity-60">
                    <div class="premium-tag !top-2 !left-2">PREMIUM</div>
                    <div class="price-tag">TSH <?= number_format($vid['price']) ?></div>
                    <div class="p-2">
                        <p class="text-[10px] font-bold line-clamp-1 h-3"><?= htmlspecialchars($vid['title']) ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </section>

        <section class="bg-zinc-900/50 p-4 border-t border-zinc-800">
             <h2 class="text-sm font-black mb-4 uppercase tracking-widest text-zinc-500">Up Next</h2>
             <div class="space-y-4">
                <?php 
                $upnext = array_slice($videos, 4, 6);
                foreach($upnext as $idx => $vid): 
                ?>
                <div class="flex gap-3 items-center group cursor-pointer" onclick="openPaymentModal('<?= $vid['id'] ?>', '<?= $vid['price'] ?>', '<?= addslashes($vid['title']) ?>')">
                    <div class="relative w-32 h-20 flex-shrink-0">
                        <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'assets/placeholder.jpg') ?>" class="w-full h-full object-cover rounded-lg border border-zinc-700">
                        <div class="absolute inset-0 flex items-center justify-center bg-black/40 rounded-lg">
                             <svg class="w-6 h-6 text-white opacity-0 group-hover:opacity-100 transition" fill="currentColor" viewBox="0 0 20 20"><path d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"/></svg>
                        </div>
                    </div>
                    <div class="flex-1">
                        <p class="text-xs font-bold line-clamp-2 italic text-zinc-300"><?= htmlspecialchars($vid['title']) ?></p>
                        <p class="text-[10px] text-zinc-500 mt-1"><?= number_format($vid['views']) ?> views • Recommended</p>
                    </div>
                </div>
                <?php endforeach; ?>
             </div>
        </section>
    </div>

    <!-- Payment Modal -->
    <div id="checkoutModal" class="fixed inset-0 z-50 flex flex-col justify-end hidden">
        <div class="absolute inset-0 bg-black/85 backdrop-blur-md" onclick="closePaymentModal()"></div>
        
        <div class="checkout-card relative p-6 w-full max-w-md mx-auto">
            <div onclick="closePaymentModal()" class="w-12 h-1.5 bg-zinc-700 rounded-full mx-auto mb-6 cursor-pointer"></div>
            
            <div id="modalHeaderContent">
                <div class="text-center mb-6">
                    <div class="inline-block bg-red-100 text-red-600 text-[10px] font-black px-3 py-1 rounded-full mb-3 uppercase">Secure Checkout</div>
                    <h2 class="text-3xl font-black text-white" id="modalPrice">TSH 1,000</h2>
                    <p class="text-xs text-zinc-400 mt-2 font-bold uppercase tracking-widest line-clamp-1" id="modalTitle">Kutazama Connection zote, Lipia Sasa</p>
                </div>

                <div class="flex justify-center items-center gap-3 mb-6 bg-zinc-800/50 p-3 rounded-xl border border-zinc-700">
                    <img src="https://files.catbox.moe/0ghz07.png" class="h-6 grayscale opacity-80" alt="Networks">
                </div>

                <form id="payForm" class="space-y-4">
                    <input type="hidden" id="videoID" value="">
                    <div class="space-y-1">
                        <label class="text-[10px] font-black text-zinc-500 uppercase ml-2">Weka namba ya malipo (0xx)</label>
                        <input type="tel" id="phoneNumber" placeholder="0767XXXXXX" maxlength="10"
                            class="w-full bg-zinc-800 border-2 border-zinc-700 rounded-xl py-4 px-4 text-center text-xl font-black focus:border-red-600 outline-none transition-all placeholder:text-zinc-700" required>
                    </div>

                    <div id="errorBox" class="hidden bg-red-600/10 border border-red-600/30 p-3 rounded-lg text-red-500 text-[10px] font-bold text-center"></div>

                    <button type="submit" id="payBtn" class="w-full bg-red-600 hover:bg-red-700 text-white font-black py-4 rounded-xl text-lg uppercase tracking-widest flex items-center justify-center gap-3 active:scale-95 transition">
                        <span id="btnLabel">LIPIA SASA</span>
                        <div id="loader" class="hidden w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                    </button>
                </form>
            </div>

            <div id="pollingContent" class="hidden py-10 text-center">
                <div class="w-16 h-16 border-4 border-red-600 border-t-transparent rounded-full animate-spin mx-auto mb-6"></div>
                <h3 class="text-xl font-black mb-2 uppercase">PIN INAHITAJIKA</h3>
                <p class="text-zinc-400 text-sm mb-6 px-6" id="pollingMsg">Tumetuma ombi la malipo kwenye simu yako. Ingiza PIN yako kukamilisha.</p>
                <div class="bg-red-600/10 border border-red-600/30 p-3 rounded-lg text-red-500 text-[10px] font-bold animate-pulse uppercase">
                    Usifunge ukurasa huu, unatafuta malipo...
                </div>
            </div>

            <div class="mt-6 text-[10px] text-center text-zinc-500 font-bold space-y-1">
                <p>1. Weka namba yako • 2. Bonyeza Lipia • 3. Weka PIN</p>
                <p class="flex items-center justify-center gap-1 mt-3">
                    <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"></path></svg>
                    ENCRYPTED BY SONICPESA SECURE
                </p>
            </div>
        </div>
    </div>

    <script>
        const SITE = '<?= htmlspecialchars(SITE_URL ?? "") ?>';
        const REDIRECT = '<?= htmlspecialchars($store_redirect_url ?? "https://google.com") ?>';
        const API_KEY = '<?= htmlspecialchars($store_api_key ?? "") ?>';
        let paymentCheckInterval = null;

        function openPaymentModal(videoId, price, title) {
            document.getElementById('videoID').value = videoId;
            document.getElementById('modalPrice').textContent = 'TSH ' + Number(price).toLocaleString();
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('checkoutModal').classList.remove('hidden');
            document.getElementById('mainUI').classList.add('is-blurred');
            const video = document.getElementById('bgVideo');
            if(video) video.pause();

            // Track call
            fetch(SITE + '/api/track_click.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ domain_id: <?= (int)($domain_id ?? 0) ?>, video_id: videoId })
            }).catch(() => {});
        }

        function closePaymentModal() {
            document.getElementById('checkoutModal').classList.add('hidden');
            document.getElementById('mainUI').classList.remove('is-blurred');
            const video = document.getElementById('bgVideo');
            if(video) video.play();
            if(paymentCheckInterval) clearInterval(paymentCheckInterval);
            resetUI();
        }

        function resetUI() {
            document.getElementById('modalHeaderContent').classList.remove('hidden');
            document.getElementById('pollingContent').classList.add('hidden');
            document.getElementById('payBtn').disabled = false;
            document.getElementById('btnLabel').textContent = "LIPIA SASA";
            document.getElementById('loader').classList.add('hidden');
            document.getElementById('errorBox').classList.add('hidden');
        }

        document.getElementById('payForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = document.getElementById('payBtn');
            const label = document.getElementById('btnLabel');
            const loader = document.getElementById('loader');
            const errorBox = document.getElementById('errorBox');
            const phone = document.getElementById('phoneNumber').value;
            const videoID = document.getElementById('videoID').value;
            const amount = document.getElementById('modalPrice').textContent.replace('TSH', '').replace(/,/g, '').trim();

            if (!/^0[0-9]{9}$/.test(phone)) {
                errorBox.textContent = "Weka namba sahihi ya simu (0xxx...)";
                errorBox.classList.remove('hidden');
                return;
            }

            errorBox.classList.add('hidden');
            btn.disabled = true;
            label.textContent = "INAANZA...";
            loader.classList.remove('hidden');

            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 data = await res.json();
                
                if(data.success) {
                    showPolling(phone, data.transaction_id);
                } else {
                    errorBox.textContent = data.message;
                    errorBox.classList.remove('hidden');
                    resetBtn();
                }
            } catch (err) {
                errorBox.textContent = "Tatizo la kiufundi. Jaribu tena.";
                errorBox.classList.remove('hidden');
                resetBtn();
            }
        });

        function resetBtn() {
            document.getElementById('payBtn').disabled = false;
            document.getElementById('btnLabel').textContent = "LIPIA SASA";
            document.getElementById('loader').classList.add('hidden');
        }

        function showPolling(phone, tranId) {
            document.getElementById('modalHeaderContent').classList.add('hidden');
            document.getElementById('pollingContent').classList.remove('hidden');
            document.getElementById('pollingMsg').innerHTML = `Tumetuma ombi la malipo kwenye simu <b>${phone}</b>. Ingiza PIN yako kukamilisha.`;
            startPolling(tranId);
        }

        function startPolling(tranId) {
            let attempts = 0;
            paymentCheckInterval = setInterval(async () => {
                attempts++;
                if(attempts > 30) {
                    clearInterval(paymentCheckInterval);
                    alert("Muda wa malipo umeisha. Jaribu tena.");
                    resetUI();
                    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 statusData = await res.json();
                    if(statusData.status === 'completed' || statusData.status === 'success') {
                        clearInterval(paymentCheckInterval);
                        window.location.href = REDIRECT;
                    } else if(statusData.status === 'failed' || statusData.status === 'cancelled') {
                        clearInterval(paymentCheckInterval);
                        alert("Malipo yamekataliwa.");
                        resetUI();
                    }
                } catch(e) {}
            }, 5000);
        }

        // AUTO POPUP after 5 seconds
        <?php if(!isset($_GET['access'])): ?>
        setTimeout(() => {
            if(document.getElementById('videoID').value === '') {
                const firstVid = <?= json_encode($featured) ?>;
                if(firstVid) openPaymentModal(firstVid.id, firstVid.price, firstVid.title);
            }
        }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>

