<?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;
$teledrama = null;

// 2. FETCH TELEDRAMA DETAILS
if (!empty($slug)) {
    // Fetch by Slug
    $stmt = $conn->prepare("SELECT * FROM teledramas WHERE slug = :slug");
    $stmt->bindParam(':slug', $slug);
    $stmt->execute();
    $teledrama = $stmt->fetch(PDO::FETCH_ASSOC);
} elseif ($id > 0) {
    // Fetch by ID (Fallback)
    $stmt = $conn->prepare("SELECT * FROM teledramas WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    $teledrama = $stmt->fetch(PDO::FETCH_ASSOC);
}

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

// IMPORTANT: Ensure $id is set to the real numeric ID for episode queries
$id = $teledrama['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;

$episodes_stmt = $conn->prepare("SELECT * FROM teledrama_videos WHERE teledrama_id = :id ORDER BY published_at DESC LIMIT :offset, :limit");
$episodes_stmt->bindParam(':id', $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 teledrama_videos WHERE teledrama_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);

// 4. PREPARE PAGINATION URL BASE
// If using slug, link format: teledramas/slug?page=X
// If using ID, link format: ?id=X&page=X
$paginationBase = !empty($slug) 
    ? "teledramas/" . htmlspecialchars($slug) . "?" 
    : "?id=" . $id . "&";

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

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

<style>
/* Your existing CSS exactly as provided */
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 {
    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;
    }
}

@media (max-width: 400px) {
    .pagination {
        gap: 0.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($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 if (!empty($episodes)) {
                foreach ($episodes as $episode) {
                    ?>
                    <div class="col episode-item" data-published-at="<?php echo htmlspecialchars($episode['published_at']); ?>">
                        <div class="card mb-4">
                            <img src="<?php echo htmlspecialchars($episode['thumbnail']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($episode['title']); ?>" style="width:100%; height:auto; object-fit:contain;">
                            <div class="card-body">
                                <h6 class="card-title"><?php echo htmlspecialchars($episode['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($episode['video_id']); ?>" data-title="<?php echo htmlspecialchars($episode['title']); ?>">
                                    Watch
                                </button>
                            </div>
                        </div>
                    </div>
                <?php }
            } else { ?>
                <div class="col">
                    <p>No episodes found for this teledrama.</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');
    // Removed sorting logic here as it wasn't in your main logic block for the live file provided,
    // but ensured modal logic remains.

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

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