<?php
// admin/report.php
require_once '../config/config.php';
require_login();

// 1. Get the student_exam_id from the URL
$student_exam_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

// Check if an ID is present and valid
if (!$student_exam_id) {
    header('Location: results.php');
    exit;
}

// 2. SQL Query to fetch the report data
$stmt = $pdo->prepare("
    SELECT
        se.id AS student_exam_id, se.total_marks, se.obtained_marks, se.percentage, se.result, se.submitted_at,
        s.full_name, s.mobile, s.email, s.company,
        e.title AS exam_title, e.duration, e.instructions, e.passing_marks,
        q.question_text, q.option_a, q.option_b, q.option_c, q.option_d, q.correct_answer, q.marks AS question_marks,
        sa.selected_answer, sa.is_correct
    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();

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

// Extract summary data
$summary = $report_data[0];
$questions = $report_data;

// Calculate statistics
$total_questions = count($questions);
$correct_answers = count(array_filter($questions, fn($q) => $q->is_correct));
$wrong_answers = $total_questions - $correct_answers;
$adjusted_date = strtotime($summary->submitted_at . ' +9 hours');

/**
 * Function to display an option with styling
 */
function display_option($letter, $text, $selected, $correct) {
    $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">Your 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; }
        }
        
        .pdf-page {
            background: white;
            page-break-inside: avoid;
        }
        
        .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%);
        }
        .report-header {
            background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
        }
        
        /* PDF specific styles */
        .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 justify-between items-center mb-6 no-print">
            <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 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 to Results
                </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 hover:shadow-lg">
                    <i class="fas fa-file-pdf mr-2"></i>Download 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 hover:shadow-lg">
                    <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">Time Training Center</h2>
                        <p class="text-white/90">Established 1993 • Abu Dhabi, UAE</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 Number
                            </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 Address
                            </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-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                <div class="stat-card rounded-xl shadow-lg p-6 text-white">
                    <div class="flex items-center justify-between mb-4">
                        <div class="bg-white/20 rounded-full p-3">
                            <i class="fas fa-clipboard-list text-2xl"></i>
                        </div>
                        <span class="text-xs bg-white/20 px-3 py-1 rounded-full">Total</span>
                    </div>
                    <p class="text-white/80 text-sm font-medium mb-1">Total Questions</p>
                    <p class="text-4xl font-bold"><?php echo $total_questions; ?></p>
                </div>

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

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

                <div class="stat-card info rounded-xl shadow-lg p-6 text-white">
                    <div class="flex items-center justify-between mb-4">
                        <div class="bg-white/20 rounded-full p-3">
                            <i class="fas fa-percentage text-2xl"></i>
                        </div>
                        <span class="text-xs bg-white/20 px-3 py-1 rounded-full">Score</span>
                    </div>
                    <p class="text-white/80 text-sm font-medium mb-1">Percentage</p>
                    <p class="text-4xl font-bold"><?php echo $summary->percentage; ?>%</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' : 'bg-red-50'; ?> rounded-lg">
                            <p class="text-sm text-gray-600 mb-2">Result</p>
                            <p class="text-2xl font-bold <?php echo $summary->result === 'pass' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo strtoupper($summary->result); ?>
                            </p>
                        </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 $summary->percentage; ?>%</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 $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): ?>
                    <div class="question-card mb-6 pb-6 <?php echo $q_number < count($questions) ? 'border-b border-gray-200' : ''; ?>">
                        <!-- Question Header -->
                        <div class="flex items-start justify-between mb-4">
                            <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 items-center gap-4 text-sm">
                                        <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 ml-4">
                                <?php if ($q->is_correct): ?>
                                    <span class="inline-flex items-center px-4 py-2 bg-green-100 text-green-800 text-sm font-semibold rounded-lg">
                                        <i class="fas fa-check-circle mr-2"></i>Correct
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-4 py-2 bg-red-100 text-red-800 text-sm font-semibold rounded-lg">
                                        <i class="fas fa-times-circle mr-2"></i>Incorrect
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Options -->
                        <div class="space-y-3 ml-14">
                            <?php display_option('A', $q->option_a, $q->selected_answer, $q->correct_answer); ?>
                            <?php display_option('B', $q->option_b, $q->selected_answer, $q->correct_answer); ?>
                            <?php display_option('C', $q->option_c, $q->selected_answer, $q->correct_answer); ?>
                            <?php display_option('D', $q->option_d, $q->selected_answer, $q->correct_answer); ?>
                        </div>
                        
                        <?php 
                        // Add page break every 3 questions for better PDF pagination
                        if ($q_number % 3 == 0 && $q_number < count($questions)) {
                            echo '<div class="page-break"></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 Time 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() {
            // Show loading overlay
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'pdf-generating';
            loadingDiv.innerHTML = `
                <div class="pdf-progress">
                    <div class="mb-4">
                        <i class="fas fa-file-pdf text-6xl text-red-500 mb-4"></i>
                    </div>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">Generating PDF Report</h3>
                    <p class="text-gray-600 mb-4">Please wait while we prepare your document...</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 duration-300" 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 pdf = new jsPDF('p', 'mm', 'a4');
                const pageWidth = pdf.internal.pageSize.getWidth();
                const pageHeight = pdf.internal.pageSize.getHeight();
                const margin = 15;
                
                progressBar.style.width = '10%';
                progressText.textContent = 'Capturing content...';
                
                // Get all sections
                const sections = [
                    { element: document.querySelector('.report-header'), name: 'Header' },
                    { element: document.querySelector('.bg-white.rounded-xl.shadow-lg.overflow-hidden.mb-6'), name: 'Student Info' },
                    { element: document.querySelectorAll('.stat-card')[0]?.parentElement, name: 'Statistics' },
                    { element: document.querySelectorAll('.bg-white.rounded-xl.shadow-lg.overflow-hidden.mb-6')[1], name: 'Summary' },
                ];
                
                // Add questions sections
                const questionCards = document.querySelectorAll('.question-card');
                questionCards.forEach((card, index) => {
                    sections.push({ element: card, name: `Question ${index + 1}` });
                });
                
                let currentY = margin;
                let pageNumber = 1;
                const totalSections = sections.filter(s => s.element).length;
                let processedSections = 0;
                
                for (const section of sections) {
                    if (!section.element) continue;
                    
                    progressBar.style.width = `${10 + (processedSections / totalSections * 80)}%`;
                    progressText.textContent = `Processing ${section.name}...`;
                    
                    const canvas = await html2canvas(section.element, {
                        scale: 2,
                        useCORS: true,
                        logging: false,
                        backgroundColor: '#ffffff'
                    });
                    
                    const imgData = canvas.toDataURL('image/jpeg', 0.95);
                    const imgWidth = pageWidth - (margin * 2);
                    const imgHeight = (canvas.height * imgWidth) / canvas.width;
                    
                    // Check if we need a new page
                    if (currentY + imgHeight > pageHeight - margin && pageNumber > 1) {
                        pdf.addPage();
                        currentY = margin;
                        pageNumber++;
                    }
                    
                    pdf.addImage(imgData, 'JPEG', margin, currentY, imgWidth, imgHeight);
                    currentY += imgHeight + 5;
                    
                    // Add new page if needed
                    if (currentY > pageHeight - margin - 20) {
                        pdf.addPage();
                        currentY = margin;
                        pageNumber++;
                    }
                    
                    processedSections++;
                }
                
                // Add page numbers and footer
                progressBar.style.width = '90%';
                progressText.textContent = 'Adding page numbers...';
                
                const totalPages = pdf.internal.getNumberOfPages();
                for (let i = 1; i <= totalPages; i++) {
                    pdf.setPage(i);
                    pdf.setFontSize(8);
                    pdf.setTextColor(150);
                    pdf.text(
                        `Time Training Center | Page ${i} of ${totalPages} | Report ID: TTC-<?php echo str_pad($student_exam_id, 6, '0', STR_PAD_LEFT); ?>`,
                        pageWidth / 2,
                        pageHeight - 10,
                        { align: 'center' }
                    );
                }
                
                progressBar.style.width = '100%';
                progressText.textContent = 'Finalizing document...';
                
                // Save the PDF
                const filename = 'Exam_Report_<?php echo preg_replace('/[^a-zA-Z0-9_-]/', '_', $summary->full_name); ?>_<?php echo date("Y-m-d", $adjusted_date); ?>.pdf';
                pdf.save(filename);
                
                // Remove loading overlay
                setTimeout(() => {
                    document.body.removeChild(loadingDiv);
                }, 500);
                
            } catch (error) {
                console.error('PDF Generation Error:', error);
                progressText.textContent = 'Error generating PDF. Please try again.';
                progressBar.style.width = '100%';
                progressBar.classList.remove('from-orange-400', 'to-orange-600');
                progressBar.classList.add('bg-red-500');
                
                setTimeout(() => {
                    document.body.removeChild(loadingDiv);
                }, 2000);
            }
        }
    </script>
</body>
</html>