<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';

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

$db = getDB();

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $lessonId = $data['lesson_id'];
    $action = $data['action'] ?? 'start';
    $userId = $_SESSION['user_id'];

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

    // Get enrollment for this lesson's course
    $stmt = $db->prepare("
        SELECT ce.id, ce.status, cl.course_id
        FROM course_enrollments ce
        JOIN course_lessons cl ON cl.course_id = ce.course_id
        WHERE ce.student_id = ? AND cl.id = ? AND ce.status IN ('enrolled', 'in_progress', 'completed')
    ");
    $stmt->execute([$userId, $lessonId]);
    $enrollment = $stmt->fetch();

    if (!$enrollment) {
        echo json_encode(['success' => false, 'error' => 'Not enrolled in this course']);
        exit;
    }

    try {
        switch ($action) {
            case 'start':
                // Mark lesson as in progress
                $stmt = $db->prepare("
                    INSERT INTO course_lesson_progress (enrollment_id, lesson_id, status, last_accessed)
                    VALUES (?, ?, 'in_progress', NOW())
                    ON DUPLICATE KEY UPDATE status = 'in_progress', last_accessed = NOW()
                ");
                $stmt->execute([$enrollment['id'], $lessonId]);
                break;

            case 'complete':
                // Mark lesson as completed
                $stmt = $db->prepare("
                    INSERT INTO course_lesson_progress (enrollment_id, lesson_id, status, progress_percentage, completed_at, last_accessed)
                    VALUES (?, ?, 'completed', 100, NOW(), NOW())
                    ON DUPLICATE KEY UPDATE status = 'completed', progress_percentage = 100, completed_at = NOW(), last_accessed = NOW()
                ");
                $stmt->execute([$enrollment['id'], $lessonId]);

                // Update enrollment status if not already completed
                if ($enrollment['status'] !== 'completed') {
                    $stmt = $db->prepare("UPDATE course_enrollments SET status = 'in_progress', updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$enrollment['id']]);
                }
                break;

            case 'track_time':
                $timeSpent = intval($data['time_spent'] ?? 0);
                if ($timeSpent > 0) {
                    $stmt = $db->prepare("
                        INSERT INTO course_lesson_progress (enrollment_id, lesson_id, time_spent, last_accessed)
                        VALUES (?, ?, ?, NOW())
                        ON DUPLICATE KEY UPDATE time_spent = time_spent + VALUES(time_spent), last_accessed = NOW()
                    ");
                    $stmt->execute([$enrollment['id'], $lessonId, $timeSpent]);
                }
                break;

            case 'add_note':
                $note = trim($data['note'] ?? '');
                if (!empty($note)) {
                    $stmt = $db->prepare("
                        UPDATE course_lesson_progress
                        SET notes = CONCAT(IFNULL(CONCAT(notes, '\n\n'), ''), NOW(), ': ', ?)
                        WHERE enrollment_id = ? AND lesson_id = ?
                    ");
                    $stmt->execute([$note, $enrollment['id'], $lessonId]);
                }
                break;

            default:
                echo json_encode(['success' => false, 'error' => 'Invalid action']);
                exit;
        }

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

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

} elseif ($method === 'GET') {
    $lessonId = $_GET['lesson_id'];
    $userId = $_SESSION['user_id'];

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

    // Get lesson progress
    $stmt = $db->prepare("
        SELECT clp.*, ce.student_id
        FROM course_lesson_progress clp
        JOIN course_enrollments ce ON clp.enrollment_id = ce.id
        WHERE clp.lesson_id = ? AND ce.student_id = ?
    ");
    $stmt->execute([$lessonId, $userId]);
    $progress = $stmt->fetch();

    if ($progress) {
        echo json_encode(['success' => true, 'progress' => $progress]);
    } else {
        echo json_encode(['success' => true, 'progress' => null]);
    }

} else {
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
}
?>