<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'components/db_connect.php';

// Start session
session_start();

// 1. INPUT HANDLING (SLUG vs ID)
$slug = isset($_GET['slug']) ? $_GET['slug'] : '';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$programme = null;

// 2. FETCH PROGRAMME DETAILS (Main Info)
if (!empty($slug)) {
    $stmt = $conn->prepare("SELECT * FROM programmes WHERE slug = :slug");
    $stmt->bindParam(':slug', $slug);
    $stmt->execute();
    $programme = $stmt->fetch(PDO::FETCH_ASSOC);
} elseif ($id > 0) {
    $stmt = $conn->prepare("SELECT * FROM programmes WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    $programme = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$programme) {
    die("Programme not found.");
}

// Get the real ID
$programme_real_id = $programme['id'];

// 3. FETCH EPISODES FROM DATABASE
$items_per_page = 21;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $items_per_page;

// --- CRITICAL FIX: Using 'programmes_id' based on your schema ---
$episodes_stmt = $conn->prepare("SELECT * FROM programmes_videos WHERE programmes_id = :id ORDER BY published_at DESC LIMIT :offset, :limit");
$episodes_stmt->bindParam(':id', $programme_real_id, PDO::PARAM_INT);
$episodes_stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$episodes_stmt->bindParam(':limit', $items_per_page, PDO::PARAM_INT);
$episodes_stmt->execute();
$episodes = $episodes_stmt->fetchAll(PDO::FETCH_ASSOC);

// Count total episodes for pagination
$count_stmt = $conn->prepare("SELECT COUNT(*) FROM programmes_videos WHERE programmes_id = :id");
$count_stmt->bindParam(':id', $programme_real_id, PDO::PARAM_INT);
$count_stmt->execute();
$total_items = $count_stmt->fetchColumn();
$total_pages = ceil($total_items / $items_per_page);

// 4. PAGINATION URL BASE
if (!empty($slug)) {
    $paginationBase = "programmes/" . htmlspecialchars($slug) . "?";
} else {
    $paginationBase = "programme_detail.php?id=" . $programme_real_id . "&";
}

$page_title = $programme['title'] . " | Swarnawahini";
require 'components/header.php';
?>

<base href="https://www.swarnavahini.lk/">

<style>
body { margin: 0; padding: 0; min-height: 100vh; position: relative; }
.main-content { padding-bottom: 150px; width: 100%; padding-top: 110px; }
.container { max-width: 1200px; margin: 0 auto; padding: 0 15px; padding-top: 20px; }
.row:last-child { margin-bottom: 20px; }
.video-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; }
.video-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.pagination { margin-top: 2rem; display: flex; justify-content: center; gap: 0.5rem; flex-wrap: wrap; }
.pagination .page-item { display: inline-flex; }
.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; font-size: 16px; }
.pagination .page-item.active .page-link { background-color: #FFC107; color: #1A237E; border-color: #FFC107; transform: scale(1.1); }
.pagination .page-item.disabled .page-link { background-color: rgba(255, 255, 255, 0.5); color: #6c757d; opacity: 0.7; cursor: not-allowed; }
.pagination .page-link:hover { background-color: #ff0000; color: #ffffff; transform: scale(1.05); }
@media (max-width: 991px) { .main-content { padding-top: 0px; } .pagination { gap: 0.4rem; } .pagination .page-link { padding: 6px 12px; min-width: 36px; font-size: 14px; } }
@media (max-width: 576px) { .pagination { gap: 0.3rem; padding: 0 10px; } .pagination .page-link { padding: 5px 10px; min-width: 32px; font-size: 12px; line-height: 1.5; } .pagination .page-item { margin: 2px 0; } }
</style>

<div class="main-content">
    <div class="container">
        <h1 style="color: #FFC107;"><?php echo htmlspecialchars($programme['title']); ?></h1>
     
     
          
                 
              
     

        <h3 style="color: #FFC107;">Episodes</h3>
        
        <div class="row row-cols-1 row-cols-md-3 g-4" id="episodeList">
            <?php if (!empty($episodes)) {
                foreach ($episodes as $episode) { 
                    $video_id = $episode['video_id']; 
                    $title = $episode['title'];
                    $thumbnail = $episode['thumbnail']; 
                    $published_at = $episode['published_at'];
            ?>
                <div class="col episode-item" data-published-at="<?php echo htmlspecialchars($published_at); ?>">
                    <div class="card mb-4">
                        <img src="<?php echo htmlspecialchars($thumbnail); ?>" 
                             class="card-img-top" 
                             alt="<?php echo htmlspecialchars($title); ?>" 
                             style="width:100%; height:auto; object-fit:contain;">
                        <div class="card-body">
                            <h6 class="card-title"><?php echo htmlspecialchars($title); ?></h6>
                            <button type="button" 
                                    class="btn btn-primary btn-sm watch-video" 
                                    data-bs-toggle="modal" 
                                    data-bs-target="#videoModal" 
                                    data-video-id="<?php echo htmlspecialchars($video_id); ?>" 
                                    data-title="<?php echo htmlspecialchars($title); ?>">
                                Watch
                            </button>
                        </div>
                    </div>
                </div>
            <?php } 
            } else { ?> 
                <div class="col">
                    <p>No episodes found in the database for this programme.</p>
                </div>
            <?php } ?>
        </div>

        <?php if ($total_pages > 1): ?>
            <nav aria-label="Episode pagination" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="<?php echo $paginationBase; ?>page=<?php echo $page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">«</span>
                        </a>
                    </li>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                            <a class="page-link" href="<?php echo $paginationBase; ?>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="<?php echo $paginationBase; ?>page=<?php echo $page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">»</span>
                        </a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="videoModal" tabindex="-1" aria-labelledby="videoModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="videoModalLabel">Watch Video</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="video-container">
                    <iframe id="videoPlayer" width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const videoModal = document.getElementById('videoModal');
    const videoPlayer = document.getElementById('videoPlayer');
    const videoTitle = document.getElementById('videoModalLabel');
    const sortOrderSelect = document.getElementById('sortOrder'); 
    const episodeList = document.getElementById('episodeList');
    const episodeItems = Array.from(document.querySelectorAll('.episode-item'));

    if (videoModal) {
        videoModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const videoId = button.getAttribute('data-video-id');
            const title = button.getAttribute('data-title');
            videoPlayer.src = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
            videoTitle.textContent = title;
        });

        videoModal.addEventListener('hidden.bs.modal', function () {
            videoPlayer.src = '';
            videoTitle.textContent = "Watch Video";
        });
    }

    if (sortOrderSelect) {
        sortOrderSelect.addEventListener('change', function () {
            const sortOrder = this.value;
            const sortedItems = episodeItems.sort((a, b) => {
                const dateA = new Date(a.getAttribute('data-published-at'));
                const dateB = new Date(b.getAttribute('data-published-at'));
                return sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
            });
            episodeList.innerHTML = '';
            sortedItems.forEach(item => episodeList.appendChild(item));
        });
    }
});
</script>

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