<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../includes/functions.php';

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

$db = getDB();
$userId = $_SESSION['user_id'] ?? 0;
$topicId = $_GET['topic_id'] ?? 0;

if (!$topicId || !$userId) {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

// Check if user can access this topic (through course)
$stmt = $db->prepare("
    SELECT ct.id FROM course_topics ct
    JOIN course_modules cm ON ct.module_id = cm.id
    JOIN courses c ON cm.course_id = c.id
    WHERE ct.id = ? AND c.instructor_id = ?
");
$stmt->execute([$topicId, $userId]);
$topic = $stmt->fetch();

if (!$topic) {
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        // Get lessons for a topic
        try {
            $stmt = $db->prepare("
                SELECT * FROM course_lessons
                WHERE topic_id = ?
                ORDER BY sort_order ASC
            ");
            $stmt->execute([$topicId]);
            $lessons = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode([
                'success' => true,
                'lessons' => $lessons
            ]);

        } catch (PDOException $e) {
            echo json_encode([
                'success' => false,
                'error' => 'Database error: ' . $e->getMessage()
            ]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}
?>