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

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

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

// Check if user is instructor or admin
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['instructor', 'admin'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit;
}

$db = getDB();
$submissionId = $_GET['id'] ?? null;

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

try {
    // Get submission details with instructor verification
    $stmt = $db->prepare("
        SELECT
            asub.*,
            cl.title as lesson_title,
            c.title as course_title,
            u.username as student_name,
            up.first_name,
            up.last_name
        FROM assignment_submissions asub
        JOIN course_lessons cl ON asub.lesson_id = cl.id
        JOIN course_enrollments ce ON asub.enrollment_id = ce.id
        JOIN courses c ON cl.course_id = c.id
        JOIN users u ON ce.student_id = u.id
        LEFT JOIN user_profiles up ON u.id = up.user_id
        WHERE asub.id = ? AND c.instructor_id = ?
    ");
    $stmt->execute([$submissionId, $_SESSION['user_id']]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$submission) {
        echo json_encode(['success' => false, 'error' => 'Submission not found or access denied']);
        exit;
    }

    // Format the response
    $response = [
        'success' => true,
        'submission' => [
            'id' => $submission['id'],
            'lesson_title' => $submission['lesson_title'],
            'course_title' => $submission['course_title'],
            'student_name' => $submission['first_name'] && $submission['last_name'] ?
                $submission['first_name'] . ' ' . $submission['last_name'] :
                $submission['student_name'],
            'submission_text' => $submission['submission_text'],
            'attachment_path' => $submission['attachment_path'],
            'submitted_at' => $submission['submitted_at'],
            'grade' => $submission['grade'],
            'feedback' => $submission['feedback'],
            'status' => $submission['status']
        ]
    ];

    echo json_encode($response);

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