<?php
session_start();
if (!isset($_SESSION['student_id'])) {
    header('Location: student_login.php');
    exit;
}

$student_id = $_SESSION['student_id'];

require_once 'connectiondb.php';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Fetch completed exams for the student
    $stmt = $pdo->prepare("
        SELECT e.id AS exam_id, e.exam_name, se.start_time, se.completed_at, se.attempts
        FROM exams e
        JOIN student_exams se ON e.id = se.exam_id
        WHERE se.student_id = ? AND se.status = 'completed' AND se.result_approved = 1
        ORDER BY e.id, se.start_time
    ");
    $stmt->execute([$student_id]);
    $completed_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

function calculate_score($pdo, $student_id, $exam_id) {
    // Get total questions count
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM questions WHERE exam_id = ?");
    $stmt->execute([$exam_id]);
    $total_questions = (int)$stmt->fetchColumn();

    if ($total_questions === 0) {
        return [0, 0];
    }

    // Get count of correct answers by comparing selected_option_id with correct option
    $stmt = $pdo->prepare("
        SELECT COUNT(*) FROM student_answers sa
        JOIN questions q ON sa.question_id = q.id
        JOIN options o ON sa.selected_option_id = o.id
        WHERE sa.student_id = ? AND q.exam_id = ? AND o.is_correct = 1
    ");
    $stmt->execute([$student_id, $exam_id]);
    $correct_answers = (int)$stmt->fetchColumn();

    return [$correct_answers, $total_questions];
}

function get_grade($percentage) {
    if ($percentage >= 0 && $percentage <= 40) {
        return ['Below Average', 'C'];
    } elseif ($percentage >= 41 && $percentage <= 60) {
        return ['Average', 'B'];
    } elseif ($percentage >= 61 && $percentage <= 70) {
        return ['Good', 'B+'];
    } elseif ($percentage >= 71 && $percentage <= 80) {
        return ['Very Good', 'A'];
    } elseif ($percentage >= 81 && $percentage <= 90) {
        return ['Excellent', 'A+'];
    } elseif ($percentage >= 91 && $percentage <= 100) {
        return ['Outstanding', 'O'];
    } else {
        return ['N/A', 'N/A'];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Student Results</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="student_dashboard.php">MCQ Exam Portal</a>
    <div class="d-flex align-items-center">
      <a href="student_logout.php" class="btn btn-outline-light btn-sm">Logout</a>
    </div>
  </div>
</nav>
<div class="container my-4">
    <h2 class="mb-4">Your Exam Results</h2>
    <?php if (empty($completed_exams)): ?>
        <p>You have not completed any exams yet.</p>
    <?php else: ?>
        <?php
        // Group attempts by exam_id
        $grouped_exams = [];
        foreach ($completed_exams as $attempt) {
            $grouped_exams[$attempt['exam_id']][] = $attempt;
        }
        ?>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Exam Name</th>
                    
                    <th>Total Questions</th>
                    <th>Correct Answers</th>
                    <th>Score (%)</th>
                  
                    <th>Grade</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($grouped_exams as $exam_id => $attempts): ?>
                    <?php
                    $exam_name = htmlspecialchars($attempts[0]['exam_name']);
                    $rowspan = count($attempts);
                    ?>
                    <?php foreach ($attempts as $index => $attempt): 
                        list($correct, $total) = calculate_score($pdo, $student_id, $exam_id);
                        $percentage = $total > 0 ? round(($correct / $total) * 100, 2) : 0;
                        $time_taken = 'N/A';
                        if (!empty($attempt['start_time']) && !empty($attempt['completed_at'])) {
                            $start_dt = new DateTime($attempt['start_time']);
                            $completed_dt = new DateTime($attempt['completed_at']);
                            $interval = $start_dt->diff($completed_dt);
                            $time_taken = $interval->format('%h hours %i minutes %s seconds');
                        }
                        list($grade_desc, $grade_letter) = get_grade($percentage);
                    ?>
                    <tr>
                        <?php if ($index === 0): ?>
                            <td rowspan="<?php echo $rowspan; ?>"><?php echo $exam_name; ?></td>
                        <?php endif; ?>
                      
                        <td><?php echo $total; ?></td>
                        <td><?php echo $correct; ?></td>
                        <td><?php echo $percentage; ?>%</td>
                      
                        <td><?php echo  $grade_letter ; ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    <div class="container my-4">
        <h4>Grading Criteria</h4>
        <ul>
            <li>0-40% = Below Average (C)</li>
            <li>41-60% = Average (B)</li>
            <li>61-70% = Good (B+)</li>
            <li>71-80% = Very Good (A)</li>
            <li>81-90% = Excellent (A+)</li>
            <li>91-100% = Outstanding (O)</li>
        </ul>
    </div>
</div>
</body>
</html>
