<?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;
$courseId = $_POST['course_id'] ?? 0;

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

// Check if user can access this course
$stmt = $db->prepare("SELECT id FROM courses WHERE id = ? AND instructor_id = ?");
$stmt->execute([$courseId, $userId]);
$course = $stmt->fetch();

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $updates = json_decode(file_get_contents('php://input'), true);

    if (!$updates || !isset($updates['updates'])) {
        echo json_encode(['success' => false, 'error' => 'Invalid input']);
        exit;
    }

    try {
        $db->beginTransaction();

        foreach ($updates['updates'] as $update) {
            $table = '';
            $idField = 'id';

            switch ($update['type']) {
                case 'module':
                    $table = 'course_modules';
                    // Verify module belongs to course
                    $stmt = $db->prepare("SELECT id FROM course_modules WHERE id = ? AND course_id = ?");
                    $stmt->execute([$update['id'], $courseId]);
                    if (!$stmt->fetch()) continue 2;
                    break;
                case 'topic':
                    $table = 'course_topics';
                    // Verify topic belongs to user's course
                    $stmt = $db->prepare("
                        SELECT ct.id FROM course_topics ct
                        JOIN course_modules cm ON ct.module_id = cm.id
                        WHERE ct.id = ? AND cm.course_id = ?
                    ");
                    $stmt->execute([$update['id'], $courseId]);
                    if (!$stmt->fetch()) continue 2;
                    break;
                case 'lesson':
                    $table = 'course_lessons';
                    // Verify lesson belongs to user's course
                    $stmt = $db->prepare("SELECT id FROM course_lessons WHERE id = ? AND course_id = ?");
                    $stmt->execute([$update['id'], $courseId]);
                    if (!$stmt->fetch()) continue 2;
                    break;
                default:
                    continue 2; // Skip invalid types
            }

            $stmt = $db->prepare("UPDATE $table SET description = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$update['description'], $update['id']]);
        }

        $db->commit();
        echo json_encode(['success' => true, 'message' => 'Descriptions updated successfully']);

    } catch (PDOException $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
}
?>