<?php
// CORS and headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

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

require_once '../config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

$data = json_decode(file_get_contents('php://input'), true);
$session_token = $data['session_token'] ?? '';

if (empty($session_token)) {
    http_response_code(400);
    die(json_encode(['error' => 'Session token required']));
}

$debug = [];

try {
    $pdo->beginTransaction();

    // Mark session as submitted
    $stmt = $pdo->prepare("
        UPDATE active_sessions 
        SET session_status = 'submitted',
            submitted_at = NOW()
        WHERE session_token = ? AND session_status = 'active'
    ");
    $stmt->execute([$session_token]);

    // Get session details
    $stmt = $pdo->prepare("
        SELECT s.learner_id, s.assessment_id, s.session_status, a.assessment_title, l.full_name
        FROM active_sessions s
        JOIN assessments a ON s.assessment_id = a.assessment_id
        JOIN learners l ON s.learner_id = l.learner_id
        WHERE s.session_token = ?
    ");
    $stmt->execute([$session_token]);
    $session = $stmt->fetch();

    if (!$session) {
        throw new Exception('Session not found');
    }
    
    $debug['session'] = $session;

    // Get all responses for this session from learner_responses
    $stmt = $pdo->prepare("SELECT question_id, selected_choice FROM learner_responses WHERE session_token = ?");
    $stmt->execute([$session_token]);
    $responses = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $debug['responses_from_learner_responses'] = $responses;
    $debug['responses_count'] = count($responses);
    
    // If no responses in learner_responses, try to get from exam_progress
    if (empty($responses)) {
        $stmt = $pdo->prepare("SELECT answers_json FROM exam_progress WHERE session_token = ?");
        $stmt->execute([$session_token]);
        $progress = $stmt->fetch();
        
        if ($progress && !empty($progress['answers_json'])) {
            $answers = json_decode($progress['answers_json'], true);
            if (is_array($answers)) {
                foreach ($answers as $qid => $choices) {
                    if (is_array($choices) && count($choices) > 0) {
                        $responses[intval($qid)] = implode(',', $choices);
                    }
                }
                $debug['responses_from_exam_progress'] = $responses;
            }
        }
    }

    $earned = 0;
    $maximum = 0;
    $correctCount = 0;
    $wrongCount = 0;
    $totalAnswered = count($responses);
    
    // Use flutter_questions table for scoring
    $stmt = $pdo->prepare("SELECT id, correct_answers, is_multi_answer, point_value FROM flutter_questions");
    $stmt->execute();
    $questions = $stmt->fetchAll();
    
    $debug['questions_count'] = count($questions);
    
    foreach ($questions as $question) {
        $maximum += floatval($question['point_value']);
        $questionId = $question['id'];
        $isMultiAnswer = (bool)$question['is_multi_answer'];
        $correctAnswers = array_map('trim', explode(',', strtoupper($question['correct_answers'])));
        sort($correctAnswers);
        
        if (isset($responses[$questionId])) {
            $selectedChoices = array_map('trim', explode(',', strtoupper($responses[$questionId])));
            sort($selectedChoices);
            
            if ($isMultiAnswer) {
                if ($selectedChoices === $correctAnswers) {
                    $earned += floatval($question['point_value']);
                    $correctCount++;
                } else {
                    $wrongCount++;
                }
            } else {
                if (count($selectedChoices) === 1 && in_array($selectedChoices[0], $correctAnswers)) {
                    $earned += floatval($question['point_value']);
                    $correctCount++;
                } else {
                    $wrongCount++;
                }
            }
        } else {
            $wrongCount++;
        }
    }

    // Prevent division by zero - but use 30 as fallback
    if ($maximum <= 0) {
        $maximum = 30;
    }

    // Get passing threshold
    $stmt = $pdo->prepare("SELECT passing_threshold, question_count FROM assessments WHERE assessment_id = ?");
    $stmt->execute([$session['assessment_id']]);
    $assessmentData = $stmt->fetch();
    $threshold = floatval($assessmentData['passing_threshold'] ?? 50);
    $totalQuestions = intval($assessmentData['question_count'] ?? 30);

    $percentage = ($maximum > 0) ? round(($earned / $maximum) * 100, 2) : 0;
    $passed = $percentage >= $threshold;

    // Insert result
    $stmt = $pdo->prepare("
        INSERT INTO assessment_results (
            session_token, learner_id, assessment_id, 
            total_score, maximum_score, score_percentage, pass_status, was_terminated, graded_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE
            total_score = VALUES(total_score),
            maximum_score = VALUES(maximum_score),
            score_percentage = VALUES(score_percentage),
            pass_status = VALUES(pass_status),
            graded_at = NOW()
    ");

    $was_terminated = $session['session_status'] === 'terminated';
    $stmt->execute([
        $session_token,
        $session['learner_id'],
        $session['assessment_id'],
        $earned,
        $maximum,
        $percentage,
        $passed ? 1 : 0,
        $was_terminated ? 1 : 0
    ]);

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'result' => [
            'student_name' => $session['full_name'],
            'exam_title' => $session['assessment_title'],
            'score' => $earned,
            'max_score' => $maximum,
            'percentage' => $percentage,
            'passed' => $passed,
            'correct_count' => $correctCount,
            'wrong_count' => $wrongCount,
            'total_questions' => $totalQuestions,
            'total_answered' => $totalAnswered,
            'terminated' => $was_terminated
        ],
        'debug' => $debug
    ]);

} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['error' => 'Failed to submit exam', 'details' => $e->getMessage(), 'debug' => $debug]);
}
?>
