<?php
require_once('db.php'); // Include the database connection

header('Content-Type: application/json');

$response = [];

// --- Check if topic_id is provided ---
if (isset($_GET['topic_id']) && !empty($_GET['topic_id'])) {
    // --- Fetch Lessons for a specific Topic ID ---
    $topicId = $_GET['topic_id'];

    $stmt = $conn->prepare("SELECT lesson_id, lesson_name FROM lessons WHERE topic_id = ? ORDER BY lesson_name");
    if ($stmt === false) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to prepare statement for lessons: ' . $conn->error]);
        $conn->close();
        exit();
    }

    $stmt->bind_param("s", $topicId); // "s" for string, use "i" if topic_id is an integer in your DB

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $response[] = $row;
        }
        $stmt->close();
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to execute statement for lessons: ' . $stmt->error]);
        $conn->close();
        exit();
    }

} else {
    // --- Fetch All Topics ---
    $stmt = $conn->prepare("SELECT topic_id, topic_name FROM topics ORDER BY topic_name");
    if ($stmt === false) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to prepare statement for topics: ' . $conn->error]);
        $conn->close();
        exit();
    }

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $response[] = $row;
        }
        $stmt->close();
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to execute statement for topics: ' . $stmt->error]);
        $conn->close();
        exit();
    }
}

// --- Close Connection and Output JSON ---
$conn->close();
echo json_encode($response);

?> 