<?php
// C:\xampp\htdocs\swarnawahini_web\components\programme_list.php

include __DIR__ . '/db_connect.php';
include_once __DIR__ . '/functions.php';

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
    $page = 1; 
}

$items_per_page = 6;
$offset = ($page - 1) * $items_per_page;
$total_items = 0;
$programmes = [];

// 1. DUAL DB SUPPORT (PDO & MySQLi)
if (isset($conn) && $conn instanceof PDO) {
    $total_stmt = $conn->query("SELECT COUNT(*) FROM programmes");
    $total_items = $total_stmt->fetchColumn();

    $stmt = $conn->prepare("SELECT * FROM programmes ORDER BY sort_order ASC LIMIT :limit OFFSET :offset");
    $stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $programmes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} elseif (isset($conn) && $conn instanceof mysqli) {
    $result = $conn->query("SELECT COUNT(*) as total FROM programmes");
    $row = $result->fetch_assoc();
    $total_items = $row['total'] ?? 0;

    $stmt = $conn->prepare("SELECT * FROM programmes ORDER BY sort_order ASC LIMIT ? OFFSET ?");
    $stmt->bind_param("ii", $items_per_page, $offset);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $programmes[] = $row;
    }
}

$total_pages = ceil($total_items / $items_per_page);

// 2. EPISODE COUNTS
$counts = [];
$ids = array_column($programmes, 'id');

if (!empty($ids)) {
    if (isset($conn) && $conn instanceof PDO) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $conn->prepare("SELECT programmes_id, COUNT(*) AS cnt FROM programmes_videos WHERE programmes_id IN ($placeholders) GROUP BY programmes_id");
        $stmt->execute($ids);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as $r) $counts[$r['programmes_id']] = (int)$r['cnt'];

    } elseif (isset($conn) && $conn instanceof mysqli) {
        $safeIds = array_map('intval', $ids);
        $in = implode(',', $safeIds);
        $res = $conn->query("SELECT programmes_id, COUNT(*) AS cnt FROM programmes_videos WHERE programmes_id IN ($in) GROUP BY programmes_id");
        if ($res) {
            while ($r = $res->fetch_assoc()) $counts[$r['programmes_id']] = (int)$r['cnt'];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Programmes | Swarnawahini</title>
    
    <base href="https://www.swarnavahini.lk/">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* Global Reset */
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: Poppins, sans-serif;
            background: rgb(25, 52, 134);
            margin: 0;
            padding: 90px 0 0;
            overflow-x: hidden;
        }

        /* Container */
        .container.ts {
            max-width: 1200px;
            margin: 40px auto;
            padding: 20px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            color: white;
            position: relative; 
        }

        /* Top Right Button */
        .top-right-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            background-color: #FFC107;
            color: #1A237E;
            padding: 8px 15px;
            border-radius: 15px;
            font-family: 'Poppins', sans-serif;
            font-weight: bold;
            text-decoration: none;
            transition: background-color 0.3s ease, transform 0.3s ease;
            border: none;
            cursor: pointer;
        }
        .top-right-btn:hover {
            background-color: #ff0000;
            color: #1A237E;
            transform: scale(1.05);
        }

        /* Page Title */
        .page-title {
            text-align: center;
            margin-bottom: 30px;
            font-size: 2rem;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
            color: white;
        }

        /* Grid Layout */
        .row {
            display: grid;
            grid-template-columns: repeat(3, 1fr); 
            gap: 1.5rem; 
            justify-content: center;
            padding: 0 0.75rem; 
        }

        .col { display: flex; justify-content: center; }

        /* Cards */
        .card {
            background: rgba(255, 255, 255, 0.08); 
            backdrop-filter: blur(20px) saturate(200%);
            -webkit-backdrop-filter: blur(20px) saturate(200%);
            border-radius: 20px; 
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3); 
            border: 1px solid rgba(255, 255, 255, 0.15); 
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease, background 0.3s ease;
            width: 100%;
            max-width: 350px;
            background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.02) 100%); 
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 25px rgba(0, 0, 0, 0.4);
            background: rgba(255, 255, 255, 0.12);
            background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.18) 0%, rgba(255, 255, 255, 0.03) 100%);
        }

        .card-img-top {
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;
            width: 100%;
            height: 200px;
            object-fit: cover;
        }

        .card-body { padding: 15px; color: white; }

        .card-text {
            font-family: 'Poppins', sans-serif;
            font-weight: 400;
            font-size: 16px;
            color: #ecf0f1;
            margin-bottom: 15px;
        }

        .btn.btn-primary {
            display: inline-flex;
            align-items: center;
            background-color: #FFC107;
            color: #1A237E;
            padding: 8px 15px;
            border-radius: 15px;
            font-family: 'Poppins', sans-serif;
            font-weight: bold;
            text-decoration: none;
            transition: background-color 0.3s ease, transform 0.3s ease;
            border: none;
        }
        .btn.btn-primary:hover {
            background-color: #ff0000;
            color: #1A237E;
            transform: scale(1.05);
            text-decoration: none;
        }

        /* Pagination */
        .pagination { margin-top: 2rem; display: flex; justify-content: center; gap: 0.5rem; }
        .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;
        }
        .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) {
            .container.ts { border-radius: 10px; }
            .page-title { font-size: 1.5rem; }
            .row { grid-template-columns: repeat(2, 1fr); }
            .card { border-radius: 10px; max-width: 350px; }
            .card-img-top { height: 150px; }
            .top-right-btn { padding: 6px 12px; font-size: 14px; }
        }
        @media (max-width: 576px) {
            .container.ts { border-radius: 8px; }
            .page-title { font-size: 1.25rem; }
            .row { grid-template-columns: 1fr; }
            .card { border-radius: 20px; max-width: 100%; }
            .card-img-top { height: 120px; }
            .card-body { padding: 10px; }
            .card-text { font-size: 14px; }
            .btn.btn-primary { padding: 6px 12px; font-size: 14px; }
            .top-right-btn { padding: 5px 10px; font-size: 12px; top: 10px; right: 10px; }
        }
    </style>
</head>
<body>
    <div class="container ts">
        <a href="programmes.php" class="top-right-btn">More</a>
        <div class="teledrama-container">
            <h1 class="page-title">Programmes</h1>
            <div class="row g-4 justify-content-center">
                <?php foreach ($programmes as $row): ?>
                    <?php
                        // --- DIRECT DB VALUE (Exact same as Teledramas) ---
                        // We do NOT add any folder path manually.
                        // We trust the DB column 'cover_image' has the correct path.
                        $thumbnail = !empty($row['cover_image']) 
                            ? $row['cover_image'] 
                            : 'assets/images/default-placeholder.jpg';

                        // --- SLUG URL FEATURE ---
                        $link = !empty($row['slug']) 
                            ? "programmes/" . $row['slug'] 
                            : "programme_detail.php?id=" . $row['id'];
                    ?>
                    <div class="col">
                        <div class="card">
                            <img src="<?php echo htmlspecialchars($thumbnail); ?>"
                                 class="card-img-top"
                                 alt="<?php echo htmlspecialchars($row['title']); ?>"
                                 style="width:100%; height:auto; object-fit:contain;">

                            <div class="card-body">
                                <p class="card-text"><?php echo htmlspecialchars($row['description']); ?></p>
                                <a href="<?php echo htmlspecialchars($link); ?>" class="btn btn-primary">
                                    <?php echo htmlspecialchars($row['title']); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>