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

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Authentication required']);
    exit;
}

$userId = $_SESSION['user_id'];
$db = getDB();

try {
    // Get form data
    $lessonId = $_POST['lesson_id'] ?? null;
    $enrollmentId = $_POST['enrollment_id'] ?? null;
    $submissionText = $_POST['submission_text'] ?? '';
    $attachment = $_FILES['attachment'] ?? null;

    // Validate required fields
    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.student_id, cl.lesson_type
        FROM course_enrollments ce
        JOIN course_lessons cl ON cl.id = ?
        WHERE ce.id = ? AND ce.student_id = ?
    ");
    $stmt->execute([$lessonId, $enrollmentId, $userId]);
    $enrollment = $stmt->fetch(PDO::FETCH_ASSOC);

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

    if ($enrollment['lesson_type'] !== 'assignment') {
        echo json_encode(['success' => false, 'error' => 'This lesson is not an assignment']);
        exit;
    }

    // Handle file upload if provided
    $attachmentPath = null;
    if ($attachment && $attachment['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../uploads/assignments/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $fileName = uniqid() . '_' . basename($attachment['name']);
        $attachmentPath = $uploadDir . $fileName;

        if (!move_uploaded_file($attachment['tmp_name'], $attachmentPath)) {
            echo json_encode(['success' => false, 'error' => 'Failed to upload attachment']);
            exit;
        }
    }

    // Check if submission already exists
    $stmt = $db->prepare("
        SELECT id FROM assignment_submissions
        WHERE enrollment_id = ? AND lesson_id = ?
    ");
    $stmt->execute([$enrollmentId, $lessonId]);
    $existingSubmission = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existingSubmission) {
        // Update existing submission
        $stmt = $db->prepare("
            UPDATE assignment_submissions
            SET submission_text = ?, attachment_path = ?, submitted_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$submissionText, $attachmentPath, $existingSubmission['id']]);
    } else {
        // Create new submission
        $stmt = $db->prepare("
            INSERT INTO assignment_submissions (enrollment_id, lesson_id, submission_text, attachment_path, submitted_at)
            VALUES (?, ?, ?, ?, NOW())
        ");
        $stmt->execute([$enrollmentId, $lessonId, $submissionText, $attachmentPath]);
    }

    echo json_encode(['success' => true, 'message' => 'Assignment submitted successfully']);

} catch (Exception $e) {
    error_log('Assignment submission error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'An error occurred while submitting the assignment']);
}
?>