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

$id = $_GET['id'] ?? 0;

// Check if ID is valid
if (!$id) {
    echo json_encode(["status" => "error", "message" => "Invalid lesson ID"]);
    exit;
}

// Fetch the lesson data
$stmt = $pdo->prepare("SELECT * FROM lessons WHERE id = ?");
$stmt->execute([$id]);
$lesson = $stmt->fetch(PDO::FETCH_ASSOC);

// If lesson is not found
if (!$lesson) {
    echo json_encode(["status" => "error", "message" => "Lesson not found"]);
    exit;
}

// Fetch all chapters for the chapter select
$stmtChapters = $pdo->prepare("SELECT id, chapter_name FROM chapters");
$stmtChapters->execute();
$chapters = $stmtChapters->fetchAll(PDO::FETCH_ASSOC);

// Fetch the image path (if it exists)
$imagePath = $lesson['featured_image'] ? "../uploads/lessons/" . $lesson['featured_image'] : null;

echo json_encode([
    "status" => "success",
    "lesson" => $lesson,
    "imagePath" => $imagePath,
    "chapters" => $chapters
]);
?>
