<?php
// v.php
require_once 'config.php';
require_once 'includes/db.php';

try {
    // Determine user context. This system assumes 1 main user holding videos,
    // or we fetch all active videos from the system. For a multi-tenant setup,
    // v.php could filter by a user_id based on domain or query param. 
    // Here we fetch all active videos.
    $stmt = $pdo->query("SELECT * FROM videos WHERE status = 'active' ORDER BY views DESC, created_at DESC LIMIT 20");
    $videos = $stmt->fetchAll();
    
    // Featured video
    $featured_id = $_GET['id'] ?? '';
    if ($featured_id) {
        $stmt_feat = $pdo->prepare("SELECT * FROM videos WHERE id = ? AND status = 'active'");
        $stmt_feat->execute([$featured_id]);
        $featured = $stmt_feat->fetch();
    } else {
        $featured = $videos[0] ?? null;
    }
} catch (PDOException $e) {
    $videos = [];
    $featured = 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><?= $featured ? htmlspecialchars($featured['title']) : 'UTAMU+ | 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">
    <style>
        /* Essential CSS adapted from template */
        :root { --primary: #e50914; --primary-hover: #f40612; --bg: #0f0f0f; --card-bg: #181818; --text-main: #ffffff; --text-dim: #b3b3b3; --premium: #ffd700; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text-main); line-height: 1.5; overflow-x: hidden; }
        .navbar { position: fixed; top: 0; width: 100%; z-index: 1000; padding: 12px 5%; display: flex; justify-content: space-between; background: rgba(15,15,15,0.9); border-bottom: 1px solid rgba(255,255,255,0.1); }
        .logo { font-size: 1.5rem; font-weight: 800; color: var(--primary); text-decoration: none; }
        .nav-right { display: flex; gap: 20px; align-items: center; }
        .avatar { width: 32px; height: 32px; background: var(--primary); border-radius: 4px; display: grid; place-items: center; font-weight: bold; font-size: 0.8rem; }
        
        .hero { min-height: 80vh; display: flex; align-items: flex-end; padding: 80px 5% 40px; background: linear-gradient(to top, var(--bg), transparent), url('<?= $featured && $featured['thumbnail_url'] ? htmlspecialchars($featured['thumbnail_url']) : 'assets/landing2.jpg' ?>') center/cover; position: relative; }
        .hero-content { z-index: 2; max-width: 800px; width: 100%; }
        .hero-tag { background: var(--primary); padding: 6px 14px; border-radius: 4px; font-size: 0.75rem; font-weight: 700; display: inline-block; margin-bottom: 20px; }
        .hero-title { font-size: 3rem; font-weight: 800; margin-bottom: 15px; }
        .btn-play { padding: 16px 30px; background: #fff; color: #000; border: none; border-radius: 8px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-size: 1rem; width: 100%; max-width: 300px; justify-content: center; }
        .btn-play:hover { background: rgba(255,255,255,0.9); }
        
        .section-container { padding: 50px 5%; }
        .movie-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 20px; }
        .movie-card { background: var(--card-bg); border-radius: 12px; overflow: hidden; position: relative; aspect-ratio: 2/3; display: flex; flex-direction: column; cursor: pointer; transition: transform 0.2s; }
        .movie-card:hover { transform: translateY(-5px); }
        .card-thumb { flex: 1; background: #222; position: relative; overflow: hidden; }
        .card-thumb img { width: 100%; height: 100%; object-fit: cover; }
        .badge { position: absolute; top: 10px; left: 10px; background: var(--primary); padding: 4px 10px; font-size: 0.65rem; font-weight: 800; border-radius: 4px; }
        .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: 0.75rem; font-weight: 700; border: 1px solid var(--premium); }
        .card-info { padding: 15px; background: var(--card-bg); }
        .card-info h3 { font-size: 0.95rem; margin-bottom: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .card-info p { font-size: 0.8rem; color: var(--text-dim); }

        /* Modal */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.9); display: none; justify-content: center; align-items: center; z-index: 2000; padding: 20px; box-sizing: border-box; }
        .modal-content { background: var(--card-bg); width: 100%; max-width: 450px; border-radius: 16px; position: relative; max-height: 90vh; overflow-y: auto; }
        .modal-header { padding: 25px; border-bottom: 1px solid rgba(255,255,255,0.1); text-align: center; border-radius: 16px 16px 0 0; }
        .modal-body { padding: 25px; }
        .close-modal { position: absolute; top: 16px; right: 16px; color: var(--text-dim); cursor: pointer; font-size: 1.5rem; }
        .payment-method { background: #222; border: 2px solid var(--primary); border-radius: 12px; padding: 16px; display: flex; align-items: center; gap: 15px; background: rgba(229,9,20,0.1); margin-bottom: 20px; }
        .payment-method i { font-size: 1.5rem; color: var(--premium); }
        .input-group label { display: block; font-size: 0.85rem; color: var(--text-dim); margin-bottom: 8px; font-weight: 600; }
        .input-group { margin-bottom: 20px; }
        .input-group input { width: 100%; background: #222; border: 1px solid #444; padding: 15px; color: #fff; border-radius: 8px; font-size: 1rem; outline: none; box-sizing: border-box; }
        .input-group input:focus { border-color: var(--primary); }
        .btn-full { width: 100%; background: var(--primary); color: #fff; padding: 15px; border-radius: 10px; border: none; font-size: 1rem; font-weight: bold; cursor: pointer; transition: 0.2s; }
        .btn-full:disabled { opacity: 0.7; pointer-events: none; }
        .btn-full:hover { background: var(--primary-hover); }
    </style>
</head>
<body>
    <nav class="navbar">
        <a href="#" class="logo">UTAMU+</a>
        <div class="nav-right">
            <i class="fas fa-search" style="color:white;cursor:pointer;"></i>
            <div class="avatar">18+</div>
        </div>
    </nav>

    <?php if ($featured): ?>
    <header class="hero">
        <div class="hero-content">
            <span class="hero-tag"><i class="fas fa-crown"></i> PREMIUM ACCESS</span>
            <h1 class="hero-title"><?= htmlspecialchars($featured['title']) ?></h1>
            <button class="btn-play" onclick="openPaymentModal(event, '<?= $featured['price'] ?>', '<?= $featured['id'] ?>')">
                <i class="fas fa-play"></i> UNLOCK ALL ACCESS
            </button>
        </div>
    </header>
    <?php endif; ?>

    <main class="section-container">
        <div style="margin-bottom:20px;">
            <h2 style="font-size:1.5rem;"><i class="fas fa-fire" style="color:var(--primary);"></i> TRENDING NOW</h2>
        </div>
        <div class="movie-grid">
            <?php foreach($videos as $vid): ?>
            <a href="#" onclick="openPaymentModal(event, '<?= $vid['price'] ?>', '<?= $vid['id'] ?>')" style="text-decoration:none; color:inherit;">
                <div class="movie-card">
                    <div class="card-thumb">
                        <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: 'assets/placeholder.jpg') ?>" alt="Thumb">
                        <span class="badge">PREMIUM</span>
                        <span class="price-tag">TSH <?= number_format($vid['price']) ?></span>
                    </div>
                    <div class="card-info">
                        <h3><?= htmlspecialchars($vid['title']) ?></h3>
                        <p><?= number_format($vid['views']) ?> views • <i class="fas fa-star" style="color:var(--premium)"></i></p>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </main>

    <!-- Payment Modal -->
    <div class="modal-overlay" id="paymentModal">
        <div class="modal-content">
            <i class="fas fa-times close-modal" onclick="closePaymentModal()"></i>
            <div class="modal-header">
                <h2 style="color: var(--premium)"><i class="fas fa-shield-alt"></i> Secure Checkout</h2>
                <p style="font-size: 0.8rem; color: var(--text-dim)">Unlock Premium Video Content</p>
            </div>
            <div class="modal-body">
                <input type="hidden" id="videoID" value="">
                <div style="text-align: center; margin-bottom: 20px;">
                    <span style="font-size: 0.9rem; color: var(--text-dim)">Amount to Pay:</span>
                    <h1 id="modalPrice">TSH 0</h1>
                </div>
                <div class="payment-method">
                    <i class="fas fa-mobile-alt"></i>
                    <div>
                        <strong>Mobile Money</strong>
                        <p style="font-size: 0.7rem; color: var(--text-dim)">M-Pesa, Tigo Pesa, Airtel Money, HaloPesa</p>
                    </div>
                </div>
                <div class="input-group">
                    <label>Enter Phone Number (0xxx xxx xxx)</label>
                    <input type="tel" id="phoneNumber" placeholder="0700 000 000" pattern="[0-9]*">
                </div>
                <button class="btn-full" id="payBtn" onclick="processPayment()">PAY SECURELY NOW</button>
            </div>
        </div>
    </div>

    <script>
        let paymentCheckInterval;
        let API_BASE = 'api';

        function openPaymentModal(event, price, id) {
            event.preventDefault();
            document.getElementById('modalPrice').innerText = 'TSH ' + price;
            document.getElementById('videoID').value = id;
            document.getElementById('paymentModal').style.display = 'flex';
        }

        function closePaymentModal() {
            document.getElementById('paymentModal').style.display = 'none';
            if (paymentCheckInterval) clearInterval(paymentCheckInterval);
            resetPayBtn();
        }

        function resetPayBtn() {
            let b = document.getElementById('payBtn');
            b.innerHTML = 'PAY SECURELY NOW';
            b.disabled = false;
            b.style.backgroundColor = '';
        }

        async function processPayment() {
            const phone = document.getElementById('phoneNumber').value.trim();
            const videoID = document.getElementById('videoID').value;
            const amount = document.getElementById('modalPrice').innerText.replace('TSH ','').trim();
            const btn = document.getElementById('payBtn');

            if (!phone || phone.length < 10) {
                alert('Please enter a valid phone number');
                return;
            }

            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> INITIATING...';

            try {
                let res = await fetch(SITE_URL + '/api/pay.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ phone: phone, amount: amount, videoID: videoID, token: <?= json_encode($store_api_key ?? '') ?> })
                });
                let data = await res.json();
                
                if (data.success) {
                    btn.innerHTML = '<i class="fas fa-clock"></i> AWAITING PIN (Check Phone)...';
                    checkStatus(data.transaction_id, data.redirect_url);
                } else {
                    alert('Error: ' + data.message);
                    resetPayBtn();
                }
            } catch(e) {
                alert('Network error.');
                resetPayBtn();
            }
        }

        function checkStatus(tranId, redirectUrl) {
            let attempts = 0;
            const maxAttempts = 20;

            paymentCheckInterval = setInterval(async () => {
                attempts++;
                if (attempts > maxAttempts) {
                    clearInterval(paymentCheckInterval);
                    alert('Payment timeout. Please try again.');
                    resetPayBtn();
                    return;
                }

                try {
                    const cacheBuster = Date.now();
                    let res = await fetch(SITE_URL + '/api/check_status.php?tran_id=' + encodeURIComponent(tranId) + '&token=' + encodeURIComponent(<?= json_encode($store_api_key ?? '') ?>) + '&_=' + cacheBuster);
                    let d = await res.json();

                    if (d.status === 'completed' || d.status === 'success' || d.status === 'successful' || d.status === 'paid') {
                        clearInterval(paymentCheckInterval);
                        let btn = document.getElementById('payBtn');
                        btn.style.backgroundColor = '#28a745';
                        btn.innerHTML = '<i class="fas fa-check"></i> SUCCESSFUL! REDIRECTING...';
                        setTimeout(() => window.location.href = redirectUrl, 1500);
                    } else if (d.status === 'failed' || d.status === 'cancelled' || d.status === 'rejected' || d.status === 'user_cancelled' || d.status === 'expired') {
                        clearInterval(paymentCheckInterval);
                        alert('Payment failed or cancelled.');
                        resetPayBtn();
                    }
                } catch(e) {}
            }, 5000);
        }
    </script>
</body>
</html>

