<?php
// We must include config.php to get BASE_URL
// FIXED: Made path relative to this file's parent directory
require_once __DIR__ . '/../config.php'; 

// Database connection
try {
    // FIXED: Assumed db_connect.php is in the components folder
    require_once __DIR__ . '/../components/db_connect.php'; 
    if (!$conn) throw new Exception("Database connection is null.");
    
    // --- FETCH ADS ---
    // Fetch 1 random top ad
    $top_ad = $conn->query("SELECT * FROM live_top_ads ORDER BY RAND() LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    // Fetch 2 random side ads
    $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();
}

// Now Showing logic
date_default_timezone_set("Asia/Colombo");
$currentDay = date('l');
$currentTime = date('H:i:s');

try {
    if (isset($conn)) {
        $now_stmt = $conn->prepare("
            SELECT * FROM tv_schedule 
            WHERE day = :day 
            AND time <= :time 
            ORDER BY time DESC 
            LIMIT 1
        ");
        $now_stmt->execute([':day'=>$currentDay, ':time'=>$currentTime]);
        $now_program = $now_stmt->fetch(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    if (!isset($error_message)) $error_message = "DB Error: "."Failed to connect to the database";
}

?>
<!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>
/* === YOUR ORIGINAL STYLES (MODIFIED) === */
.video-player-wrapper {
    margin: 0; 
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    width: 100%; /* Fill the center column */
}
.video-player {
    position: relative;
    width: 100%;
    padding-top: 56.25%; /* 16:9 */
    background: #000;
}
.video-player video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
    background: #000;
}
.player-alert-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 20px;
    font-size: 1rem;
    font-weight: 500;
    background: linear-gradient(90deg, #fdc206, #ff9800);
    color: #000;
}
.player-alert-bar .alert-label { font-weight: 700; text-transform: uppercase; }
.player-alert-bar .alert-text { flex: 1; }
.player-alert-bar .error { color: #fff; background: rgba(220, 53, 69, 0.9); padding: 6px 10px; border-radius: 6px; }


/* === NEW AD LAYOUT STYLES (CORRECTED) === */

.live-page-container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 15px; 
}

/* 1. Main Content (Ads + Player) */
.live-main-content {
    display: flex;
    justify-content: center; 
    
    /* The default 'stretch' will make all columns the same height */
}

/* 2. Side Ads */
.live-side-ad-container {
    width: 160px;
    
    /* Removed fixed height, it will now stretch */
    
    /* background: #f0f0f0; */ /* REMOVED: Placeholder color */
    
    overflow: hidden;
    border-radius: 8px;

    /* Add this to make the <a> tag fill the height */
    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; /* Added border-radius to the image itself */
}

/* 3. Player Column */
.live-player-column {
    width: 100%;
    max-width: 840px; 
    margin: 0 20px; /* This creates the gaps */
}

/* 4. Top Ad (Now inside the player column) */
.live-top-ad-container {
    width: 100%;
    margin-bottom: 20px;
}
.live-top-ad-item {
    width: 100%;
    height: 100px; /* You changed this from 50px */
    /* background: #f0f0f0; */ /* REMOVED: Placeholder color */
    overflow: hidden;
    border-radius: 8px;
}
.live-top-ad-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px; /* Added border-radius to the image itself */
}


/* === RESPONSIVE STYLES === */

@media (max-width: 1199px) { 
    .live-main-content {
        flex-direction: column;  /* Stack all columns vertically */
        align-items: center;   /* Center the stacked items */
    }

    .live-player-column {
        order: 1; /* Player column (with top ad) comes first */
        margin: 0 auto 20px auto; /* No side margins, 20px bottom margin */
    }
    
    .live-side-ad-container {
        order: 2; /* Both side ads come after the player */
        width: 100%;
        max-width: 300px; /* A reasonable mobile ad width */
        height: 300px; /* A reasonable mobile ad height */
        margin-bottom: 20px; /* Space between stacked ads */
    }
    
    .live-side-ad-container.live-side-ad-right {
        order: 3; /* Right ad comes last */
        margin-bottom: 0;
    }
}
@media (max-width: 768px) {
    .player-alert-bar { font-size: 0.9rem; padding: 10px 15px; }
    
    .live-player-column {
        margin: 0 0 20px 0; /* No side margins on small screens */
    }
}
@media (max-width: 576px) {
    .player-alert-bar { flex-direction: column; align-items: flex-start; font-size: 0.85rem; }
}
</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">
                    <video id="liveVideo" autoplay muted playsinline controls></video>
                </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>


<script>
// Encoded URLs (Base64)
const encodedUrls = [
    'aHR0cHM6Ly9qazNsejh4a2x3NzktaGxzLWxpdmUuNWNlbnRzY2RuLmNvbS9saXZlLzYyMjZmN2NiZTU5ZTk5YTkwYjVjZWY2Zjk0Zjk2NmZkLnNkcC9wbGF5bGlzdC5tM3U4',
    'aHR0cHM6Ly9lZGdlMS1tb2JsaXZlLnl1cHBjZG4ubmV0L2RybS9zbWlsOnN3YXJuYXdhaGluaWRybS5zbWlsL21hbmlmZXN0Lm0zdTg='
];

// Decode Base64 to URL
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 alert('Live stream is unavailable.');
            }
        });
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url.trim();
        video.addEventListener('error', () => {
            if (urlIndex + 1 < encodedUrls.length) playStream(urlIndex + 1);
            else alert('Live stream is unavailable.');
        });
        video.play();
    } else {
        alert('HLS not supported in this browser.');
    }
}

// Start playback
playStream(currentUrlIndex);
</script>

</body>
</html>