<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

if (!isset($_GET['exam_id'])) {
    die('Exam ID is required.');
}

$exam_id = intval($_GET['exam_id']);

// Database connection
require_once 'connectiondb.php';


// Fetch exam info
$stmt = $pdo->prepare("SELECT exam_name FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$exam) {
    die('Exam not found.');
}

$stmt = $pdo->prepare("SELECT exam_name FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$exam) {
    die('Exam not found.');
}

// Fetch total number of questions in the exam
$stmt = $pdo->prepare("SELECT COUNT(*) FROM questions WHERE exam_id = ?");
$stmt->execute([$exam_id]);
$total_questions = $stmt->fetchColumn();

// Fetch student stats: attempted questions and total marks
$stmt = $pdo->prepare("
    SELECT s.id as student_id, s.name as student_name,
    COUNT(sa.question_id) as questions_attempted,
    SUM(CASE WHEN o.is_correct = 1 THEN 1 ELSE 0 END) as total_marks
    FROM students s
    JOIN student_exams se ON s.id = se.student_id AND se.exam_id = ?
    LEFT JOIN student_answers sa ON sa.student_id = s.id
    LEFT JOIN options o ON sa.selected_option_id = o.id
    WHERE se.exam_id = ?
    GROUP BY s.id
    ORDER BY s.name
");
$stmt->execute([$exam_id, $exam_id]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Prepare CSV output
$filename = 'exam_marks_' . preg_replace('/[^a-zA-Z0-9]/', '_', $exam['exam_name']) . '.csv';

header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Cache-Control: max-age=0');

$output = fopen('php://output', 'w');

$header = ['Student Name', 'Total Questions', 'Questions Attempted', 'Marks'];
fputcsv($output, $header);

// Data rows
foreach ($results as $row) {
    fputcsv($output, [
        $row['student_name'],
        $total_questions,
        $row['questions_attempted'],
        $row['total_marks']
    ]);
}

fclose($output);
exit;
?>
