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

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

try {
    $db = getDB();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Database connection failed: ' . $e->getMessage()]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if ($data === null) {
        echo json_encode(['success' => false, 'error' => 'Invalid JSON data']);
        exit;
    }
    $lessonId = $data['lesson_id'];
    $enrollmentId = $data['enrollment_id'];
    $action = $data['action'] ?? 'start';
    $userId = $_SESSION['user_id'];

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

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

    // Verify enrollment belongs to user
    $stmt = $db->prepare("
        SELECT ce.id, ce.status
        FROM course_enrollments ce
        WHERE ce.id = ? AND ce.student_id = ? AND ce.status IN ('enrolled', 'in_progress', 'completed')
    ");
    $stmt->execute([$enrollmentId, $userId]);
    $enrollment = $stmt->fetch();

    if (!$enrollment) {
        echo json_encode(['success' => false, 'error' => 'Invalid enrollment']);
        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([$enrollmentId, $lessonId]);
                break;

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

                // Recalculate progress percentage
                $stmt = $db->prepare("
                    SELECT COUNT(*) as total_lessons,
                           SUM(CASE WHEN clp.status = 'completed' THEN 1 ELSE 0 END) as completed_lessons
                    FROM course_lessons cl
                    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
                    WHERE cl.course_id = (SELECT course_id FROM course_enrollments WHERE id = ?)
                ");
                $stmt->execute([$enrollmentId, $enrollmentId]);
                $progress = $stmt->fetch();
                $progressPercentage = $progress['total_lessons'] > 0 ? round(($progress['completed_lessons'] / $progress['total_lessons']) * 100) : 0;

                // Update enrollment progress and status
                $newStatus = $progressPercentage >= 100 ? 'completed' : 'in_progress';
                $stmt = $db->prepare("UPDATE course_enrollments SET status = ?, progress_percentage = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$newStatus, $progressPercentage, $enrollmentId]);
                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([$enrollmentId, $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, $enrollmentId, $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']);
}
?>