<?php
// admin/report.php - Updated for Multiple Question Types
require_once '../config/config.php';
require_login();

$student_exam_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$student_exam_id) {
    header('Location: results.php');
    exit;
}

// Timezone offset (same as exam.php)
$TIMEZONE_OFFSET_HOURS = 10;

// Fetch report data with question type info
$stmt = $pdo->prepare("
    SELECT
        se.id AS student_exam_id, se.total_marks, se.obtained_marks, se.percentage, se.result, se.submitted_at,
        se.correct_answers, se.wrong_answers, se.unanswered,
        s.full_name, s.mobile, s.email, s.company,
        e.title AS exam_title, e.duration, e.instructions, e.passing_marks,
        q.id AS question_id, q.question_text, q.question_type, q.option_a, q.option_b, q.option_c, q.option_d, 
        q.correct_answer, q.marks AS question_marks, q.auto_grade, q.word_limit,
        sa.selected_answer, sa.answer_text, sa.is_correct, sa.partial_marks, sa.feedback, sa.graded_at
    FROM student_exams se
    JOIN students s ON se.student_id = s.id
    JOIN exams e ON se.exam_id = e.id
    JOIN student_answers sa ON se.id = sa.student_exam_id
    JOIN questions q ON sa.question_id = q.id
    WHERE se.id = :student_exam_id
    ORDER BY q.id ASC
");
$stmt->execute(['student_exam_id' => $student_exam_id]);
$report_data = $stmt->fetchAll();

if (empty($report_data)) {
    set_flash('error', 'Exam report not found or exam is not completed.');
    header('Location: results.php');
    exit;
}

$summary = $report_data[0];
$questions = $report_data;

// Calculate statistics
$total_questions = count($questions);
$correct_answers = $summary->correct_answers ?? 0;
$wrong_answers = $summary->wrong_answers ?? 0;
$unanswered = $summary->unanswered ?? 0;
$pending_grading = count(array_filter($questions, fn($q) => !$q->auto_grade && $q->graded_at === null && !empty($q->answer_text)));

// Adjusted time
$adjusted_date = strtotime($summary->submitted_at) + ($TIMEZONE_OFFSET_HOURS * 3600);

// Question type styles
$type_styles = [
    'mcq_4' => ['icon' => 'fa-list-ul', 'color' => 'blue', 'label' => 'Multiple Choice (4)'],
    'mcq_3' => ['icon' => 'fa-list', 'color' => 'indigo', 'label' => 'Multiple Choice (3)'],
    'mcq_2' => ['icon' => 'fa-toggle-on', 'color' => 'violet', 'label' => 'Multiple Choice (2)'],
    'true_false' => ['icon' => 'fa-check-circle', 'color' => 'green', 'label' => 'True/False'],
    'fill_blank' => ['icon' => 'fa-pencil-alt', 'color' => 'yellow', 'label' => 'Fill in Blank'],
    'short_answer' => ['icon' => 'fa-align-left', 'color' => 'orange', 'label' => 'Short Answer'],
    'essay' => ['icon' => 'fa-file-alt', 'color' => 'red', 'label' => 'Essay'],
];

function display_mcq_option($letter, $text, $selected, $correct) {
    if (empty($text)) return;
    
    $class = 'flex items-start p-3 rounded-lg transition-all duration-200';
    $icon = '';
    $badge = '';
    $is_selected = (strcasecmp($selected ?? '', $letter) === 0);
    $is_correct_answer = (strcasecmp($correct ?? '', $letter) === 0);

    if ($is_correct_answer) {
        $class .= ' bg-green-50 border-2 border-green-300 shadow-sm';
        $icon = '<div class="flex-shrink-0 w-8 h-8 bg-green-500 rounded-full flex items-center justify-center text-white font-bold mr-3">' . $letter . '</div>';
        $badge = '<span class="ml-auto flex-shrink-0 px-2 py-1 bg-green-500 text-white text-xs font-semibold rounded">Correct Answer</span>';
    } elseif ($is_selected && !$is_correct_answer) {
        $class .= ' bg-red-50 border-2 border-red-300 shadow-sm';
        $icon = '<div class="flex-shrink-0 w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white font-bold mr-3">' . $letter . '</div>';
        $badge = '<span class="ml-auto flex-shrink-0 px-2 py-1 bg-red-500 text-white text-xs font-semibold rounded">Student\'s Answer</span>';
    } else {
        $class .= ' bg-gray-50 border-2 border-gray-200';
        $icon = '<div class="flex-shrink-0 w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center text-gray-600 font-bold mr-3">' . $letter . '</div>';
    }
    
    echo "<div class=\"{$class}\">{$icon}<span class=\"flex-1 text-gray-800\">" . escape($text) . "</span>{$badge}</div>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Report - <?php echo escape($summary->full_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        @media print {
            .no-print { display: none !important; }
            body { background: white; }
            .page-break { page-break-before: always; }
        }
        .question-card { page-break-inside: avoid; }
        .stat-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .stat-card.success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .stat-card.danger { background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%); }
        .stat-card.info { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .stat-card.warning { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .report-header { background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%); }
        .pdf-generating {
            position: fixed; top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.8); display: flex;
            align-items: center; justify-content: center; z-index: 9999;
        }
        .pdf-progress {
            background: white; padding: 2rem; border-radius: 1rem;
            text-align: center; min-width: 300px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <?php include 'includes/nav.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 py-8">
        <!-- Header Actions -->
        <div class="flex flex-wrap justify-between items-center mb-6 no-print gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-900 mb-1">
                    <i class="fas fa-file-invoice text-orange-500 mr-2"></i>Examination Report
                </h1>
                <p class="text-gray-600">Detailed performance analysis and answer breakdown</p>
            </div>
            <div class="flex flex-wrap gap-3">
                <a href="results.php" class="px-6 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition shadow-sm">
                    <i class="fas fa-arrow-left mr-2"></i>Back
                </a>
                <button onclick="downloadPDF()" class="px-6 py-2.5 bg-gradient-to-r from-red-500 to-red-600 text-white rounded-lg font-medium hover:from-red-600 hover:to-red-700 transition shadow-md">
                    <i class="fas fa-file-pdf mr-2"></i>PDF
                </button>
                <button onclick="window.print()" class="px-6 py-2.5 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg font-medium hover:from-blue-600 hover:to-blue-700 transition shadow-md">
                    <i class="fas fa-print mr-2"></i>Print
                </button>
            </div>
        </div>

        <!-- Report Content -->
        <div id="reportContent">
            <!-- Professional Header -->
            <div class="report-header rounded-xl shadow-lg p-8 mb-6 text-white">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h2 class="text-3xl font-bold mb-2">Edoxi Training Center</h2>
                        <p class="text-white/90">Delivering Training Excellence, Globally!</p>
                    </div>
                    <div class="text-right">
                        <div class="bg-white/20 backdrop-blur-sm rounded-lg px-6 py-3">
                            <p class="text-sm text-white/80">Report Generated</p>
                            <p class="text-lg font-bold"><?php echo date('M d, Y'); ?></p>
                        </div>
                    </div>
                </div>
                <div class="border-t border-white/30 pt-4">
                    <h3 class="text-2xl font-bold"><?php echo escape($summary->exam_title); ?></h3>
                    <p class="text-white/90 mt-1">Official Examination Report</p>
                </div>
            </div>

            <!-- Student Information Card -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-user-graduate text-orange-500 mr-2"></i>Student Information
                    </h2>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        <div class="flex items-start">
                            <div class="flex-shrink-0 w-12 h-12 bg-gradient-to-br from-orange-400 to-orange-600 rounded-lg flex items-center justify-center text-white text-xl font-bold mr-4">
                                <?php echo strtoupper(substr($summary->full_name, 0, 1)); ?>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wide mb-1">Student Name</p>
                                <p class="text-base font-semibold text-gray-900"><?php echo escape($summary->full_name); ?></p>
                            </div>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500 uppercase tracking-wide mb-1">
                                <i class="fas fa-phone text-gray-400 mr-1"></i>Mobile
                            </p>
                            <p class="text-base font-semibold text-gray-900"><?php echo escape($summary->mobile); ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500 uppercase tracking-wide mb-1">
                                <i class="fas fa-envelope text-gray-400 mr-1"></i>Email
                            </p>
                            <p class="text-base font-semibold text-gray-900"><?php echo escape($summary->email); ?></p>
                        </div>
                        <div>
                            <p class="text-xs text-gray-500 uppercase tracking-wide mb-1">
                                <i class="fas fa-building text-gray-400 mr-1"></i>Company
                            </p>
                            <p class="text-base font-semibold text-gray-900"><?php echo escape($summary->company); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 mb-6">
                <div class="stat-card rounded-xl shadow-lg p-5 text-white">
                    <div class="flex items-center justify-between mb-3">
                        <div class="bg-white/20 rounded-full p-2">
                            <i class="fas fa-clipboard-list text-xl"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-medium mb-1">Total Questions</p>
                    <p class="text-3xl font-bold"><?php echo $total_questions; ?></p>
                </div>

                <div class="stat-card success rounded-xl shadow-lg p-5 text-white">
                    <div class="flex items-center justify-between mb-3">
                        <div class="bg-white/20 rounded-full p-2">
                            <i class="fas fa-check-circle text-xl"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-medium mb-1">Correct</p>
                    <p class="text-3xl font-bold"><?php echo $correct_answers; ?></p>
                </div>

                <div class="stat-card danger rounded-xl shadow-lg p-5 text-white">
                    <div class="flex items-center justify-between mb-3">
                        <div class="bg-white/20 rounded-full p-2">
                            <i class="fas fa-times-circle text-xl"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-medium mb-1">Wrong</p>
                    <p class="text-3xl font-bold"><?php echo $wrong_answers; ?></p>
                </div>

                <div class="stat-card warning rounded-xl shadow-lg p-5 text-white">
                    <div class="flex items-center justify-between mb-3">
                        <div class="bg-white/20 rounded-full p-2">
                            <i class="fas fa-clock text-xl"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-medium mb-1">Pending</p>
                    <p class="text-3xl font-bold"><?php echo $pending_grading; ?></p>
                </div>

                <div class="stat-card info rounded-xl shadow-lg p-5 text-white">
                    <div class="flex items-center justify-between mb-3">
                        <div class="bg-white/20 rounded-full p-2">
                            <i class="fas fa-percentage text-xl"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-medium mb-1">Score</p>
                    <p class="text-3xl font-bold"><?php echo round($summary->percentage, 1); ?>%</p>
                </div>
            </div>

            <!-- Exam Summary -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-chart-bar text-orange-500 mr-2"></i>Examination Summary
                    </h2>
                </div>
                <div class="p-6">
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-6">
                        <div class="text-center p-4 bg-gray-50 rounded-lg">
                            <p class="text-sm text-gray-600 mb-2">Total Marks</p>
                            <p class="text-3xl font-bold text-gray-900"><?php echo $summary->total_marks; ?></p>
                        </div>
                        <div class="text-center p-4 bg-green-50 rounded-lg">
                            <p class="text-sm text-gray-600 mb-2">Obtained Marks</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo $summary->obtained_marks; ?></p>
                        </div>
                        <div class="text-center p-4 bg-blue-50 rounded-lg">
                            <p class="text-sm text-gray-600 mb-2">Passing Marks</p>
                            <p class="text-3xl font-bold text-blue-600"><?php echo $summary->passing_marks; ?></p>
                        </div>
                        <div class="text-center p-4 <?php echo $summary->result === 'pass' ? 'bg-green-50' : ($summary->result === 'fail' ? 'bg-red-50' : 'bg-yellow-50'); ?> rounded-lg">
                            <p class="text-sm text-gray-600 mb-2">Result</p>
                            <?php if ($summary->result): ?>
                                <p class="text-2xl font-bold <?php echo $summary->result === 'pass' ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo strtoupper($summary->result); ?>
                                </p>
                            <?php else: ?>
                                <p class="text-xl font-bold text-yellow-600">PENDING</p>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="flex items-center p-4 bg-gray-50 rounded-lg">
                            <i class="fas fa-calendar text-orange-500 text-2xl mr-4"></i>
                            <div>
                                <p class="text-sm text-gray-600">Submission Date</p>
                                <p class="text-base font-semibold text-gray-900"><?php echo date('M d, Y', $adjusted_date); ?></p>
                            </div>
                        </div>
                        <div class="flex items-center p-4 bg-gray-50 rounded-lg">
                            <i class="fas fa-clock text-orange-500 text-2xl mr-4"></i>
                            <div>
                                <p class="text-sm text-gray-600">Submission Time</p>
                                <p class="text-base font-semibold text-gray-900"><?php echo date('h:i A', $adjusted_date); ?></p>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Bar -->
                    <div class="mt-6">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-gray-700">Performance Overview</span>
                            <span class="text-sm font-bold text-gray-900"><?php echo round($summary->percentage, 1); ?>%</span>
                        </div>
                        <div class="w-full h-4 bg-gray-200 rounded-full overflow-hidden">
                            <div class="h-full bg-gradient-to-r from-orange-400 to-orange-600 rounded-full transition-all duration-500" 
                                 style="width: <?php echo min(100, $summary->percentage); ?>%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Questions Breakdown -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden mb-6">
                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-list-ol text-orange-500 mr-2"></i>Detailed Answer Breakdown
                    </h2>
                </div>
                <div class="p-6">
                    <?php $q_number = 1; ?>
                    <?php foreach ($questions as $q): 
                        $type_style = $type_styles[$q->question_type] ?? ['icon' => 'fa-question', 'color' => 'gray', 'label' => 'Question'];
                        
                        // Determine status
                        $status_class = '';
                        $status_badge = '';
                        
                        if ($q->auto_grade) {
                            if ($q->is_correct) {
                                $status_class = 'bg-green-100 text-green-800';
                                $status_badge = '<i class="fas fa-check-circle mr-1"></i>Correct';
                            } else {
                                $status_class = 'bg-red-100 text-red-800';
                                $status_badge = '<i class="fas fa-times-circle mr-1"></i>Incorrect';
                            }
                        } else {
                            if ($q->graded_at) {
                                $status_class = 'bg-blue-100 text-blue-800';
                                $status_badge = '<i class="fas fa-check-double mr-1"></i>Graded: ' . $q->partial_marks . '/' . $q->question_marks;
                            } else {
                                $status_class = 'bg-yellow-100 text-yellow-800';
                                $status_badge = '<i class="fas fa-clock mr-1"></i>Pending Review';
                            }
                        }
                    ?>
                    <div class="question-card mb-6 pb-6 <?php echo $q_number < count($questions) ? 'border-b border-gray-200' : ''; ?>">
                        <!-- Question Header -->
                        <div class="flex flex-wrap items-start justify-between mb-4 gap-3">
                            <div class="flex items-start flex-1">
                                <div class="flex-shrink-0 w-10 h-10 bg-gradient-to-br from-orange-400 to-orange-600 rounded-lg flex items-center justify-center text-white font-bold mr-4">
                                    <?php echo $q_number; ?>
                                </div>
                                <div class="flex-1">
                                    <p class="text-lg font-semibold text-gray-900 mb-2"><?php echo escape($q->question_text); ?></p>
                                    <div class="flex flex-wrap items-center gap-3 text-sm">
                                        <span class="inline-flex items-center px-2 py-1 rounded-full bg-<?php echo $type_style['color']; ?>-100 text-<?php echo $type_style['color']; ?>-800 text-xs font-semibold">
                                            <i class="fas <?php echo $type_style['icon']; ?> mr-1"></i>
                                            <?php echo $type_style['label']; ?>
                                        </span>
                                        <span class="text-gray-600">
                                            <i class="fas fa-award text-yellow-500 mr-1"></i>
                                            Marks: <strong><?php echo $q->question_marks; ?></strong>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="flex-shrink-0">
                                <span class="inline-flex items-center px-4 py-2 <?php echo $status_class; ?> text-sm font-semibold rounded-lg">
                                    <?php echo $status_badge; ?>
                                </span>
                            </div>
                        </div>

                        <!-- Answer Display Based on Question Type -->
                        <div class="ml-14">
                            <?php if (in_array($q->question_type, ['mcq_4', 'mcq_3', 'mcq_2'])): ?>
                                <!-- MCQ Options -->
                                <div class="space-y-3">
                                    <?php display_mcq_option('A', $q->option_a, $q->selected_answer, $q->correct_answer); ?>
                                    <?php display_mcq_option('B', $q->option_b, $q->selected_answer, $q->correct_answer); ?>
                                    <?php if ($q->option_c): ?>
                                        <?php display_mcq_option('C', $q->option_c, $q->selected_answer, $q->correct_answer); ?>
                                    <?php endif; ?>
                                    <?php if ($q->option_d): ?>
                                        <?php display_mcq_option('D', $q->option_d, $q->selected_answer, $q->correct_answer); ?>
                                    <?php endif; ?>
                                </div>
                                
                            <?php elseif ($q->question_type === 'true_false'): ?>
                                <!-- True/False -->
                                <div class="flex gap-4">
                                    <div class="flex-1 p-4 rounded-lg text-center <?php echo strtolower($q->correct_answer) === 'true' ? 'bg-green-100 border-2 border-green-400' : (strtolower($q->selected_answer) === 'true' ? 'bg-red-100 border-2 border-red-400' : 'bg-gray-100 border-2 border-gray-200'); ?>">
                                        <i class="fas fa-check-circle text-2xl <?php echo strtolower($q->correct_answer) === 'true' ? 'text-green-600' : 'text-gray-400'; ?> mb-1"></i>
                                        <p class="font-bold">TRUE</p>
                                        <?php if (strtolower($q->selected_answer) === 'true'): ?>
                                            <p class="text-xs mt-1 font-semibold">(Student's Answer)</p>
                                        <?php endif; ?>
                                        <?php if (strtolower($q->correct_answer) === 'true'): ?>
                                            <p class="text-xs text-green-600 font-semibold">✓ Correct Answer</p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="flex-1 p-4 rounded-lg text-center <?php echo strtolower($q->correct_answer) === 'false' ? 'bg-green-100 border-2 border-green-400' : (strtolower($q->selected_answer) === 'false' ? 'bg-red-100 border-2 border-red-400' : 'bg-gray-100 border-2 border-gray-200'); ?>">
                                        <i class="fas fa-times-circle text-2xl <?php echo strtolower($q->correct_answer) === 'false' ? 'text-green-600' : 'text-gray-400'; ?> mb-1"></i>
                                        <p class="font-bold">FALSE</p>
                                        <?php if (strtolower($q->selected_answer) === 'false'): ?>
                                            <p class="text-xs mt-1 font-semibold">(Student's Answer)</p>
                                        <?php endif; ?>
                                        <?php if (strtolower($q->correct_answer) === 'false'): ?>
                                            <p class="text-xs text-green-600 font-semibold">✓ Correct Answer</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                            <?php elseif ($q->question_type === 'fill_blank'): ?>
                                <!-- Fill in Blank -->
                                <div class="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <p class="text-sm font-semibold text-gray-700 mb-1">Student's Answer:</p>
                                            <p class="px-4 py-2 rounded-lg font-semibold <?php echo $q->is_correct ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                                <?php echo escape($q->selected_answer) ?: '(Not answered)'; ?>
                                            </p>
                                        </div>
                                        <div>
                                            <p class="text-sm font-semibold text-gray-700 mb-1">Correct Answer:</p>
                                            <p class="px-4 py-2 bg-green-100 text-green-800 rounded-lg font-semibold">
                                                <?php echo escape($q->correct_answer); ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                
                            <?php elseif (in_array($q->question_type, ['short_answer', 'essay'])): ?>
                                <!-- Essay/Short Answer -->
                                <div class="bg-<?php echo $q->question_type === 'essay' ? 'red' : 'orange'; ?>-50 rounded-lg p-4 border border-<?php echo $q->question_type === 'essay' ? 'red' : 'orange'; ?>-200">
                                    <p class="text-sm font-semibold text-gray-700 mb-2">Student's Answer:</p>
                                    <div class="bg-white rounded-lg p-4 border border-gray-200 whitespace-pre-wrap text-gray-800 mb-3">
                                        <?php echo escape($q->answer_text) ?: '(Not answered)'; ?>
                                    </div>
                                    
                                    <?php if ($q->answer_text && $q->word_limit): ?>
                                    <p class="text-xs text-gray-500 mb-3">
                                        <i class="fas fa-text-width mr-1"></i>
                                        Word count: <?php echo str_word_count($q->answer_text); ?> / <?php echo $q->word_limit; ?>
                                    </p>
                                    <?php endif; ?>
                                    
                                    <?php if ($q->graded_at): ?>
                                    <div class="bg-blue-100 rounded-lg p-4 border border-blue-200">
                                        <div class="flex items-center justify-between mb-2">
                                            <p class="font-semibold text-blue-800">
                                                <i class="fas fa-check-double mr-1"></i> Graded
                                            </p>
                                            <span class="text-xl font-bold text-blue-700">
                                                <?php echo $q->partial_marks; ?> / <?php echo $q->question_marks; ?> marks
                                            </span>
                                        </div>
                                        <?php if ($q->feedback): ?>
                                        <div class="mt-2 pt-2 border-t border-blue-200">
                                            <p class="text-sm text-gray-700"><strong>Feedback:</strong> <?php echo escape($q->feedback); ?></p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php else: ?>
                                    <div class="bg-yellow-100 rounded-lg p-3 border border-yellow-200 text-center">
                                        <p class="text-yellow-800 font-semibold">
                                            <i class="fas fa-clock mr-1"></i> Awaiting Manual Grading
                                        </p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php $q_number++; ?>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Footer -->
            <div class="bg-white rounded-xl shadow-lg p-6 text-center">
                <div class="border-t border-gray-200 pt-4">
                    <p class="text-gray-600 text-sm mb-2">
                        <i class="fas fa-shield-alt text-orange-500 mr-1"></i>
                        This is an official examination report generated by Edoxi Training Center Assessment System
                    </p>
                    <p class="text-gray-500 text-xs">
                        Generated on <?php echo date('F d, Y \a\t h:i A'); ?> | Report ID: TTC-<?php echo str_pad($student_exam_id, 6, '0', STR_PAD_LEFT); ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        async function downloadPDF() {
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'pdf-generating';
            loadingDiv.innerHTML = `
                <div class="pdf-progress">
                    <i class="fas fa-file-pdf text-6xl text-red-500 mb-4"></i>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">Generating PDF Report</h3>
                    <p class="text-gray-600 mb-4">Please wait...</p>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="progressBar" class="bg-gradient-to-r from-orange-400 to-orange-600 h-2 rounded-full transition-all" style="width: 0%"></div>
                    </div>
                    <p id="progressText" class="text-sm text-gray-500 mt-2">Initializing...</p>
                </div>
            `;
            document.body.appendChild(loadingDiv);
            
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            
            try {
                const { jsPDF } = window.jspdf;
                const element = document.getElementById('reportContent');
                
                progressBar.style.width = '30%';
                progressText.textContent = 'Capturing content...';
                
                const canvas = await html2canvas(element, {
                    scale: 2,
                    useCORS: true,
                    logging: false,
                    backgroundColor: '#ffffff'
                });
                
                progressBar.style.width = '60%';
                progressText.textContent = 'Creating PDF...';
                
                const imgData = canvas.toDataURL('image/jpeg', 0.95);
                const pdf = new jsPDF('p', 'mm', 'a4');
                const pageWidth = pdf.internal.pageSize.getWidth();
                const pageHeight = pdf.internal.pageSize.getHeight();
                const imgWidth = pageWidth - 20;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                
                let heightLeft = imgHeight;
                let position = 10;
                let page = 1;
                
                pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
                heightLeft -= (pageHeight - 20);
                
                while (heightLeft > 0) {
                    position = heightLeft - imgHeight + 10;
                    pdf.addPage();
                    pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
                    heightLeft -= (pageHeight - 20);
                    page++;
                }
                
                progressBar.style.width = '90%';
                progressText.textContent = 'Finalizing...';
                
                const totalPages = pdf.internal.getNumberOfPages();
                for (let i = 1; i <= totalPages; i++) {
                    pdf.setPage(i);
                    pdf.setFontSize(8);
                    pdf.setTextColor(150);
                    pdf.text(`Page ${i} of ${totalPages} | TTC-<?php echo str_pad($student_exam_id, 6, '0', STR_PAD_LEFT); ?>`, pageWidth / 2, pageHeight - 5, { align: 'center' });
                }
                
                progressBar.style.width = '100%';
                progressText.textContent = 'Done!';
                
                pdf.save('Exam_Report_<?php echo preg_replace('/[^a-zA-Z0-9_-]/', '_', $summary->full_name); ?>_<?php echo date("Y-m-d"); ?>.pdf');
                
                setTimeout(() => document.body.removeChild(loadingDiv), 500);
                
            } catch (error) {
                console.error('PDF Error:', error);
                progressText.textContent = 'Error! Please try Print instead.';
                progressBar.classList.add('bg-red-500');
                setTimeout(() => document.body.removeChild(loadingDiv), 2000);
            }
        }
    </script>
</body>
</html>