<?php
/**
 * Get All Progress API
 * Returns all student exam progress for admin dashboard
 * Fixed to use flutter_questions table
 */

require_once '../config/database.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, Authorization, X-Requested-With');

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

try {
    // Get all Flutter questions for answer mapping
    $stmt = $pdo->query("SELECT id, title, option_a, option_b, option_c, option_d, correct_answers, is_multi_answer FROM flutter_questions ORDER BY id");
    $flutter_questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Create lookup by ID
    $questions_map = [];
    foreach ($flutter_questions as $idx => $q) {
        $questions_map[$q['id']] = [
            'question_id' => $q['id'],
            'question_order' => $idx + 1,
            'question_prompt' => $q['title'],
            'choice_a' => $q['option_a'],
            'choice_b' => $q['option_b'],
            'choice_c' => $q['option_c'],
            'choice_d' => $q['option_d'],
            'correct_answers' => $q['correct_answers'],
            'is_multi_answer' => (bool)$q['is_multi_answer']
        ];
    }
    
    // Get all progress records with exam details
    $stmt = $pdo->query("
        SELECT 
            ep.id,
            ep.session_token,
            ep.student_email,
            ep.student_name,
            ep.roll_no,
            ep.exam_code,
            ep.answers_json,
            ep.time_remaining,
            ep.current_question,
            ep.total_questions,
            ep.answered_count,
            ep.status as progress_status,
            ep.last_sync,
            ep.created_at,
            a.assessment_title as exam_title,
            a.total_duration_mins,
            s.session_status,
            s.termination_reason,
            s.violation_count,
            s.submitted_at,
            ar.total_score,
            ar.maximum_score,
            ar.score_percentage,
            ar.pass_status
        FROM exam_progress ep
        LEFT JOIN assessments a ON ep.exam_code = a.exam_code
        LEFT JOIN active_sessions s ON ep.session_token = s.session_token
        LEFT JOIN assessment_results ar ON ep.session_token = ar.session_token
        ORDER BY ep.last_sync DESC
    ");
    $progress = $stmt->fetchAll();

    // Format response
    $formatted = [];
    foreach ($progress as $p) {
        $answers = json_decode($p['answers_json'], true) ?: [];
        
        // Map answers to question details using flutter_questions
        $detailed_answers = [];
        $correct_count = 0;
        $wrong_count = 0;
        $not_attempted = 0;
        
        foreach ($questions_map as $qid => $q) {
            $selected = isset($answers[$qid]) ? $answers[$qid] : null;
            
            if ($selected && is_array($selected) && count($selected) > 0) {
                // Student answered this question
                $selectedStr = strtoupper(implode(',', $selected));
                $correctStr = strtoupper($q['correct_answers']);
                
                // For comparison, sort both
                $selectedSorted = explode(',', $selectedStr);
                $correctSorted = explode(',', $correctStr);
                sort($selectedSorted);
                sort($correctSorted);
                
                $is_correct = ($selectedSorted === $correctSorted);
                
                if ($is_correct) {
                    $correct_count++;
                } else {
                    $wrong_count++;
                }
                
                $detailed_answers[] = [
                    'question_id' => $qid,
                    'question_order' => $q['question_order'],
                    'question_prompt' => $q['question_prompt'],
                    'choices' => [
                        'A' => $q['choice_a'],
                        'B' => $q['choice_b'],
                        'C' => $q['choice_c'],
                        'D' => $q['choice_d']
                    ],
                    'selected' => $selected,
                    'correct' => $q['correct_answers'],
                    'is_correct' => $is_correct,
                    'is_multi_answer' => $q['is_multi_answer']
                ];
            } else {
                $not_attempted++;
            }
        }

        $formatted[] = [
            'id' => $p['id'],
            'student' => [
                'name' => $p['student_name'],
                'email' => $p['student_email'],
                'roll_no' => $p['roll_no'] ?? ''
            ],
            'exam' => [
                'code' => $p['exam_code'],
                'title' => $p['exam_title'] ?? $p['exam_code'],
                'duration_minutes' => $p['total_duration_mins']
            ],
            'progress' => [
                'current_question' => $p['current_question'],
                'total_questions' => count($questions_map),
                'answered_count' => $p['answered_count'],
                'time_remaining' => $p['time_remaining'],
                'percentage' => count($questions_map) > 0 
                    ? round(($p['answered_count'] / count($questions_map)) * 100) 
                    : 0
            ],
            'status' => $p['session_status'] ?? $p['progress_status'] ?? 'active',
            'termination_reason' => $p['termination_reason'] ?? null,
            'violation_count' => $p['violation_count'] ?? 0,
            'submitted_at' => $p['submitted_at'],
            'result' => $p['total_score'] !== null ? [
                'score' => floatval($p['total_score']),
                'max_score' => floatval($p['maximum_score']),
                'percentage' => floatval($p['score_percentage'] ?? 0),
                'passed' => (bool)$p['pass_status'],
                'correct_count' => $correct_count,
                'wrong_count' => $wrong_count,
                'not_attempted' => $not_attempted
            ] : null,
            'summary' => [
                'correct_count' => $correct_count,
                'wrong_count' => $wrong_count,
                'not_attempted' => $not_attempted
            ],
            'answers' => $detailed_answers,
            'last_sync' => $p['last_sync'],
            'started_at' => $p['created_at']
        ];
    }

    echo json_encode([
        'success' => true,
        'count' => count($formatted),
        'total_questions' => count($questions_map),
        'students' => $formatted
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error', 'details' => $e->getMessage()]);
}
?>
