<?php
// student/result.php - Updated for Multiple Question Types
require_once '../config/config.php';

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

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

// 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();

if (!$student_exam || $student_exam->status !== 'completed') {
    redirect('student/dashboard.php'); 
}

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

if (!$exam) {
    redirect('student/dashboard.php'); 
}

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

if (!$student) {
    redirect('student/register.php'); 
}

// Check for pending manual grading
$stmt = $pdo->prepare("
    SELECT COUNT(*) as pending FROM student_answers sa
    JOIN questions q ON sa.question_id = q.id
    WHERE sa.student_exam_id = ? AND q.auto_grade = 0 AND sa.graded_at IS NULL AND sa.answer_text IS NOT NULL
");
$stmt->execute([$student_exam->id]);
$pending_result = $stmt->fetch();
$pending_manual = $pending_result->pending ?? 0;

// Fetch Detailed Question and Answer Data
$questions = [];
if ($exam->show_result) {
    $stmt = $pdo->prepare("
        SELECT
            q.id, q.question_text, q.question_type, q.option_a, q.option_b, q.option_c, q.option_d, 
            q.correct_answer, q.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_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();
}

// Question type styles
$type_styles = [
    'mcq_4' => ['icon' => 'fa-list-ul', 'color' => 'blue', 'label' => 'Multiple Choice'],
    'mcq_3' => ['icon' => 'fa-list', 'color' => 'indigo', 'label' => 'Multiple Choice'],
    'mcq_2' => ['icon' => 'fa-toggle-on', 'color' => 'violet', 'label' => 'Multiple Choice'],
    '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) {
    $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) {
        $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) {
        $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>';
    }
    
    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 -->
    <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://assessment.edoxi.cyradrive.com/assets/01.png" alt="Edoxi 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 -->
                <?php 
                $header_color = 'blue';
                $header_icon = 'hourglass-half';
                $header_text = 'Assessment Submitted';
                $header_subtitle = 'Awaiting Final Results';
                
                if ($pending_manual == 0 && $student_exam->result) {
                    $header_color = $student_exam->result === 'pass' ? 'green' : 'red';
                    $header_icon = $student_exam->result === 'pass' ? 'trophy' : 'times-circle';
                    $header_text = $student_exam->result === 'pass' ? 'Congratulations!' : 'Keep Practicing!';
                    $header_subtitle = 'You ' . strtoupper($student_exam->result) . 'ED the Assessment';
                }
                ?>
                <div class="bg-gradient-to-r from-<?php echo $header_color; ?>-500 to-<?php echo $header_color; ?>-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 $header_icon; ?> text-7xl"></i>
                    </div>
                    <h1 class="text-5xl font-bold mb-3"><?php echo $header_text; ?></h1>
                    <p class="text-2xl font-semibold"><?php echo $header_subtitle; ?></p>
                    
                    <?php if ($pending_manual > 0): ?>
                    <div class="mt-4 bg-white bg-opacity-20 rounded-lg px-6 py-3 inline-block">
                        <p class="text-lg">
                            <i class="fas fa-clock mr-2"></i>
                            <?php echo $pending_manual; ?> question(s) pending manual grading
                        </p>
                    </div>
                    <?php endif; ?>
                </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 $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 $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 round($student_exam->percentage, 1); ?>%</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): 
                    $type_style = $type_styles[$q->question_type] ?? ['icon' => 'fa-question', 'color' => 'gray', 'label' => 'Question'];
                    
                    // Determine status
                    $status_class = 'border-gray-300';
                    $status_badge = '';
                    
                    if ($q->auto_grade) {
                        if ($q->is_correct) {
                            $status_class = 'border-green-500';
                            $status_badge = '<span class="bg-green-500 text-white px-4 py-2 rounded-full text-sm font-bold"><i class="fas fa-check mr-1"></i> Correct</span>';
                        } else {
                            $status_class = 'border-red-500';
                            $status_badge = '<span class="bg-red-500 text-white px-4 py-2 rounded-full text-sm font-bold"><i class="fas fa-times mr-1"></i> Wrong</span>';
                        }
                    } else {
                        if ($q->graded_at) {
                            $status_class = $q->partial_marks > 0 ? 'border-green-500' : 'border-red-500';
                            $status_badge = '<span class="bg-blue-500 text-white px-4 py-2 rounded-full text-sm font-bold"><i class="fas fa-check-double mr-1"></i> Graded: '.$q->partial_marks.'/'.$q->marks.'</span>';
                        } else {
                            $status_class = 'border-yellow-500';
                            $status_badge = '<span class="bg-yellow-500 text-white px-4 py-2 rounded-full text-sm font-bold"><i class="fas fa-clock mr-1"></i> Pending Review</span>';
                        }
                    }
                ?>
                <div class="bg-white rounded-xl shadow-md p-6 mb-4 border-l-8 <?php echo $status_class; ?>">
                    <div class="flex flex-wrap justify-between items-start mb-4 pb-3 border-b-2 border-gray-200 gap-2">
                        <div class="flex items-center gap-3">
                            <span class="inline-block bg-gray-200 text-gray-700 rounded-full px-3 py-1 text-sm font-bold">Q<?php echo $q_number++; ?></span>
                            <span class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-<?php echo $type_style['color']; ?>-100 text-<?php echo $type_style['color']; ?>-800">
                                <i class="fas <?php echo $type_style['icon']; ?> mr-1"></i>
                                <?php echo $type_style['label']; ?>
                            </span>
                            <span class="text-sm text-gray-500">(<?php echo $q->marks; ?> mark<?php echo $q->marks > 1 ? 's' : ''; ?>)</span>
                        </div>
                        <?php echo $status_badge; ?>
                    </div>
                    
                    <p class="font-semibold text-lg text-gray-800 mb-4"><?php echo escape($q->question_text); ?></p>

                    <?php if (in_array($q->question_type, ['mcq_4', 'mcq_3', 'mcq_2'])): ?>
                        <!-- MCQ Display -->
                        <div class="space-y-3 mb-4">
                            <?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 Display -->
                        <div class="flex gap-4 mb-4">
                            <div class="flex-1 p-4 rounded-lg text-center <?php echo $q->correct_answer === 'true' ? 'bg-green-100 border-2 border-green-400' : ($q->selected_answer === 'true' ? 'bg-red-100 border-2 border-red-400' : 'bg-gray-100'); ?>">
                                <i class="fas fa-check-circle text-2xl <?php echo $q->correct_answer === 'true' ? 'text-green-600' : 'text-gray-400'; ?> mb-1"></i>
                                <p class="font-bold">TRUE</p>
                                <?php if ($q->selected_answer === 'true'): ?>
                                    <p class="text-xs mt-1">(Your answer)</p>
                                <?php endif; ?>
                            </div>
                            <div class="flex-1 p-4 rounded-lg text-center <?php echo $q->correct_answer === 'false' ? 'bg-green-100 border-2 border-green-400' : ($q->selected_answer === 'false' ? 'bg-red-100 border-2 border-red-400' : 'bg-gray-100'); ?>">
                                <i class="fas fa-times-circle text-2xl <?php echo $q->correct_answer === 'false' ? 'text-green-600' : 'text-gray-400'; ?> mb-1"></i>
                                <p class="font-bold">FALSE</p>
                                <?php if ($q->selected_answer === 'false'): ?>
                                    <p class="text-xs mt-1">(Your answer)</p>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                    <?php elseif ($q->question_type === 'fill_blank'): ?>
                        <!-- Fill in Blank Display -->
                        <div class="bg-yellow-50 rounded-lg p-4 mb-4">
                            <p class="mb-2">
                                <span class="font-semibold text-gray-700">Your Answer:</span>
                                <span class="ml-2 px-3 py-1 rounded <?php echo $q->is_correct ? 'bg-green-200 text-green-800' : 'bg-red-200 text-red-800'; ?> font-semibold">
                                    <?php echo escape($q->selected_answer) ?: '(Not answered)'; ?>
                                </span>
                            </p>
                            <?php if (!$q->is_correct): ?>
                            <p>
                                <span class="font-semibold text-gray-700">Correct Answer:</span>
                                <span class="ml-2 px-3 py-1 rounded bg-green-200 text-green-800 font-semibold">
                                    <?php echo escape($q->correct_answer); ?>
                                </span>
                            </p>
                            <?php endif; ?>
                        </div>
                        
                    <?php elseif (in_array($q->question_type, ['short_answer', 'essay'])): ?>
                        <!-- Essay/Short Answer Display -->
                        <div class="bg-<?php echo $q->question_type === 'essay' ? 'red' : 'orange'; ?>-50 rounded-lg p-4 mb-4">
                            <p class="font-semibold text-gray-700 mb-2">Your Answer:</p>
                            <div class="bg-white rounded-lg p-4 border border-gray-200 whitespace-pre-wrap text-gray-800">
                                <?php echo escape($q->answer_text) ?: '(Not answered)'; ?>
                            </div>
                            <?php if ($q->answer_text && $q->word_limit): ?>
                            <p class="text-xs text-gray-500 mt-2">
                                Word count: <?php echo str_word_count($q->answer_text); ?> / <?php echo $q->word_limit; ?>
                            </p>
                            <?php endif; ?>
                            
                            <?php if ($q->graded_at && $q->feedback): ?>
                            <div class="mt-4 bg-blue-100 rounded-lg p-4">
                                <p class="font-semibold text-blue-800 mb-1"><i class="fas fa-comment mr-1"></i> Instructor Feedback:</p>
                                <p class="text-gray-700"><?php echo escape($q->feedback); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Answer Summary for auto-graded -->
                    <?php if ($q->auto_grade && in_array($q->question_type, ['mcq_4', 'mcq_3', 'mcq_2', 'true_false'])): ?>
                    <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>
                    <?php endif; ?>
                </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'); ?> Edoxi Training Center. All rights reserved.</p>
    </div>
</body>
</html>