<?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();

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

$stmt = $conn->prepare("SELECT * FROM teledramas WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$teledrama = $stmt->fetch(PDO::FETCH_ASSOC);

// Check if teledrama exists
if (!$teledrama) {
    die("Teledrama not found.");
}

// YouTube API setup
$api_key = 'AIzaSyBAON_ChCgF5BEXX7ijp--GImeRmAHdUBY';
$playlist_id = $teledrama['youtube_playlist'];
$items_per_page = 21; // Match the previous page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page_token = isset($_GET['pageToken']) ? $_GET['pageToken'] : '';

// Reset page tokens if teledrama ID changes
if (!isset($_SESSION['current_teledrama_id']) || $_SESSION['current_teledrama_id'] != $id) {
    $_SESSION['page_tokens'] = [];
    $_SESSION['current_teledrama_id'] = $id;
}

// Fetch total items to calculate total pages
$total_url = "https://www.googleapis.com/youtube/v3/playlists?part=contentDetails&id=$playlist_id&key=$api_key";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $total_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$total_response = curl_exec($ch);

if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    curl_close($ch);
    die("cURL Error (Total Items): $error_msg");
}
curl_close($ch);

$total_data = json_decode($total_response, true);
$total_items = $total_data['items'][0]['contentDetails']['itemCount'] ?? 0;
$total_pages = ceil($total_items / $items_per_page);

// Function to fetch page tokens up to the desired page
function fetchPageTokens($playlist_id, $api_key, $items_per_page, $target_page, &$page_tokens) {
    $current_page = 1;
    $next_page_token = '';
    $page_tokens[1] = ''; // Page 1 has no pageToken

    while ($current_page < $target_page && $next_page_token !== null) {
        $url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=$items_per_page&playlistId=$playlist_id&key=$api_key";
        if ($next_page_token) {
            $url .= "&pageToken=$next_page_token";
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            curl_close($ch);
            return false; // Handle error in main logic
        }
        curl_close($ch);

        $data = json_decode($response, true);
        if (isset($data['error'])) {
            return false; // Handle error in main logic
        }

        $next_page_token = $data['nextPageToken'] ?? null;
        $current_page++;
        if ($next_page_token && $current_page <= $target_page) {
            $page_tokens[$current_page] = $next_page_token;
        }
    }
    return true;
}

// Fetch page tokens if not already stored
if (!isset($_SESSION['page_tokens'][$page]) && $page > 1) {
    if (!fetchPageTokens($playlist_id, $api_key, $items_per_page, $page, $_SESSION['page_tokens'])) {
        echo "YouTube API Error: Unable to fetch page tokens.";
        $episodes = [];
        $next_page_token = '';
        $prev_page_token = '';
    }
}

// Use the page token for the current page
$page_token = $_SESSION['page_tokens'][$page] ?? '';

// Fetch episodes for the current page
$max_results = $items_per_page;
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=$max_results&playlistId=$playlist_id&key=$api_key";
if ($page_token) {
    $url .= "&pageToken=$page_token";
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    $error_msg = curl_error($ch);
    curl_close($ch);
    die("cURL Error: $error_msg");
}
curl_close($ch);

// Parse the response
$playlist_data = json_decode($response, true);
if (isset($playlist_data['error'])) {
    echo "YouTube API Error: " . htmlspecialchars($playlist_data['error']['message']) . "<br>";
    $episodes = [];
    $next_page_token = '';
    $prev_page_token = '';
} else {
    $episodes = $playlist_data['items'] ?? [];
    $next_page_token = $playlist_data['nextPageToken'] ?? '';
    $prev_page_token = $playlist_data['prevPageToken'] ?? '';
    // Store tokens for next and previous pages
    if ($next_page_token && !isset($_SESSION['page_tokens'][$page + 1])) {
        $_SESSION['page_tokens'][$page + 1] = $next_page_token;
    }
    if ($prev_page_token && !isset($_SESSION['page_tokens'][$page - 1])) {
        $_SESSION['page_tokens'][$page - 1] = $prev_page_token;
    }
}

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

<style>
    body {
        margin: 0;
        padding: 0;
        min-height: 100vh;
        position: relative;
    }

    .main-content {
        padding-bottom: 150px; /* footer spacing */
        width: 100%;
        padding-top: 110px; /* desktop header height */
    }

    .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%; /* 16:9 aspect ratio */
        height: 0;
        overflow: hidden;
    }

    .video-container iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .sort-container {
        margin-bottom: 20px;
    }

    /* Pagination styles from the previous page, enhanced for responsiveness */
    .pagination {
        margin-top: 2rem;
        display: flex;
        justify-content: center;
        gap: 0.5rem; /* Space between items */
        flex-wrap: wrap; /* Allow buttons to wrap on small screens */
    }

    .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; /* Fully rounded corners */
        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; /* Default font size */
    }

    .pagination .page-item.active .page-link {
        background-color: #FFC107;
        color: #1A237E;
        border-color: #FFC107;
        transform: scale(1.1); /* Slight scale on active */
    }

    .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); /* Slight scale on hover */
    }

    /* Enhanced responsive adjustments */
    @media (max-width: 991px) {
        .main-content {
            padding-top: 0px; /* Small spacing below mobile header */
        }

        .pagination {
            gap: 0.4rem; /* Slightly smaller gap */
        }

        .pagination .page-link {
            padding: 6px 12px;
            min-width: 36px; /* Slightly smaller buttons */
            font-size: 14px; /* Smaller font size */
        }
    }

    @media (max-width: 576px) {
        .pagination {
            gap: 0.3rem; /* Even smaller gap */
            padding: 0 10px; /* Prevent overflow */
        }

        .pagination .page-link {
            padding: 5px 10px;
            min-width: 32px; /* Smaller buttons for mobile */
            font-size: 12px; /* Smaller font size for mobile */
            line-height: 1.5; /* Ensure readability */
        }

        .pagination .page-item {
            margin: 2px 0; /* Add vertical spacing if wrapping occurs */
        }
    }

    @media (max-width: 400px) {
        .pagination {
            gap: 0.2rem; /* Minimal gap for very small screens */
        }

        .pagination .page-link {
            padding: 4px 8px;
            min-width: 28px; /* Minimal button size */
            font-size: 11px; /* Minimal font size */
        }
    }
</style>

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

        <h3 style="color: #FFC107;">Episodes</h3>
       
        <div class="row row-cols-1 row-cols-md-3 g-4" id="episodeList">
            <?php foreach ($episodes as $episode) { ?>
                <?php
                $video_id = $episode['snippet']['resourceId']['videoId'];
                $title = $episode['snippet']['title'];
                $thumbnail = $episode['snippet']['thumbnails']['medium']['url'] ?? 'default.jpg';
                $published_at = $episode['snippet']['publishedAt'];
                ?>
                <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 } ?>
            <?php if (empty($episodes)) { ?> 
                <div class="col">
                    <p>No episodes found for this playlist.</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; ?><?php echo isset($_SESSION['page_tokens'][$page - 1]) ? '&pageToken=' . urlencode($_SESSION['page_tokens'][$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 isset($_SESSION['page_tokens'][$i]) ? '&pageToken=' . urlencode($_SESSION['page_tokens'][$i]) : ''; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo !$next_page_token || $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?id=<?php echo $id; ?>&page=<?php echo $page + 1; ?><?php echo $next_page_token ? '&pageToken=' . urlencode($next_page_token) : ''; ?>" 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'));

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

    // Sorting functionality
    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;
        });

        // Clear and re-append sorted items
        episodeList.innerHTML = '';
        sortedItems.forEach(item => episodeList.appendChild(item));
        
        // If no episodes, re-append the "No episodes" message
        if (episodeItems.length === 0) {
            const noEpisodes = document.createElement('div');
            noEpisodes.className = 'col';
            noEpisodes.innerHTML = '<p>No episodes found for this playlist.</p>';
            episodeList.appendChild(noEpisodes);
        }
    });
});
</script>

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