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

// 1. Initialize variables to prevent "Undefined Variable" notices
$teledramas = [];
$total_items = 0;
$total_pages = 0;

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

$items_per_page = 8; // Shows exactly 2 rows of 4 cards on desktop
$offset = ($page - 1) * $items_per_page;

try {
    if ($conn instanceof PDO) {
        $total_stmt = $conn->query("SELECT COUNT(*) FROM teledramas");
        $total_items = $total_stmt->fetchColumn();

        $stmt = $conn->prepare("SELECT * FROM teledramas 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();
        $teledramas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } elseif ($conn instanceof mysqli) {
        $result = $conn->query("SELECT COUNT(*) as total FROM teledramas");
        $row = $result->fetch_assoc();
        $total_items = $row['total'] ?? 0;

        $stmt = $conn->prepare("SELECT * FROM teledramas 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()) {
            $teledramas[] = $row;
        }
    }
    $total_pages = ceil($total_items / $items_per_page);
} catch (Exception $e) {
    error_log($e->getMessage());
}
?>

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

    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Poppins', sans-serif;
            background: rgb(25, 52, 134);
            padding: 90px 0 0;
            overflow-x: hidden;
        }

        /* --- 100% FROZEN OUTER BOX (OVERRIDES BOOTSTRAP) --- */
        .container.ts {
            width: 1260px !important; /* Strictly locks the box size */
            max-width: 1260px !important; /* Stops Bootstrap from expanding it on 4K/wide screens */
            margin: 40px auto !important; /* Centers the frozen box horizontally */
            padding: 30px;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            color: white;
            position: relative;
        }

        .page-title {
            text-align: center;
            margin-bottom: 40px;
            font-size: 2.5rem;
            color: white;
        }

        /* --- 4 CARDS IN 1 ROW (FIXED SIZE) --- */
        .teledrama-grid {
            display: grid;
            grid-template-columns: repeat(4, 280px); /* Exactly 4 columns, each 280px wide */
            justify-content: center; /* Centers the 4 cards inside the box */
            gap: 20px;
            width: 100%;
        }

        .card {
            width: 280px; /* Locks card width so it never resizes */
            background: rgba(255, 255, 255, 0.08);
            backdrop-filter: blur(20px) saturate(180%);
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.15);
            overflow: hidden;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            height: 100%; 
        }

        .card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4);
        }

        /* --- IMAGE SETTINGS --- */
        .card-img-top {
            width: 280px;
            height: 158px; /* Exact 16:9 ratio for 280px width */
            object-fit: contain;
            background: #0b1736;
        }

        .card-body {
            padding: 20px;
            flex-grow: 1; 
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .card-text {
            font-size: 14px;
            color: #ecf0f1;
            margin-bottom: 20px;
        }

        .btn-watch {
            text-align: center;
            background-color: #FFC107;
            color: #1A237E;
            padding: 12px;
            border-radius: 12px;
            font-weight: bold;
            text-decoration: none;
            transition: 0.3s;
        }

        .btn-watch:hover {
            background-color: #fff;
        }

        /* --- TABLET & MOBILE FALLBACKS ONLY --- */
        /* Only shrinks if the screen physically cannot fit the 1260px box (tablets/phones) */
        @media (max-width: 1280px) {
            .container.ts { 
                width: 95% !important; 
                max-width: 95% !important; 
            }
            .teledrama-grid { 
                grid-template-columns: repeat(2, 280px); 
            }
        }

        @media (max-width: 640px) {
            .container.ts { 
                padding: 15px; 
                width: 98% !important; 
            }
            .teledrama-grid { 
                grid-template-columns: minmax(250px, 280px); 
            }
            .card, .card-img-top {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container ts">
        <a href="pages/teledramas.php" class="top-right-btn">More</a>
        <div class="teledrama-container">
            <h1 class="page-title">Teledramas</h1>
            
            <div class="teledrama-grid">
                <?php if (!empty($teledramas)): ?>
                    <?php foreach ($teledramas as $row): ?>
                        <?php
                            $link = !empty($row['slug']) ? "teledramas/" . $row['slug'] : "teledrama_detail.php?id=" . $row['id'];
                        ?>
                        <div class="card">
                            <img src="<?php echo htmlspecialchars($row['thumbnail']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($row['title']); ?>">
                            <div class="card-body">
                                <a href="<?php echo htmlspecialchars($link); ?>" class="btn-watch">
                                    <?php echo htmlspecialchars($row['title']); ?>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>