<?php
// student/result.php
require_once '../config/config.php';

// 1. Initial Session Check
if (!isset($_SESSION['student_id']) || !isset($_SESSION['exam_id'])) {
    redirect('student/register.php');
}

$student_id = $_SESSION['student_id'];
$exam_id = $_SESSION['exam_id'];

// 2. Fetch Student Exam Summary
$stmt = $pdo->prepare("SELECT * FROM student_exams WHERE student_id = ? AND exam_id = ?");
$stmt->execute([$student_id, $exam_id]);
$student_exam = $stmt->fetch();

// CRITICAL CHECK: Ensure student_exam record exists and is completed
if (!$student_exam || $student_exam->status !== 'completed') {
    // Redirect if exam record is missing or not marked completed
    redirect('student/dashboard.php'); 
}

// 3. Fetch Exam Details
$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

// CRITICAL CHECK: Ensure exam record exists
if (!$exam) {
    redirect('student/dashboard.php'); 
}


// 4. Fetch Student Details
$stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch();

// CRITICAL CHECK: Ensure student record exists
if (!$student) {
    redirect('student/register.php'); 
}

// 5. Fetch Detailed Question and Answer Data (Only if results are shown)
$questions = [];
if ($exam->show_result) {
    $stmt = $pdo->prepare("
        SELECT
            q.question_text, q.option_a, q.option_b, q.option_c, q.option_d, q.correct_answer,
            sa.selected_answer, sa.is_correct
        FROM
            student_answers sa
        JOIN
            questions q ON sa.question_id = q.id
        WHERE
            sa.student_exam_id = ?
        ORDER BY
            q.id ASC
    ");
    $stmt->execute([$student_exam->id]);
    $questions = $stmt->fetchAll();
}

/**
 * Function to display an option with styling based on correctness and selection.
 */
function display_option($letter, $text, $selected, $correct) {
    // Use strcasecmp for case-insensitive comparison
    $class = 'p-4 rounded-lg transition-colors duration-150 text-sm';
    $icon = '';
    $is_selected = (strcasecmp($selected, $letter) === 0);
    $is_correct_answer = (strcasecmp($correct, $letter) === 0);

    if ($is_correct_answer) {
        // Highlight the correct answer
        $class .= ' bg-green-50 font-semibold border-2 border-green-400';
        $icon = '<i class="fas fa-check-circle text-green-600 mr-2"></i>';
    } elseif ($is_selected && !$is_correct_answer) {
        // Highlight the wrong selected answer
        $class .= ' bg-red-50 font-semibold border-2 border-red-400';
        $icon = '<i class="fas fa-times-circle text-red-600 mr-2"></i>';
    } else {
        $class .= ' bg-gray-50 text-gray-700 border border-gray-200';
        $icon = '<span class="text-gray-500 mr-2 font-semibold">'.$letter.'.</span>';
    }
    
    // Assuming 'escape' is defined in config.php
    echo "<div class=\"{$class}\">{$icon} " . escape($text) . "</div>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Assessment Result - <?php echo escape($exam->title); ?></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>
        function toggleDetails() {
            const details = document.getElementById('report-details');
            const button = document.getElementById('toggle-button');
            if (details.classList.contains('hidden')) {
                details.classList.remove('hidden');
                button.innerHTML = '<i class="fas fa-eye-slash mr-2"></i> Hide Detailed Report';
            } else {
                details.classList.add('hidden');
                button.innerHTML = '<i class="fas fa-eye mr-2"></i> View Detailed Report';
            }
        }
        
        function printResult() {
            window.print();
        }
    </script>
    <style>
        @media print {
            .no-print {
                display: none;
            }
            #report-details {
                display: block !important;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-500 to-purple-600 min-h-screen">
    <!-- Header with Logo -->
    <div class="bg-white shadow-md no-print">
        <div class="max-w-5xl mx-auto px-4 py-4">
            <div class="flex items-center justify-between">
                <img src="https://www.timetraining.ae/design/images/new_logo.png" 
                     alt="Time Training Center" 
                     class="h-12">
                <div class="text-right">
                    <p class="text-sm text-gray-600">Assessment Result</p>
                    <p class="font-semibold text-gray-800"><?php echo date('d M Y'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-5xl mx-auto px-4 py-8">
        <?php if (!$exam->show_result): ?>
            <!-- Submission Confirmation (Results Hidden) -->
            <div class="bg-white rounded-2xl shadow-2xl p-12 text-center">
                <div class="inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6">
                    <i class="fas fa-check-circle text-blue-600 text-5xl"></i>
                </div>
                <h1 class="text-4xl font-bold text-gray-800 mb-4">Assessment Submitted Successfully!</h1>
                <p class="text-gray-600 text-lg mb-6">Your assessment has been submitted and recorded.</p>
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-6 max-w-md mx-auto">
                    <p class="text-gray-700 mb-2"><strong>Assessment:</strong> <?php echo escape($exam->title); ?></p>
                    <p class="text-gray-700 mb-2"><strong>Participant:</strong> <?php echo escape($student->full_name); ?></p>
                    <p class="text-gray-700"><strong>Company:</strong> <?php echo escape($student->company); ?></p>
                </div>
                <p class="text-gray-500 mt-6">Results will be announced by the training coordinator.</p>
            </div>
        <?php else: ?>
            <!-- Results Display -->
            <div class="bg-white rounded-2xl shadow-2xl overflow-hidden mb-8">
                <!-- Result Header -->
                <div class="bg-gradient-to-r from-<?php echo $student_exam->result === 'pass' ? 'green' : 'red'; ?>-500 to-<?php echo $student_exam->result === 'pass' ? 'green' : 'red'; ?>-600 p-10 text-center text-white">
                    <div class="inline-flex items-center justify-center w-28 h-28 bg-white bg-opacity-20 rounded-full mb-4">
                        <i class="fas fa-<?php echo $student_exam->result === 'pass' ? 'trophy' : 'times-circle'; ?> text-7xl"></i>
                    </div>
                    <h1 class="text-5xl font-bold mb-3">
                        <?php echo $student_exam->result === 'pass' ? 'Congratulations!' : 'Keep Practicing!'; ?>
                    </h1>
                    <p class="text-2xl font-semibold">You <span class="uppercase"><?php echo $student_exam->result; ?>ED</span> the Assessment</p>
                </div>
                
                <!-- Student and Exam Info -->
                <div class="p-8 md:p-10">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8 pb-6 border-b-2 border-gray-200">
                        <div class="bg-blue-50 rounded-lg p-5">
                            <h3 class="text-sm font-bold text-blue-800 mb-3 flex items-center">
                                <i class="fas fa-user-circle mr-2"></i> PARTICIPANT DETAILS
                            </h3>
                            <p class="text-gray-800 mb-1"><strong>Name:</strong> <?php echo escape($student->full_name); ?></p>
                            <p class="text-gray-800 mb-1"><strong>Email:</strong> <?php echo escape($student->email); ?></p>
                            <p class="text-gray-800 mb-1"><strong>Mobile:</strong> <?php echo escape($student->mobile); ?></p>
                            <p class="text-gray-800"><strong>Company:</strong> <?php echo escape($student->company); ?></p>
                        </div>
                        <div class="bg-purple-50 rounded-lg p-5">
                            <h3 class="text-sm font-bold text-purple-800 mb-3 flex items-center">
                                <i class="fas fa-clipboard-list mr-2"></i> ASSESSMENT DETAILS
                            </h3>
                            <p class="text-gray-800 mb-1"><strong>Assessment:</strong> <?php echo escape($exam->title); ?></p>
                            <p class="text-gray-800 mb-1"><strong>Duration:</strong> <?php echo $exam->duration; ?> minutes</p>
                            <p class="text-gray-800 mb-1"><strong>Total Marks:</strong> <?php echo $student_exam->total_marks; ?></p>
                            <p class="text-gray-800"><strong>Passing Marks:</strong> <?php echo $exam->passing_marks; ?></p>
                        </div>
                    </div>
                    
                    <!-- Score Cards -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
                        <div class="bg-gradient-to-br from-blue-50 to-blue-100 border-2 border-blue-300 rounded-xl p-5 text-center shadow-md">
                            <p class="text-4xl font-bold text-blue-600 mb-1">
                                <?php echo $student_exam->obtained_marks; ?><span class="text-2xl">/<?php echo $student_exam->total_marks; ?></span>
                            </p>
                            <p class="text-sm font-semibold text-gray-700">Your Score</p>
                        </div>
                        <div class="bg-gradient-to-br from-green-50 to-green-100 border-2 border-green-300 rounded-xl p-5 text-center shadow-md">
                            <p class="text-4xl font-bold text-green-600 mb-1"><?php echo $student_exam->correct_answers; ?></p>
                            <p class="text-sm font-semibold text-gray-700">Correct</p>
                        </div>
                        <div class="bg-gradient-to-br from-red-50 to-red-100 border-2 border-red-300 rounded-xl p-5 text-center shadow-md">
                            <p class="text-4xl font-bold text-red-600 mb-1"><?php echo $student_exam->wrong_answers; ?></p>
                            <p class="text-sm font-semibold text-gray-700">Wrong</p>
                        </div>
                        <div class="bg-gradient-to-br from-purple-50 to-purple-100 border-2 border-purple-300 rounded-xl p-5 text-center shadow-md">
                            <p class="text-4xl font-bold text-purple-600 mb-1"><?php echo $student_exam->percentage; ?>%</p>
                            <p class="text-sm font-semibold text-gray-700">Percentage</p>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="flex flex-col md:flex-row gap-4 justify-center no-print">
                        <button id="toggle-button" onclick="toggleDetails()" 
                                class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-8 rounded-xl transition duration-200 shadow-lg flex items-center justify-center">
                            <i class="fas fa-eye mr-2"></i> View Detailed Report
                        </button>
                        <button onclick="printResult()" 
                                class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-3 px-8 rounded-xl transition duration-200 shadow-lg flex items-center justify-center">
                            <i class="fas fa-print mr-2"></i> Print Result
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Detailed Question Breakdown -->
            <div id="report-details" class="hidden">
                <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                    <h2 class="text-2xl font-bold text-gray-800 flex items-center">
                        <i class="fas fa-list-check mr-3 text-blue-600"></i> Question-by-Question Analysis
                    </h2>
                    <p class="text-gray-600 mt-2">Review your answers and the correct solutions below.</p>
                </div>
                
                <?php $q_number = 1; ?>
                <?php foreach ($questions as $q): ?>
                <div class="bg-white rounded-xl shadow-md p-6 mb-4 
                    <?php echo $q->is_correct ? 'border-l-8 border-green-500' : 'border-l-8 border-red-500'; ?>">
                    
                    <div class="flex justify-between items-start mb-4 pb-3 border-b-2 border-gray-200">
                        <p class="font-bold text-lg text-gray-800 pr-4">
                            <span class="inline-block bg-gray-200 text-gray-700 rounded-full px-3 py-1 text-sm mr-2">Q<?php echo $q_number++; ?></span>
                            <?php echo escape($q->question_text); ?>
                        </p>
                        <span class="flex-shrink-0 text-sm font-bold px-4 py-2 rounded-full shadow-sm
                            <?php echo $q->is_correct ? 'bg-green-500 text-white' : 'bg-red-500 text-white'; ?>">
                            <?php echo $q->is_correct ? '<i class="fas fa-check"></i> Correct' : '<i class="fas fa-times"></i> Wrong'; ?>
                        </span>
                    </div>

                    <div class="space-y-3 mb-4">
                        <?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>
                    
                    <div class="bg-gray-50 rounded-lg p-4 border border-gray-200">
                        <div class="flex flex-wrap items-center gap-4">
                            <div>
                                <span class="font-bold text-gray-700">Your Answer:</span> 
                                <span class="font-bold uppercase ml-1 
                                    <?php echo $q->is_correct ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo escape($q->selected_answer) ?: 'NOT ANSWERED'; ?>
                                </span>
                            </div>
                            <div class="text-gray-400">|</div>
                            <div>
                                <span class="font-bold text-gray-700">Correct Answer:</span> 
                                <span class="font-bold uppercase ml-1 text-green-600">
                                    <?php echo escape($q->correct_answer); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <div class="text-center py-6 no-print">
        <p class="text-white text-sm">© <?php echo date('Y'); ?> Time Training Center. All rights reserved.</p>
    </div>
</body>
</html>