Path : /home/vishqocm/pcib.in/student/
File Upload :
Current File : //home/vishqocm/pcib.in/student/exam_results.php

<?php
// Start session
session_start();

// Include database configuration
require_once '../config/database.php';

// Function to calculate grade based on percentage
function calculateGrade($percentage) {
    if ($percentage >= 90) {
        return ['grade' => 'A+', 'description' => 'Outstanding', 'color' => '#28a745'];
    } elseif ($percentage >= 80) {
        return ['grade' => 'A', 'description' => 'Excellent', 'color' => '#28a745'];
    } elseif ($percentage >= 70) {
        return ['grade' => 'B+', 'description' => 'Very Good', 'color' => '#17a2b8'];
    } elseif ($percentage >= 60) {
        return ['grade' => 'B', 'description' => 'Good', 'color' => '#17a2b8'];
    } elseif ($percentage >= 50) {
        return ['grade' => 'C', 'description' => 'Average', 'color' => '#6c757d'];
    } elseif ($percentage >= 40) {
        return ['grade' => 'D', 'description' => 'Pass', 'color' => '#ffc107'];
    } else {
        return ['grade' => 'F', 'description' => 'Fail', 'color' => '#dc3545'];
    }
}

// Check if user is logged in and has student role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    header('Location: ../login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// Check if exam ID is provided
if (!isset($_GET['exam_id']) || empty($_GET['exam_id'])) {
    $_SESSION['error_message'] = "No exam specified.";
    header('Location: exams.php');
    exit;
}

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

// Get exam details
$exam_query = "SELECT es.*, c.title as course_title 
               FROM exam_schedules es 
               JOIN courses c ON es.course_id = c.id 
               WHERE es.id = ?";
$stmt = $conn->prepare($exam_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$exam_result = $stmt->get_result();

if ($exam_result->num_rows === 0) {
    $_SESSION['error_message'] = "Exam not found.";
    header('Location: exams.php');
    exit;
}

$exam = $exam_result->fetch_assoc();

// Get student exam record
$student_exam_query = "SELECT * FROM student_exams WHERE user_id = ? AND exam_id = ?";
$stmt = $conn->prepare($student_exam_query);
$stmt->bind_param("ii", $user_id, $exam_id);
$stmt->execute();
$student_exam_result = $stmt->get_result();

if ($student_exam_result->num_rows === 0) {
    $_SESSION['error_message'] = "You haven't taken this exam yet.";
    header('Location: exams.php');
    exit;
}

$student_exam = $student_exam_result->fetch_assoc();

// Check if exam is completed
if (!in_array($student_exam['status'], ['completed', 'graded', 'passed', 'failed'])) {
    $_SESSION['error_message'] = "Exam is still in progress.";
    header('Location: take_exam.php?exam_id=' . $exam_id);
    exit;
}

// Check if there's a certificate available
$certificate_query = "SELECT * FROM exam_certificates WHERE student_exam_id = ?";
$stmt = $conn->prepare($certificate_query);
$stmt->bind_param("i", $student_exam['id']);
$stmt->execute();
$certificate_result = $stmt->get_result();
$certificate = $certificate_result->num_rows > 0 ? $certificate_result->fetch_assoc() : null;

// If student passed and doesn't have a certificate yet, redirect to certificate page
if ($student_exam['status'] === 'passed' && !$certificate && !isset($_GET['no_redirect'])) {
    $_SESSION['success_message'] = "Congratulations! You passed the exam. You can now generate your unified certificate that includes both your course completion and exam results.";
    header('Location: certificates.php?exam_id=' . $exam_id . '&from_results=1');
    exit;
}

// Get all questions and answers
$answers_query = "SELECT q.*, sa.answer_text, sa.selected_option_id, sa.is_correct, sa.marks_obtained, 
                qo.option_text as selected_option_text
                     FROM questions q 
                     JOIN exam_question_maps eqm ON q.id = eqm.question_id 
                LEFT JOIN student_answers sa ON q.id = sa.question_id AND sa.student_exam_id = ?
                LEFT JOIN question_options qo ON sa.selected_option_id = qo.id
                WHERE eqm.exam_id = ?
                ORDER BY eqm.id";
$stmt = $conn->prepare($answers_query);
$stmt->bind_param("ii", $student_exam['id'], $exam_id);
$stmt->execute();
$answers_result = $stmt->get_result();
$questions = [];

while ($answer = $answers_result->fetch_assoc()) {
    $questions[] = $answer;
}

// Get correct options for each question
foreach ($questions as $key => $question) {
    if ($question['question_type'] === 'multiple_choice' || $question['question_type'] === 'true_false') {
        $options_query = "SELECT * FROM question_options WHERE question_id = ?";
        $stmt = $conn->prepare($options_query);
        $stmt->bind_param("i", $question['id']);
        $stmt->execute();
        $options_result = $stmt->get_result();
        $questions[$key]['options'] = [];
        $questions[$key]['correct_option'] = null;
        
        while ($option = $options_result->fetch_assoc()) {
            $questions[$key]['options'][] = $option;
            
            if ($option['is_correct']) {
                $questions[$key]['correct_option'] = $option;
            }
        }
    }
}

// Calculate statistics
$total_questions = count($questions);
$total_marks = 0;
$obtained_marks = 0;
$correct_count = 0;
$incorrect_count = 0;
$unanswered_count = 0;

foreach ($questions as $question) {
    $total_marks += $question['marks'];
    
    if ($question['is_correct'] === 1) {
        $correct_count++;
        $obtained_marks += $question['marks_obtained'];
    } elseif ($question['is_correct'] === 0) {
        $incorrect_count++;
    } else {
        // Null means unanswered or pending grading
        $unanswered_count++;
    }
}

// Calculate percentage
$percentage = $total_marks > 0 ? ($obtained_marks / $total_marks) * 100 : 0;
$formatted_percentage = number_format($percentage, 1);

// Include header
include_once 'includes/header.php';
?>

<div class="container-fluid">
    <!-- Header with Background -->
    <div class="card mb-4 bg-gradient-primary text-white shadow">
        <div class="card-body py-4">
            <div class="d-sm-flex align-items-center justify-content-between">
                <div>
                    <h1 class="h3 mb-0 text-white">Exam Results</h1>
                    <p class="mb-0 opacity-75"><?php echo htmlspecialchars($exam['title']); ?></p>
                </div>
                <div>
                    <a href="exams.php" class="btn btn-light btn-sm shadow-sm">
                        <i class="fas fa-arrow-left fa-sm"></i> Back to Exams
                    </a>
                    <?php if ($certificate): ?>
                    <a href="view_certificate.php?id=<?php echo $certificate['id']; ?>" class="btn btn-success btn-sm shadow-sm ml-2">
                        <i class="fas fa-certificate fa-sm"></i> View Unified Certificate
                    </a>
                    <?php elseif ($student_exam['status'] === 'passed'): ?>
                    <a href="certificates.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-warning btn-sm shadow-sm ml-2">
                        <i class="fas fa-award fa-sm"></i> Get Unified Certificate
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php 
            echo $_SESSION['error_message']; 
            unset($_SESSION['error_message']);
            ?>
            <button type="button" class="close btn-close" data-dismiss="alert" data-bs-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php 
            echo $_SESSION['success_message']; 
            unset($_SESSION['success_message']);
            ?>
            <button type="button" class="close btn-close" data-dismiss="alert" data-bs-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    <?php endif; ?>
    
    <!-- Score Card -->
    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-xl-4 col-lg-5 text-center border-right">
                    <div class="mb-3">
                        <h1 class="display-4 font-weight-bold mb-0 text-<?php 
                            echo ($percentage >= $exam['passing_percentage']) ? 'success' : 'danger'; 
                        ?>"><?php echo $formatted_percentage; ?>%</h1>
                        <p class="mb-0 text-muted">Your Score</p>
                    </div>
                    
                    <div class="mb-4">
                        <div class="mb-2 d-flex justify-content-between">
                            <span>Your Score</span>
                            <span class="text-<?php echo ($percentage >= $exam['passing_percentage']) ? 'success' : 'danger'; ?>">
                                <?php echo $formatted_percentage; ?>%
                                </span>
                </div>
                        <div class="progress" style="height: 10px;">
                            <div class="progress-bar bg-<?php 
                                echo ($percentage >= $exam['passing_percentage']) ? 'success' : 'danger'; 
                            ?>" 
                                role="progressbar" 
                                style="width: <?php echo min(100, $percentage); ?>%" 
                                aria-valuenow="<?php echo $percentage; ?>" 
                                aria-valuemin="0" 
                                aria-valuemax="100">
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <span class="badge badge-pill badge-<?php 
                            echo ($student_exam['status'] === 'passed') ? 'success' : 
                                (($student_exam['status'] === 'failed') ? 'danger' : 'info'); 
                        ?> p-2 px-3 font-weight-normal">
                            <?php echo ucfirst($student_exam['status']); ?>
                        </span>
                        
                        <?php if ($student_exam['status'] === 'passed' || $student_exam['status'] === 'graded'): 
                            $grade = calculateGrade($percentage);
                        ?>
                        <span class="badge badge-pill badge-primary p-2 px-3 ml-2 font-weight-normal">
                            Grade: <?php echo $grade['grade']; ?> (<?php echo $grade['description']; ?>)
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="col-xl-4 col-lg-3 mb-4 mb-lg-0">
                    <div class="chart-pie pt-2 pb-1">
                        <canvas id="resultsPieChart"></canvas>
                    </div>
                    <div class="mt-2 text-center small">
                        <span class="mr-2">
                            <i class="fas fa-circle text-success"></i> Correct (<?php echo $correct_count; ?>)
                        </span>
                        <span class="mr-2">
                            <i class="fas fa-circle text-danger"></i> Incorrect (<?php echo $incorrect_count; ?>)
                        </span>
                        <?php if ($unanswered_count > 0): ?>
                        <span>
                            <i class="fas fa-circle text-warning"></i> Pending (<?php echo $unanswered_count; ?>)
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="col-xl-4 col-lg-4">
                    <h5 class="font-weight-bold">Exam Details</h5>
                    <div class="table-responsive">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td><i class="fas fa-book text-primary mr-2"></i> Course:</td>
                                <td><?php echo htmlspecialchars($exam['course_title']); ?></td>
                            </tr>
                            <tr>
                                <td><i class="fas fa-calendar text-primary mr-2"></i> Date:</td>
                                <td><?php echo date('M d, Y', strtotime($exam['exam_date'])); ?></td>
                            </tr>
                            <tr>
                                <td><i class="fas fa-clock text-primary mr-2"></i> Duration:</td>
                                <td><?php echo $exam['duration_minutes']; ?> minutes</td>
                            </tr>
                            <tr>
                                <td><i class="fas fa-check-circle text-primary mr-2"></i> Passing Score:</td>
                                <td><?php echo $exam['passing_percentage']; ?>%</td>
                            </tr>
                            <tr>
                                <td><i class="fas fa-tasks text-primary mr-2"></i> Total Marks:</td>
                                <td><?php echo $obtained_marks; ?> / <?php echo $total_marks; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            
            <?php if ($student_exam['status'] === 'completed'): ?>
                <div class="alert alert-info mb-0 mt-3">
                    <i class="fas fa-info-circle mr-2"></i> Some questions require manual grading. Your final score will be available once grading is complete.
                </div>
            <?php endif; ?>
            
            <?php if ($student_exam['admin_remarks']): ?>
                <div class="alert alert-info mb-0 mt-3">
                    <h6 class="font-weight-bold">Instructor Remarks:</h6>
                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($student_exam['admin_remarks'])); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Result Analysis -->
    <div class="row mb-4">
        <!-- Strengths and Weaknesses Card -->
        <div class="col-lg-12">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Performance Summary</h6>
                </div>
                            <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 border-right">
                            <h5 class="text-success mb-3"><i class="fas fa-thumbs-up mr-2"></i> What Went Well</h5>
                            <p>
                                <?php if ($correct_count > ($total_questions / 2)): ?>
                                    You performed well overall, answering the majority of questions correctly.
                                <?php elseif ($correct_count > 0): ?>
                                    You answered <?php echo $correct_count; ?> question<?php echo $correct_count !== 1 ? 's' : ''; ?> correctly.
                                <?php else: ?>
                                    Keep practicing to improve your knowledge in this area.
                                <?php endif; ?>
                            </p>
                            
                            <?php if ($percentage >= $exam['passing_percentage']): ?>
                            <p>
                                <i class="fas fa-check-circle text-success mr-1"></i> 
                                You successfully passed this exam with a score of <?php echo $formatted_percentage; ?>%, 
                                which is above the required passing score of <?php echo $exam['passing_percentage']; ?>%.
                            </p>
                            <p>
                                <i class="fas fa-award text-primary mr-1"></i>
                                Your grade is <strong><?php echo calculateGrade($percentage)['grade']; ?></strong> 
                                (<?php echo calculateGrade($percentage)['description']; ?>).
                            </p>
                            <?php if ($certificate): ?>
                            <p>
                                <i class="fas fa-certificate text-success mr-1"></i> 
                                Congratulations! You have earned a unified certificate for this course and exam.
                                <a href="view_certificate.php?id=<?php echo $certificate['id']; ?>" class="btn btn-success btn-sm ml-2">
                                    <i class="fas fa-eye"></i> View Unified Certificate
                                </a>
                            </p>
                            <?php elseif ($student_exam['status'] === 'passed'): ?>
                            <div class="alert alert-warning mt-3">
                                <i class="fas fa-award mr-1"></i>
                                <strong>Certificate Available!</strong> You've passed this exam and are eligible for a unified certificate.
                                <a href="certificates.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-warning btn-sm ml-2">
                                    <i class="fas fa-award"></i> Get Your Unified Certificate
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php endif; ?>
                            </div>
                        
                        <div class="col-md-6">
                            <h5 class="text-danger mb-3"><i class="fas fa-bullseye mr-2"></i> Areas to Improve</h5>
                            <?php if ($incorrect_count > 0): ?>
                            <p>
                                <i class="fas fa-exclamation-circle text-danger mr-1"></i>
                                You missed <?php echo $incorrect_count; ?> question<?php echo $incorrect_count !== 1 ? 's' : ''; ?>.
                                Review the detailed answers below to understand where you made mistakes.
                            </p>
                            <?php endif; ?>
                            
                            <?php if ($percentage < $exam['passing_percentage']): ?>
                            <p>
                                <i class="fas fa-times-circle text-danger mr-1"></i>
                                Your score of <?php echo $formatted_percentage; ?>% is below the required passing score of 
                                <?php echo $exam['passing_percentage']; ?>%. Consider reviewing the course materials and trying again.
                            </p>
                            <?php endif; ?>
                            
                            <?php if ($unanswered_count > 0): ?>
                            <p>
                                <i class="fas fa-clock text-warning mr-1"></i>
                                You have <?php echo $unanswered_count; ?> question<?php echo $unanswered_count !== 1 ? 's' : ''; ?> 
                                pending review by an instructor.
                            </p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Detailed Results -->
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Detailed Question Analysis</h6>
            <div>
                <span class="badge badge-success badge-pill mr-2">
                    <i class="fas fa-check-circle mr-1"></i> Correct: <?php echo $correct_count; ?>
                </span>
                <span class="badge badge-danger badge-pill">
                    <i class="fas fa-times-circle mr-1"></i> Incorrect: <?php echo $incorrect_count; ?>
                </span>
                <?php if ($unanswered_count > 0): ?>
                <span class="badge badge-warning badge-pill ml-2">
                    <i class="fas fa-clock mr-1"></i> Pending: <?php echo $unanswered_count; ?>
                </span>
                <?php endif; ?>
            </div>
        </div>
        <div class="card-body">
            <!-- Questions Summary Bar -->
            <div class="mb-4 question-summary-bar">
                <?php 
                // Calculate percentages for the bar
                $correct_percent = $total_questions > 0 ? ($correct_count / $total_questions) * 100 : 0;
                $incorrect_percent = $total_questions > 0 ? ($incorrect_count / $total_questions) * 100 : 0;
                $pending_percent = $total_questions > 0 ? ($unanswered_count / $total_questions) * 100 : 0;
                ?>
                <div class="progress" style="height: 25px; border-radius: 10px;">
                    <?php if ($correct_count > 0): ?>
                    <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $correct_percent; ?>%" 
                         title="<?php echo $correct_count; ?> Correct">
                        <?php if ($correct_percent >= 10): ?>
                            <?php echo $correct_count; ?> Correct
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($incorrect_count > 0): ?>
                    <div class="progress-bar bg-danger" role="progressbar" style="width: <?php echo $incorrect_percent; ?>%" 
                         title="<?php echo $incorrect_count; ?> Incorrect">
                        <?php if ($incorrect_percent >= 10): ?>
                            <?php echo $incorrect_count; ?> Incorrect
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($unanswered_count > 0): ?>
                    <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo $pending_percent; ?>%" 
                         title="<?php echo $unanswered_count; ?> Pending">
                        <?php if ($pending_percent >= 10): ?>
                            <?php echo $unanswered_count; ?> Pending
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="text-center mt-2">
                    <span class="text-success font-weight-bold mr-3">Total Score: <?php echo $obtained_marks; ?>/<?php echo $total_marks; ?></span>
                    <?php if($percentage >= $exam['passing_percentage']): ?>
                        <span class="badge badge-success p-2"><i class="fas fa-trophy"></i> Passed!</span>
                                    <?php else: ?>
                        <span class="badge badge-secondary p-2"><i class="fas fa-exclamation-triangle"></i> Not Passed</span>
                                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Questions Accordion -->
            <div class="accordion" id="questionsAccordion">
                <?php foreach ($questions as $index => $question): ?>
                    <div class="card mb-3 border-left-<?php 
                        echo ($question['is_correct'] === 1) ? 'success' : 
                            (($question['is_correct'] === 0) ? 'danger' : 'warning'); 
                    ?> border-left-thick shadow-sm">
                        <div class="card-header bg-light position-relative" id="heading<?php echo $index; ?>">
                            <div class="d-flex justify-content-between align-items-center">
                                <h2 class="mb-0">
                                    <button class="btn btn-link btn-block text-left font-weight-bold" type="button" 
                                            data-toggle="collapse" data-target="#collapse<?php echo $index; ?>" 
                                            aria-expanded="false" aria-controls="collapse<?php echo $index; ?>">
                                        <div class="d-flex align-items-center">
                                            <div class="question-number mr-3 bg-<?php 
                                                echo ($question['is_correct'] === 1) ? 'success' : 
                                                    (($question['is_correct'] === 0) ? 'danger' : 'warning'); 
                                            ?> text-white rounded-circle">
                                                <?php echo ($index + 1); ?>
                                            </div>
                                            <div class="question-preview">
                                                <?php echo substr(htmlspecialchars($question['question_text']), 0, 100); ?>
                                                <?php if (strlen($question['question_text']) > 100) echo '...'; ?>
                                            </div>
                                        </div>
                                </button>
                            </h2>
                                <div class="score-badge">
                                    <span class="badge badge-<?php 
                                        echo ($question['is_correct'] === 1) ? 'success' : 
                                            (($question['is_correct'] === 0) ? 'danger' : 'warning'); 
                                    ?> badge-pill mr-2">
                                        <?php if ($question['is_correct'] === 1): ?>
                                            <i class="fas fa-check-circle mr-1"></i> Correct
                                        <?php elseif ($question['is_correct'] === 0): ?>
                                            <i class="fas fa-times-circle mr-1"></i> Incorrect
                                        <?php else: ?>
                                            <i class="fas fa-clock mr-1"></i> Pending
                                        <?php endif; ?>
                                    </span>
                                    
                                    <span class="badge badge-light border font-weight-bold">
                                        <?php echo $question['marks_obtained'] ?? 0; ?>/<?php echo $question['marks']; ?>
                                    </span>
                                </div>
                            </div>
                            
                            <!-- Visual indicator of score -->
                            <?php if ($question['marks'] > 0): ?>
                            <div class="progress mt-2" style="height: 5px;">
                                <div class="progress-bar bg-<?php 
                                    echo ($question['is_correct'] === 1) ? 'success' : 
                                        (($question['is_correct'] === 0) ? 'danger' : 'warning'); 
                                ?>" 
                                    role="progressbar" 
                                    style="width: <?php echo (($question['marks_obtained'] ?? 0) / $question['marks']) * 100; ?>%" 
                                    aria-valuenow="<?php echo $question['marks_obtained'] ?? 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="<?php echo $question['marks']; ?>">
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>

                        <div id="collapse<?php echo $index; ?>" class="collapse" aria-labelledby="heading<?php echo $index; ?>" data-parent="#questionsAccordion">
                            <div class="card-body">
                                <div class="question-text mb-4">
                                    <h6 class="font-weight-bold"><i class="fas fa-question-circle text-primary mr-2"></i>Question:</h6>
                                    <div class="p-3 bg-light rounded"><?php echo nl2br(htmlspecialchars($question['question_text'])); ?></div>
                                    <div class="text-muted mt-2">
                                        <small>
                                            <span class="badge badge-pill badge-light border mr-2">Type: <?php echo ucfirst($question['question_type']); ?></span>
                                            <span class="badge badge-pill badge-light border mr-2">Difficulty: <?php echo ucfirst($question['difficulty']); ?></span>
                                            <span class="badge badge-pill badge-light border">Marks: <?php echo $question['marks']; ?></span>
                                        </small>
                                    </div>
                                </div>
                                
                                <?php if ($question['question_type'] === 'multiple_choice' || $question['question_type'] === 'true_false'): ?>
                                    <!-- Multiple Choice or True/False Question -->
                                    <h6 class="font-weight-bold"><i class="fas fa-list-ul text-primary mr-2"></i>Options:</h6>
                                    <div class="options-container">
                                        <?php foreach ($question['options'] as $option): ?>
                                            <div class="option-item p-3 mb-2 rounded d-flex justify-content-between align-items-center <?php 
                                                if ($option['id'] == $question['selected_option_id'] && $option['is_correct']) {
                                                    echo 'bg-success bg-opacity-10 border border-success';
                                                } elseif ($option['id'] == $question['selected_option_id'] && !$option['is_correct']) {
                                                    echo 'bg-danger bg-opacity-10 border border-danger';
                                                } elseif ($option['is_correct']) {
                                                    echo 'bg-success bg-opacity-10 border border-success';
                                                } else {
                                                    echo 'bg-light';
                                                }
                                            ?>">
                                                <div><?php echo htmlspecialchars($option['option_text']); ?></div>
                                                <div>
                                                    <?php if ($option['id'] == $question['selected_option_id']): ?>
                                                        <span class="badge badge-primary badge-pill">
                                                            <i class="fas fa-hand-pointer mr-1"></i> Your Answer
                                                        </span>
                                                    <?php endif; ?>
                                    
                                                    <?php if ($option['is_correct']): ?>
                                                        <span class="badge badge-success badge-pill ml-2">
                                                            <i class="fas fa-check mr-1"></i> Correct Answer
                                                    </span>
                                                <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php elseif ($question['question_type'] === 'short_answer' || $question['question_type'] === 'essay'): ?>
                                    <!-- Short Answer or Essay Question -->
                                    <div class="mb-4">
                                        <h6 class="font-weight-bold"><i class="fas fa-pen text-primary mr-2"></i>Your Answer:</h6>
                                        <div class="p-3 border rounded <?php echo ($question['is_correct'] === 1) ? 'border-success' : (($question['is_correct'] === 0) ? 'border-danger' : 'border-warning'); ?>">
                                            <?php if ($question['answer_text']): ?>
                                                <?php echo nl2br(htmlspecialchars($question['answer_text'])); ?>
                                                <?php else: ?>
                                                <em class="text-muted">No answer provided</em>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                
                                <!-- Marks and explanation -->
                                <div class="row mt-4">
                                    <div class="col-md-6">
                                        <div class="p-3 bg-light rounded">
                                            <h6 class="font-weight-bold"><i class="fas fa-star text-primary mr-2"></i>Score Details:</h6>
                                            <div class="d-flex align-items-center">
                                                <div class="score-circle mr-3 <?php 
                                                    echo ($question['is_correct'] === 1) ? 'bg-success' : 
                                                        (($question['is_correct'] === 0) ? 'bg-danger' : 'bg-warning'); 
                                                ?>">
                                                    <?php echo $question['marks_obtained'] ?? 0; ?>
                                                </div>
                                                <div>
                                                    <p class="mb-1">Points earned: <strong><?php echo $question['marks_obtained'] ?? 0; ?> out of <?php echo $question['marks']; ?></strong></p>
                                                    <?php if ($question['is_correct'] !== null): ?>
                                                        <p class="mb-0 text-<?php echo $question['is_correct'] ? 'success' : 'danger'; ?>">
                                                            <?php echo $question['is_correct'] ? 'Your answer was correct!' : 'Your answer was incorrect'; ?>
                                                        </p>
                                                    <?php else: ?>
                                                        <p class="mb-0 text-warning">Awaiting instructor review</p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <?php if ($question['explanation']): ?>
                                            <div class="p-3 bg-light rounded h-100">
                                                <h6 class="font-weight-bold"><i class="fas fa-info-circle text-primary mr-2"></i>Explanation:</h6>
                                                <div>
                                                    <?php echo nl2br(htmlspecialchars($question['explanation'])); ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<style>
/* Custom styles for the results page */
.border-left-thick {
    border-left-width: 5px !important;
}

.question-number {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

.score-circle {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 18px;
}

.bg-opacity-10 {
    opacity: 0.2;
}

.chart-pie {
    position: relative;
    height: 15rem;
    width: 100%;
}

.badge-pill {
    padding-right: 0.8em;
    padding-left: 0.8em;
}

.question-preview {
    color: #5a5c69;
}

@media (max-width: 768px) {
    .border-right {
        border-right: none !important;
        border-bottom: 1px solid #e3e6f0;
        padding-bottom: 1.5rem;
        margin-bottom: 1.5rem;
    }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Set new default font family and font color to mimic Bootstrap's default styling
    Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
    Chart.defaults.global.defaultFontColor = '#858796';

    // Pie Chart for Results
    var ctx = document.getElementById("resultsPieChart");
    var myPieChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ["Correct", "Incorrect"<?php echo $unanswered_count > 0 ? ', "Pending Review"' : ''; ?>],
            datasets: [{
                data: [
                    <?php echo $correct_count; ?>, 
                    <?php echo $incorrect_count; ?>
                    <?php echo $unanswered_count > 0 ? ', ' . $unanswered_count : ''; ?>
                ],
                backgroundColor: ['#1cc88a', '#e74a3b'<?php echo $unanswered_count > 0 ? ', "#f6c23e"' : ''; ?>],
                hoverBackgroundColor: ['#17a673', '#e02d1b'<?php echo $unanswered_count > 0 ? ', "#dda20a"' : ''; ?>],
                hoverBorderColor: "rgba(234, 236, 244, 1)",
            }],
        },
        options: {
            maintainAspectRatio: false,
            tooltips: {
                backgroundColor: "rgb(255,255,255)",
                bodyFontColor: "#858796",
                borderColor: '#dddfeb',
                borderWidth: 1,
                xPadding: 15,
                yPadding: 15,
                displayColors: false,
                caretPadding: 10,
            },
            legend: {
                display: false
            },
            cutoutPercentage: 70,
        },
    });
});
</script>

<?php
// Include footer
include_once 'includes/footer.php';
?>