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

require 'components/db_connect.php';
session_start();

// Get programme ID from URL
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false || $id <= 0) {
    die("Invalid programme ID.");
}

// Fetch programme info
$stmt = $conn->prepare("SELECT * FROM programmes WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$programme = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Pagination setup
$items_per_page = 21;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
    $page = 1;
}
$offset = ($page - 1) * $items_per_page;

// Fetch programme episodes from database
$episodes_stmt = $conn->prepare("SELECT * FROM programmes_videos WHERE programmes_id = :id ORDER BY published_at DESC LIMIT :offset, :limit");
$episodes_stmt->bindValue(':id', $id, PDO::PARAM_INT);
$episodes_stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$episodes_stmt->bindValue(':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', $id, PDO::PARAM_INT);
$count_stmt->execute();
$total_items = $count_stmt->fetchColumn();
$total_pages = ceil($total_items / $items_per_page);

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

<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%;
}
.sort-container {
    margin-bottom: 20px;
}
/* Pagination styles identical to teledrama page */
.pagination {margin-top:2rem;display:flex;justify-content:center;gap:.5rem;flex-wrap:wrap;}
.pagination .page-item{display:inline-flex;}
.pagination .page-link{color:#1A237E;background-color:rgba(255,255,255,.8);border:1px solid rgba(0,25,118,.2);padding:8px 15px;min-width:40px;text-align:center;border-radius:50px;transition:background-color .3s ease,transform .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,.5);color:#6c757d;opacity:.7;cursor:not-allowed;}
.pagination .page-link:hover{background-color:#ff0000;color:#fff;transform:scale(1.05);}
@media(max-width:991px){.main-content{padding-top:0;}.pagination{gap:.4rem;}.pagination .page-link{padding:6px 12px;min-width:36px;font-size:14px;}}
@media(max-width:576px){.pagination{gap:.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;}}
@media(max-width:400px){.pagination{gap:.2rem;}.pagination .page-link{padding:4px 8px;min-width:28px;font-size:11px;}}
</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'] ?? 'default.jpg';
                    $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 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="?id=<?php echo $id; ?>&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="?id=<?php echo $id; ?>&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="?id=<?php echo $id; ?>&page=<?php echo $page + 1; ?>" aria-label="Next"><span aria-hidden="true">»</span></a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>
    </div>
</div>

<!-- Video Modal -->
<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'));

    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";
    });

    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'; ?>
