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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

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

try {
    authMiddleware();
} catch (Exception $e) {
    error_log(date('Y-m-d H:i:s') . " - Auth middleware error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Authentication failed']);
    exit;
}

try {
    $db = getDB();
} catch (Exception $e) {
    $error = 'Database connection failed: ' . $e->getMessage();
    error_log(date('Y-m-d H:i:s') . " - DB Error: " . $error);
    echo json_encode(['success' => false, 'error' => $error]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if ($data === null) {
        error_log(date('Y-m-d H:i:s') . " - Invalid JSON input: " . $input);
        echo json_encode(['success' => false, 'error' => 'Invalid JSON data']);
        exit;
    }

    // Debug logging
    error_log(date('Y-m-d H:i:s') . " - Request: " . json_encode($data));

    $lessonId = intval($data['lesson_id'] ?? 0);
    $enrollmentId = intval($data['enrollment_id'] ?? 0);
    $action = $data['action'] ?? 'start';
    $userId = intval($_SESSION['user_id'] ?? 0);

    if (!$userId) {
        error_log(date('Y-m-d H:i:s') . " - Not authenticated");
        echo json_encode(['success' => false, 'error' => 'Not authenticated']);
        exit;
    }

    if (!$lessonId || !$enrollmentId) {
        error_log(date('Y-m-d H:i:s') . " - Missing lesson_id or enrollment_id: lesson=$lessonId, enrollment=$enrollmentId");
        echo json_encode(['success' => false, 'error' => 'Lesson ID and Enrollment ID are required']);
        exit;
    }

    // Verify enrollment belongs to user (relaxed status check for debugging)
    $stmt = $db->prepare("
        SELECT ce.id, ce.status, ce.course_id
        FROM course_enrollments ce
        WHERE ce.id = ? AND ce.student_id = ?
    ");
    $stmt->execute([$enrollmentId, $userId]);
    $enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$enrollment || $enrollment['status'] === 'cancelled') {
        error_log(date('Y-m-d H:i:s') . " - Invalid enrollment: user=$userId, enrollment=$enrollmentId, status=" . ($enrollment['status'] ?? 'null'));
        echo json_encode(['success' => false, 'error' => 'Invalid enrollment or cancelled: ' . ($enrollment['status'] ?? 'null')]);
        exit;
    }

    $courseId = $enrollment['course_id'];

    // Verify lesson belongs to the course
    $stmt = $db->prepare("SELECT id FROM course_lessons WHERE id = ? AND course_id = ?");
    $stmt->execute([$lessonId, $courseId]);
    $lesson = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$lesson) {
        error_log(date('Y-m-d H:i:s') . " - Invalid lesson: lesson=$lessonId, course=$courseId");
        echo json_encode(['success' => false, 'error' => 'Invalid lesson']);
        exit;
    }

    try {
        $response = ['success' => true];

        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]);
                error_log(date('Y-m-d H:i:s') . " - Lesson started: lesson=$lessonId, enrollment=$enrollmentId");
                break;

            case 'complete':
                // Check if already completed
                $stmt = $db->prepare("SELECT status FROM course_lesson_progress WHERE enrollment_id = ? AND lesson_id = ?");
                $stmt->execute([$enrollmentId, $lessonId]);
                $existing = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($existing && $existing['status'] === 'completed') {
                    error_log(date('Y-m-d H:i:s') . " - Lesson already completed: lesson=$lessonId, enrollment=$enrollmentId");
                    // Still return success and recalculate progress
                } else {
                    // 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]);
                    error_log(date('Y-m-d H:i:s') . " - Lesson completed: lesson=$lessonId, enrollment=$enrollmentId, time_spent=$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 = ?
                ");
                $stmt->execute([$enrollmentId, $courseId]);
                $progress = $stmt->fetch(PDO::FETCH_ASSOC);
                $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]);

                $response['progress_percentage'] = $progressPercentage;
                $response['total_lessons'] = intval($progress['total_lessons']);
                $response['completed_lessons'] = intval($progress['completed_lessons']);
                $response['course_status'] = $newStatus;

                error_log(date('Y-m-d H:i:s') . " - Progress updated: enrollment=$enrollmentId, progress=$progressPercentage%, status=$newStatus");
                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]);
                    error_log(date('Y-m-d H:i:s') . " - Time tracked: lesson=$lessonId, enrollment=$enrollmentId, time_spent=$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]);
                    error_log(date('Y-m-d H:i:s') . " - Note added: lesson=$lessonId, enrollment=$enrollmentId");
                }
                break;

            default:
                error_log(date('Y-m-d H:i:s') . " - Invalid action: $action");
                echo json_encode(['success' => false, 'error' => 'Invalid action']);
                exit;
        }

        echo json_encode($response);

    } catch (PDOException $e) {
        $errorMsg = $e->getMessage();
        error_log(date('Y-m-d H:i:s') . " - PDO Error (lesson=$lessonId, enrollment=$enrollmentId): " . $errorMsg);
        echo json_encode(['success' => false, 'error' => 'Database error: ' . $errorMsg]);
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
        error_log(date('Y-m-d H:i:s') . " - General Error (lesson=$lessonId, enrollment=$enrollmentId): " . $errorMsg);
        echo json_encode(['success' => false, 'error' => $errorMsg]);
    }

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

    if (!$lessonId) {
        error_log(date('Y-m-d H:i:s') . " - GET: Missing lesson_id");
        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(PDO::FETCH_ASSOC);

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

} else {
    error_log(date('Y-m-d H:i:s') . " - Invalid method: $method");
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
}
?>