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

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

// 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;
}

$topicId = $_GET['topic_id'] ?? 0;

$method = $_SERVER['REQUEST_METHOD'];

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

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

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

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

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

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

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

        $topicId = $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 ($topicId) {
                // Update existing topic
                $stmt = $db->prepare("UPDATE course_topics SET title = ?, description = ?, sort_order = ?, estimated_time = ?, updated_at = NOW() WHERE id = ? AND module_id = ?");
                $stmt->execute([$title, $description, $sortOrder, $estimatedTime, $topicId, $moduleId]);

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

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

                $newTopicId = $db->lastInsertId();

                echo json_encode([
                    'success' => true,
                    'message' => 'Topic created successfully',
                    'topic_id' => $newTopicId
                ]);
            }

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

    case 'DELETE':
        // Delete topic
        if (!$topicId) {
            echo json_encode(['success' => false, 'error' => 'Topic ID required']);
            exit;
        }

        try {
            // Check if 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
                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' => 'Topic not found or access denied']);
                exit;
            }

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

            echo json_encode([
                'success' => true,
                'message' => 'Topic 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_topics SET sort_order = ?, updated_at = NOW() WHERE id = ? AND module_id = ?");
                $stmt->execute([$update['sort_order'], $update['id'], $moduleId]);
            }

            $db->commit();

            echo json_encode([
                'success' => true,
                'message' => 'Topic 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;
}
?>