<?php
$page_title = "Ridee Reyak | Swarnawahini"; 
require_once '../config.php';
require '../components/db_connect.php';
require '../components/header.php';

// ==========================================
// 1. CONFIGURATION
// ==========================================

// Set Timezone
date_default_timezone_set('Asia/Colombo');

// TARGET DATE (Format: YYYY-MM-DD HH:MM:SS)
// Ensure this is in the FUTURE to see the countdown
$target_date = "2026-04-14 21:30:00"; 

// ---------------------------------------------------------
// PASTE YOUR LINK HERE (Example: Vimeo, Castr, etc.)
// ---------------------------------------------------------
// NOTE: Just put the URL here, not the full <iframe...> tag.
// Add autoplay parameters if your provider supports them (e.g., ?autoplay=1)
$stream_url = "https://player.vimeo.com/video/76979871?h=8272103f6e&autoplay=1&muted=1"; 

// ==========================================
// 2. TIME CALCULATION LOGIC
// ==========================================
$current_time = time();
$target_time = strtotime($target_date);

// Check if the event has ALREADY started
$has_started = ($current_time >= $target_time);

// ==========================================
// PAGINATION LOGIC
// ==========================================
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;

$items_per_page = 8; 
$offset = ($page - 1) * $items_per_page;

$shorts = [];
$total_pages = 1;

try {
    $count_stmt = $conn->query("SELECT COUNT(*) FROM youtube_shorts");
    $total_items = $count_stmt->fetchColumn();
    $total_pages = ceil($total_items / $items_per_page);

    $stmt = $conn->prepare("SELECT * FROM youtube_shorts ORDER BY published_at DESC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $shorts = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    error_log("DB Error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-YOUR_ID_HERE" crossorigin="anonymous"></script>

    <style>
        /* --- GLOBAL STYLES --- */
        body {
            font-family: 'Poppins', sans-serif;
            background: rgb(25, 52, 134);
            color: white;
            min-height: 100vh;
            padding-top: 90px; 
            padding-bottom: 80px;
            overflow-x: hidden;
        }

        /* --- MAIN GLASS CONTAINER --- */
        .glass-container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 20px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.2);
            width: 95%; 
            position: relative;
            z-index: 1; 
        }

        .page-title {
            text-align: center;
            font-weight: 600;
            margin-bottom: 30px;
            color: #FFC107;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
            font-size: 2rem;
        }

        /* --- COUNTDOWN STYLES --- */
        .countdown-wrapper {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            padding: 40px 20px;
            text-align: center;
            height: 100%;
        }

        .time-box {
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.1);
            padding: 15px;
            border-radius: 10px;
            min-width: 80px;
            backdrop-filter: blur(5px);
        }

        .time-val {
            display: block;
            font-size: 2.5rem;
            font-weight: 700;
            color: #FFC107;
            line-height: 1;
        }

        .time-label {
            font-size: 0.8rem;
            color: rgba(255, 255, 255, 0.7);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        /* --- LIVE STREAM CONTAINER --- */
        .live-placeholder-wrapper {
            background: #000;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(255, 193, 7, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
        }
        
        .placeholder-content {
            background: radial-gradient(circle, rgba(26,35,126,1) 0%, rgba(0,0,0,1) 100%);
            display: flex; 
            flex-direction: column; 
            justify-content: center; 
            align-items: center; 
            height: 100%;
            padding: 20px;
        }

        /* Video Box Styling */
        #live-video-box {
            width: 100%;
            height: 100%;
        }
        
        #live-video-box iframe {
            width: 100%;
            height: 100%;
            aspect-ratio: 16/9;
        }

        /* Helper Classes for PHP Toggle */
        .hidden-force { display: none !important; }

        /* --- ADS --- */
        .ad-placeholder {
            background: rgba(0, 0, 0, 0.2);
            border: 1px dashed rgba(255, 255, 255, 0.3);
            display: flex; 
            justify-content: center; 
            align-items: center;
            border-radius: 8px; 
            overflow: hidden;
        }
        .ad-top { width: 100%; height: 90px; margin-bottom: 20px; }
        .ad-vertical { width: 100%; height: 100%; min-height: 400px; }

        /* --- SHORTS CARD --- */
        .shorts-card {
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(20px) saturate(200%);
            -webkit-backdrop-filter: blur(20px) saturate(200%);
            border: 1px solid rgba(255, 255, 255, 0.15);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border-radius: 20px;
            background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.02) 100%);
            overflow: hidden;
            position: relative;
            width: 100%;
            aspect-ratio: 9 / 16; 
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .shorts-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 25px rgba(0, 0, 0, 0.4);
            border-color: #FFC107;
        }

        .shorts-card iframe {
            position: absolute;
            top: 0; left: 0;
            width: 100%; height: 100%; border: none;
        }

        /* --- PAGINATION --- */
        .pagination { margin-top: 2rem; display: flex; justify-content: center; gap: 0.5rem; }
        .pagination .page-link {
            color: #1A237E; background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(0, 25, 118, 0.2); padding: 8px 15px; min-width: 40px; text-align: center; border-radius: 50px;
            transition: background-color 0.3s ease, transform 0.3s ease; text-decoration: none; display: inline-flex; align-items: center; justify-content: center;
        }
        .pagination .page-item.active .page-link { background-color: #FFC107; color: #1A237E; border-color: #FFC107; transform: scale(1.1); }
        .pagination .page-link:hover { background-color: #ff0000; color: #ffffff; transform: scale(1.05); }

        @media (max-width: 991px) {
            .glass-container { border-radius: 10px; }
            .ad-vertical { min-height: 250px; margin-top: 15px; }
            .page-title { font-size: 1.5rem; }
            .time-val { font-size: 1.8rem; }
            .time-box { min-width: 60px; padding: 10px; }
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="glass-container">
        
        <div class="row mb-5 align-items-center">
            
            <div class="col-12 order-1 order-lg-2"> 
                <div class="live-placeholder-wrapper">
                    <div class="ratio ratio-16x9">
                        
                        <div id="countdown-section" class="placeholder-content <?php echo $has_started ? 'hidden-force' : ''; ?>">
                            <i class="bi bi-broadcast text-warning mb-3" style="font-size: 2rem;"></i>
                            <h3 class="text-white mb-3 text-center">Live Stream Starts In</h3>
                            
                            <div class="countdown-wrapper">
                                <div class="time-box">
                                    <span class="time-val" id="days">00</span>
                                    <span class="time-label">Days</span>
                                </div>
                                <div class="time-box">
                                    <span class="time-val" id="hours">00</span>
                                    <span class="time-label">Hrs</span>
                                </div>
                                <div class="time-box">
                                    <span class="time-val" id="minutes">00</span>
                                    <span class="time-label">Mins</span>
                                </div>
                                <div class="time-box">
                                    <span class="time-val" id="seconds">00</span>
                                    <span class="time-label">Secs</span>
                                </div>
                            </div>
                        </div>

                        <div id="live-video-box" style="<?php echo $has_started ? 'display:block;' : 'display:none;'; ?>">
                            <iframe 
                                id="live-iframe" 
                                width="100%" 
                                height="100%" 
                                
                                <?php 
                                    // If STARTED: Use 'src' (Load immediately)
                                    // If WAITING: Use 'data-src' (Load later via JS)
                                    if($has_started) {
                                        echo 'src="' . $stream_url . '"';
                                    } else {
                                        echo 'data-src="' . $stream_url . '"';
                                    }
                                ?>
                                
                                title="Live Stream" 
                                frameborder="0" 
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
                                allowfullscreen>
                            </iframe>
                        </div>

                    </div>
                </div>
            </div>

        </div>

        <h1 class="page-title">Latest Shorts</h1>
        
        <div class="row g-4 justify-content-center">
            <?php if (!empty($shorts)): ?>
                <?php foreach ($shorts as $short): ?>
                    <div class="col-12 col-sm-6 col-lg-3"> 
                        <div class="shorts-card">
                            <iframe 
                                src="https://www.youtube.com/embed/<?php echo $short['video_id']; ?>?rel=0&modestbranding=1&playsinline=1" 
                                title="<?php echo htmlspecialchars($short['title']); ?>" 
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
                                allowfullscreen>
                            </iframe>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-12 text-center py-5">
                    <p class="text-white-50">No shorts available yet. Please sync from Admin Dashboard.</p>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>">Previous</a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>">Next</a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // --- COUNTDOWN LOGIC ---
    
    const countDownDate = <?php echo ($target_time * 1000); ?>;
    
    // Only run the JS timer if the event hasn't started yet
    <?php if(!$has_started): ?>
    
    const x = setInterval(function() {
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        if (distance > 0) {
            document.getElementById("days").innerHTML = days < 10 ? "0" + days : days;
            document.getElementById("hours").innerHTML = hours < 10 ? "0" + hours : hours;
            document.getElementById("minutes").innerHTML = minutes < 10 ? "0" + minutes : minutes;
            document.getElementById("seconds").innerHTML = seconds < 10 ? "0" + seconds : seconds;
        } else {
            clearInterval(x);
            
            // 1. Hide Countdown
            const countdownSection = document.getElementById("countdown-section");
            if (countdownSection) countdownSection.style.display = "none";
            
            // 2. Show Video Box
            const videoBox = document.getElementById("live-video-box");
            if (videoBox) videoBox.style.display = "block";
            
            // 3. Trigger Load
            const iframe = document.getElementById("live-iframe");
            if (iframe) {
                const videoSrc = iframe.getAttribute("data-src");
                if (videoSrc && !iframe.getAttribute("src")) {
                    iframe.setAttribute("src", videoSrc);
                }
            }
        }
    }, 1000);
    
    <?php endif; ?>
</script>

</body>
</html>

<?php require '../components/footer.php'; ?>