<?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 = $_GET['course_id'] ?? 0;
$moduleId = $_GET['module_id'] ?? 0;

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

// Check access based on course or module
if ($moduleId) {
    // Check if user can access this module (through course)
    $stmt = $db->prepare("
        SELECT cm.id FROM course_modules cm
        JOIN courses c ON cm.course_id = c.id
        WHERE cm.id = ? AND c.instructor_id = ?
    ");
    $stmt->execute([$moduleId, $userId]);
    $module = $stmt->fetch();

    if (!$module) {
        echo json_encode(['success' => false, 'error' => 'Access denied']);
        exit;
    }
} elseif ($courseId) {
    // 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;
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Course ID or Module ID required']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if ($moduleId) {
            // Get single module
            try {
                $stmt = $db->prepare("
                    SELECT cm.*,
                           COUNT(cl.id) as lesson_count,
                           SUM(cl.estimated_time) as total_estimated_time
                    FROM course_modules cm
                    LEFT JOIN course_lessons cl ON cm.id = cl.module_id
                    WHERE cm.id = ?
                    GROUP BY cm.id
                ");
                $stmt->execute([$moduleId]);
                $module = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($module) {
                    echo json_encode([
                        'success' => true,
                        'module' => $module
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'error' => 'Module not found'
                    ]);
                }

            } catch (PDOException $e) {
                echo json_encode([
                    'success' => false,
                    'error' => 'Database error: ' . $e->getMessage()
                ]);
            }
        } else {
            // Get modules for a course
            try {
                $stmt = $db->prepare("
                    SELECT cm.*,
                           COUNT(cl.id) as lesson_count,
                           SUM(cl.estimated_time) as total_estimated_time
                    FROM course_modules cm
                    LEFT JOIN course_lessons cl ON cm.id = cl.module_id
                    WHERE cm.course_id = ?
                    GROUP BY cm.id
                    ORDER BY cm.sort_order ASC
                ");
                $stmt->execute([$courseId]);
                $modules = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

    case 'POST':
        // Create or update module
        $input = json_decode(file_get_contents('php://input'), true);

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

        $moduleId = $input['id'] ?? null;
        $title = trim($input['title'] ?? '');
        $description = trim($input['description'] ?? '');
        $sortOrder = intval($input['sort_order'] ?? 1);
        $estimatedTime = intval($input['estimated_time'] ?? 0);

        if (empty($title)) {
            echo json_encode(['success' => false, 'error' => 'Title is required']);
            exit;
        }

        try {
            if ($moduleId) {
                // Update existing module
                $stmt = $db->prepare("UPDATE course_modules SET title = ?, description = ?, sort_order = ?, estimated_time = ?, updated_at = NOW() WHERE id = ? AND course_id = ?");
                $stmt->execute([$title, $description, $sortOrder, $estimatedTime, $moduleId, $courseId]);

                echo json_encode([
                    'success' => true,
                    'message' => 'Module updated successfully',
                    'module_id' => $moduleId
                ]);
            } else {
                // Create new module
                $baseSlug = createSlug($title);
                $slug = $courseId . '-' . $baseSlug;
                $originalSlug = $slug;
                $counter = 1;
                while (true) {
                    $stmt = $db->prepare("SELECT id FROM course_modules WHERE slug = ?");
                    $stmt->execute([$slug]);
                    if (!$stmt->fetch()) break;
                    $slug = $originalSlug . '-' . $counter;
                    $counter++;
                }

                $stmt = $db->prepare("INSERT INTO course_modules (course_id, title, slug, description, sort_order, estimated_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
                $stmt->execute([$courseId, $title, $slug, $description, $sortOrder, $estimatedTime]);

                $newModuleId = $db->lastInsertId();

                echo json_encode([
                    'success' => true,
                    'message' => 'Module created successfully',
                    'module_id' => $newModuleId
                ]);
            }

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

    case 'DELETE':
        // Delete module
        $moduleId = $_GET['module_id'] ?? 0;

        if (!$moduleId) {
            echo json_encode(['success' => false, 'error' => 'Module ID required']);
            exit;
        }

        try {
            // Check if module belongs to course
            $stmt = $db->prepare("SELECT id FROM course_modules WHERE id = ? AND course_id = ?");
            $stmt->execute([$moduleId, $courseId]);
            $module = $stmt->fetch();

            if (!$module) {
                echo json_encode(['success' => false, 'error' => 'Module not found']);
                exit;
            }

            // Delete module (lessons will be set to NULL for module_id due to foreign key constraint)
            $stmt = $db->prepare("DELETE FROM course_modules WHERE id = ?");
            $stmt->execute([$moduleId]);

            echo json_encode([
                'success' => true,
                'message' => 'Module deleted successfully'
            ]);

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

    case 'PATCH':
        // Batch update sort orders
        $input = json_decode(file_get_contents('php://input'), true);

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

        try {
            $db->beginTransaction();

            foreach ($input['updates'] as $update) {
                $stmt = $db->prepare("UPDATE course_modules SET sort_order = ?, updated_at = NOW() WHERE id = ? AND course_id = ?");
                $stmt->execute([$update['sort_order'], $update['id'], $courseId]);
            }

            $db->commit();

            echo json_encode([
                'success' => true,
                'message' => 'Module order updated successfully'
            ]);

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

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