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

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

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];
$attemptId = intval($_GET['attempt_id'] ?? 0);

    // DEBUG LOGGING
    $logData = [
        'timestamp' => date('Y-m-d H:i:s'),
        'endpoint' => 'get_submission',
        'raw_get' => $_GET,
        'raw_attempt_id' => $_GET['attempt_id'] ?? 'MISSING',
        'attempt_id_int' => $attemptId
    ];
    file_put_contents('../../logs/grading_log.txt', json_encode($logData) . "\n", FILE_APPEND | LOCK_EX);

if (!$attemptId) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Attempt ID required (got: ' . json_encode($_GET['attempt_id'] ?? null) . ')']);
    exit;
}

try {
    // Fetch attempt details + verify access
    $stmt = $db->prepare("
        SELECT ea.*, e.title as exam_title, e.passing_score, e.total_points,
               u.username as student_name, up.first_name, up.last_name
        FROM exam_attempts ea
        JOIN exams e ON ea.exam_id = e.id
        JOIN users u ON ea.student_id = u.id
        LEFT JOIN user_profiles up ON u.id = up.user_id
        WHERE ea.id = ? AND e.instructor_id = ?
    ");
    $stmt->execute([$attemptId, $userId]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$submission) {
        throw new Exception('Submission not found or access denied');
    }

    // Parse student answers from JSON
    $studentAnswers = json_decode($submission['answers'] ?? '{}', true) ?: [];

    // Fetch exam questions with options
    $stmt = $db->prepare("
        SELECT eq.question_id, eq.points, eq.sort_order,
               q.content, q.question_type, q.explanation,
               qo.id as option_id, qo.option_text, qo.is_correct, qo.sort_order as option_sort
        FROM exam_questions eq
        JOIN questions q ON eq.question_id = q.id
        LEFT JOIN question_options qo ON q.id = qo.question_id
        WHERE eq.exam_id = ?
        ORDER BY eq.sort_order, qo.sort_order
    ");
    $stmt->execute([$submission['exam_id']]);
    $questionData = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Group questions + calculate auto-scores
    $questions = [];
    foreach ($questionData as $row) {
        $qid = $row['question_id'];
        if (!isset($questions[$qid])) {
            $questions[$qid] = [
                'question_id' => $qid,
                'content' => $row['content'],
                'question_type' => $row['question_type'],
                'points' => $row['points'],
                'explanation' => $row['explanation'],
                'options' => [],
                'student_answer' => $studentAnswers[$qid] ?? null,
                'earned_points' => 0
            ];
        }
        if ($row['option_id']) {
            $questions[$qid]['options'][] = [
                'id' => $row['option_id'],
                'option_text' => $row['option_text'],
                'is_correct' => (bool)$row['is_correct']
            ];
        }
    }

    // Calculate auto-scores for objective questions
    foreach ($questions as $qid => &$question) {
        if (in_array($question['question_type'], ['mcq_single', 'mcq_multiple', 'true_false', 'matching'])) {
            $question['earned_points'] = calculateObjectiveScore($db, $qid, $question['student_answer'], $question);
        }
    }

    // include aliased attempt_id for JavaScript client compatibility
    $submission['attempt_id'] = $submission['id'];

    echo json_encode([
        'success' => true,
        'submission' => $submission,
        'questions' => array_values($questions)
    ]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function calculateObjectiveScore($db, $questionId, $studentAnswer, $question) {
    if (!$studentAnswer) return 0;

    switch ($question['question_type']) {
        case 'mcq_single':
        case 'true_false':
            foreach ($question['options'] as $option) {
                if (($option['id'] == $studentAnswer) && $option['is_correct']) {
                    return $question['points'];
                }
            }
            return 0;

        case 'mcq_multiple':
            if (is_array($studentAnswer)) {
                $correctOpts = array_filter($question['options'], fn($opt) => $opt['is_correct']);
                $totalCorrect = count($correctOpts);
                if ($totalCorrect == 0) return 0;
                $selectedCorrect = 0;
                foreach ($studentAnswer as $selectedId) {
                    foreach ($correctOpts as $correctOpt) {
                        if ($correctOpt['id'] == $selectedId) {
                            $selectedCorrect++;
                            break;
                        }
                    }
                }
                return ($selectedCorrect / $totalCorrect) * $question['points'];
            }
            return 0;

        case 'matching':
            if (is_array($studentAnswer)) {
                $correctMatches = 0;
                $totalMatches = 0;
                foreach ($question['options'] as $option) {
                    if ($option['is_correct']) {
                        $totalMatches++;
                        if (isset($studentAnswer[$option['id']]) && $studentAnswer[$option['id']] == $option['id']) {
                            $correctMatches++;
                        }
                    }
                }
                return $totalMatches > 0 ? ($correctMatches / $totalMatches) * $question['points'] : 0;
            }
            return 0;

        default:
            return 0;
    }
}
?>
