<?php
session_start();
if(isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">



    <?php include 'includes/styles.php';  global $school_name; ?>
    <title> View student exam result |    <?php echo $school_name; ?> </title>

    <?php
    $module_name = 'Mark';
    include "check-admin-privilege.php";
    ?>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"> View student exam result</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                            <li class="breadcrumb-item active">View exam results</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

            <div class="row">
                    <div class="col-md-10">
                        <div class="card card-info">
                            <div class="card-header">

                                <?php
                                // Fetch the exam id

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

                                // Fetch Exam Details
                                $conn->query("SELECT * FROM cbt_exams WHERE id = :exam_id");
                                $conn->bind(":exam_id", $exam_id);
                                $exam = $conn->fetchSingle();

                                // Fetch Student Answers & Score
                                $conn->query("
                                    SELECT q.id AS question_id, q.question_text, q.explanation, sa.answer AS student_answer, 
                                           o.option_text AS correct_answer, sa.is_correct
                                    FROM cbt_student_answers sa
                                    JOIN cbt_questions q ON sa.question_id = q.id
                                    JOIN cbt_options o ON q.id = o.question_id AND o.is_correct = 1
                                    WHERE sa.student_id = :student_id AND sa.exam_id = :exam_id
                                ");
                                $conn->bind(":student_id", $student_id);
                                $conn->bind(":exam_id", $exam_id);
                                $answers = $conn->fetchMultiple();

                                // Calculate total score
                                $total_questions = count($answers);
                                $correct_answers = array_sum(array_column($answers, 'is_correct'));
                                $score_percentage = ($total_questions > 0) ? round(($correct_answers / $total_questions) * 100, 2) : 0;

                                // Save result in cbt_results if not already stored
                                $conn->query("SELECT COUNT(*) FROM cbt_results WHERE student_id = :student_id AND exam_id = :exam_id");
                                $conn->bind(":student_id", $student_id);
                                $conn->bind(":exam_id", $exam_id);
                                $result_exists = $conn->fetchColumn();

                                if (!$result_exists) {
                                    $conn->query("INSERT INTO cbt_results (student_id, exam_id, total_questions, correct_answers, score_percentage)
                                            VALUES (:student_id, :exam_id, :total_questions, :correct_answers, :score_percentage)");
                                    $conn->bind(":student_id", $student_id);
                                    $conn->bind(":exam_id", $exam_id);
                                    $conn->bind(":total_questions", $total_questions);
                                    $conn->bind(":correct_answers", $correct_answers);
                                    $conn->bind(":score_percentage", $score_percentage);
                                    $conn->execute();
                                }



                                ?>
                            </div>

                                <div class="card-body">

                                    <div class="result-container">
                                        <h2><?php echo htmlspecialchars($exam->title); ?> - Exam Results</h2>
                                        <p><strong>Total Questions:</strong> <?php echo $total_questions; ?></p>
                                        <p><strong>Correct Answers:</strong> <?php echo $correct_answers; ?></p>
                                        <p><strong>Score Percentage:</strong> <?php echo $score_percentage; ?>%</p>

                                        <h3>Review Your Answers</h3>
                                        <?php foreach ($answers as $answer) : ?>
                                            <div class="question-box">
                                                <p><strong>Q:</strong> <?php echo htmlspecialchars($answer->question_text); ?></p>
                                                <p class="<?php echo ($answer->is_correct) ? 'correct' : 'incorrect'; ?>">
                                                    <strong>Your Answer:</strong> <?php echo htmlspecialchars($answer->student_answer); ?>
                                                </p>
                                                <p><strong>Correct Answer:</strong> <?php echo htmlspecialchars($answer->correct_answer); ?></p>

                                                <?php if (!empty($answer->explanation)) : ?>
                                                    <p class="explanation"><strong>Explanation:</strong> <?php echo htmlspecialchars($answer->explanation); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>

                                        <a href="<?php echo $conn->base_url();?>">Back to Dashboard</a>
                                    </div>

                                    <style>
                                        .result-container { max-width: 800px; margin: auto; padding: 20px; background: #fff; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
                                        .question-box { margin-bottom: 20px; padding: 10px; border-left: 5px solid #ddd; }
                                        .correct { color: green; font-weight: bold; }
                                        .incorrect { color: red; font-weight: bold; }
                                        .explanation { background: #f9f9f9; padding: 10px; border-left: 3px solid #ffa500; }
                                    </style>
                                </div>
                        </div>
                        <!-- /.card -->
                    </div>
                </div>



        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "includes/footer.php";?>

   

    <?php
     
      //submit form

    ?>

    <script>
        if ( window.history.replaceState ) {
            window.history.replaceState( null, null, window.location.href );
        }
    </script>

    <?php
    }else{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
        <title>Login to continue |    <?php echo $school_name; ?></title>

        <?php include 'includes/styles.php'; ?>
        <?php
        $link = $conn->base_url().'login';
        ?>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>
    

    <?php
    }

    ?>
