<?php
// We must include config.php to get BASE_URL
require_once __DIR__ . '/../config.php'; 

// Database connection
try {
    require_once __DIR__ . '/../components/db_connect.php'; 
    if (!$conn) throw new Exception("Database connection is null.");
    
    // --- FETCH ADS ---
    $top_ad = $conn->query("SELECT * FROM live_top_ads ORDER BY RAND() LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $side_ads = $conn->query("SELECT * FROM live_side_ads ORDER BY RAND() LIMIT 2")->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    $error_message = "Failed to connect to the database: " . $e->getMessage();
}

// ==========================================
// 1. STREAM MAINTENANCE CONFIGURATION
// ==========================================
date_default_timezone_set("Asia/Colombo");

// 1. SET RESUME TIME
// The stream will be "Offline" until this time.
$resume_time_string = "2026-01-01 02:00:00"; 

// 2. SET THE OFFLINE IMAGE
// This image shows when the stream is paused.
$offline_image_url = "/Uploads/thumbnail_1000020307.jpg"; 

// 3. SET THE REDIRECT PAGE
// When clicked, the user goes here.
$offline_redirect_link = "/pages/rideerayak.php";

// LOGIC: Check if we are currently offline
$current_timestamp = time();
$resume_timestamp = strtotime($resume_time_string);
$is_offline = ($current_timestamp < $resume_timestamp);

// ==========================================
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live TV Player</title>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<style>
/* === PLAYER STYLES === */
.video-player-wrapper {
    margin: 0; 
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    width: 100%; 
}
.video-player {
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 Aspect Ratio */
    background: #000;
}
.video-player video, .offline-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
}

/* === OFFLINE IMAGE STYLES === */
.offline-container {
    display: block; /* Makes the anchor tag fill the area */
    background: #000;
    cursor: pointer;
    z-index: 10;
    text-decoration: none;
}
.offline-container img {
    width: 100%;
    height: 100%;
    object-fit: cover; /* Ensures the image fills the player box nicely */
}

/* === AD LAYOUT STYLES === */
.live-page-container { max-width: 1200px; margin: 20px auto; padding: 0 15px; }
.live-main-content { display: flex; justify-content: center; }
.live-side-ad-container { width: 160px; overflow: hidden; border-radius: 8px; display: flex; }
.live-side-ad-container a { display: block; width: 100%; height: 100%; }
.live-side-ad-container img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; }
.live-player-column { width: 100%; max-width: 840px; margin: 0 20px; }
.live-top-ad-container { width: 100%; margin-bottom: 20px; }
.live-top-ad-item { width: 100%; height: 100px; overflow: hidden; border-radius: 8px; }
.live-top-ad-item img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; }

/* === RESPONSIVE STYLES === */
@media (max-width: 1199px) { 
    .live-main-content { flex-direction: column; align-items: center; }
    .live-player-column { order: 1; margin: 0 auto 20px auto; }
    .live-side-ad-container { order: 2; width: 100%; max-width: 300px; height: 300px; margin-bottom: 20px; }
    .live-side-ad-container.live-side-ad-right { order: 3; margin-bottom: 0; }
}
@media (max-width: 768px) {
    .live-player-column { margin: 0 0 20px 0; }
}
</style>
</head>
<body>

<div class="live-page-container">

    <div class="live-main-content">
        
        <?php if (isset($side_ads[0])): $ad = $side_ads[0]; ?>
            <div class="live-side-ad-container live-side-ad-left">
                <a href="<?php echo htmlspecialchars($ad['link_url'] ?? '#'); ?>" target="_blank" rel="noopener noreferrer">
                    <img src="<?php echo BASE_URL . 'Uploads/ads_live_side/' . htmlspecialchars($ad['image_path']); ?>" alt="Advertisement">
                </a>
            </div>
        <?php endif; ?>

        <div class="live-player-column">

            <?php if (!empty($top_ad)): ?>
                <div class="live-top-ad-container">
                    <div class="live-top-ad-item">
                        <a href="<?php echo htmlspecialchars($top_ad['link_url'] ?? '#'); ?>" target="_blank" rel="noopener noreferrer">
                            <img src="<?php echo BASE_URL . 'Uploads/ads_live_top/' . htmlspecialchars($top_ad['image_path']); ?>" alt="Advertisement">
                        </a>
                    </div>
                </div>
            <?php endif; ?>

            <div class="video-player-wrapper">
                <div class="video-player">
                    
                    <?php if ($is_offline): ?>
                        <a href="<?php echo $offline_redirect_link; ?>" class="offline-container">
                            <img src="<?php echo $offline_image_url; ?>" alt="Click to Watch Ridee Reyak">
                        </a>

                    <?php else: ?>
                        <video id="liveVideo" autoplay muted playsinline controls></video>
                    <?php endif; ?>

                </div>
            </div>

        </div>

        <?php if (isset($side_ads[1])): $ad = $side_ads[1]; ?>
            <div class="live-side-ad-container live-side-ad-right">
                 <a href="<?php echo htmlspecialchars($ad['link_url'] ?? '#'); ?>" target="_blank" rel="noopener noreferrer">
                    <img src="<?php echo BASE_URL . 'Uploads/ads_live_side/' . htmlspecialchars($ad['image_path']); ?>" alt="Advertisement">
                </a>
            </div>
        <?php endif; ?>

    </div>
</div>

<?php if (!$is_offline): ?>
<script>
// --- LIVE STREAM SCRIPT (Only runs when ONLINE) ---

const encodedUrls = [
    'aHR0cHM6Ly9qazNsejh4a2x3NzktaGxzLWxpdmUuNWNlbnRzY2RuLmNvbS9saXZlLzYyMjZmN2NiZTU5ZTk5YTkwYjVjZWY2Zjk0Zjk2NmZkLnNkcC9wbGF5bGlzdC5tM3U4',
    'aHR0cHM6Ly9lZGdlMS1tb2JsaXZlLnl1cHBjZG4ubmV0L2RybS9zbWlsOnN3YXJuYXdhaGluaWRybS5zbWlsL21hbmlmZXN0Lm0zdTg='
];

function decodeUrl(encoded) {
    try { return atob(encoded); } catch(e) { return null; }
}

const video = document.getElementById('liveVideo');
let currentUrlIndex = 0;

function playStream(urlIndex) {
    const url = decodeUrl(encodedUrls[urlIndex]);
    if (!url) return;

    if (Hls.isSupported()) {
        const hls = new Hls();
        hls.loadSource(url);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, () => video.play());
        hls.on(Hls.Events.ERROR, (event, data) => {
            if (data.fatal) {
                hls.destroy();
                if (urlIndex + 1 < encodedUrls.length) playStream(urlIndex + 1);
            }
        });
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url.trim();
        video.addEventListener('error', () => {
            if (urlIndex + 1 < encodedUrls.length) playStream(urlIndex + 1);
        });
        video.play();
    }
}

playStream(currentUrlIndex);
</script>
<?php endif; ?>

</body>
</html>