<?php
require("../includes/config.php");
header("Content-Type: application/json");

$page   = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit  = 5;
$offset = ($page - 1) * $limit;
$search = $_GET['search'] ?? '';

// COUNT
$stmt = $pdo->prepare("
    SELECT COUNT(*) FROM lessons l
    JOIN chapters c ON l.chapter_id = c.id
    WHERE l.lesson_title LIKE ?
");
$stmt->execute(["%$search%"]);
$total = $stmt->fetchColumn();
$total_pages = ceil($total / $limit);

// DATA
$stmt = $pdo->prepare("
    SELECT l.id ,l.lesson_title, c.chapter_name, l.status
    FROM lessons l
    JOIN chapters c ON l.chapter_id = c.id
    WHERE l.lesson_title LIKE ?
    ORDER BY l.id DESC
    LIMIT $limit OFFSET $offset
");
$stmt->execute(["%$search%"]);

echo json_encode([
    "lessons" => $stmt->fetchAll(PDO::FETCH_ASSOC),
    "total_pages" => $total_pages
]);
?>