<?php
session_start();
require_once "inc/connect.php"; // Make sure this includes $mysqli

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents("php://input"), true);
    $exam_id = trim($input['exam_id'] ?? '');

    if ($exam_id === '') {
        echo json_encode([]);
        exit;
    }

    $query = "
        SELECT 
            s.serial AS student_serial,
            CONCAT(s.surname, ' ', s.middlename, ' ', s.lastname) AS full_name,
            s.school_id,
            tm.token_id,
            tm.examination_id,
            et.examination_title,
            COALESCE(qs.total_questions, 0) AS total_questions,
            COALESCE(sal.total_score, 0) AS total_score,
            ROUND((COALESCE(sal.total_score, 0) / NULLIF(COALESCE(qs.total_questions, 0), 0)) * 100, 2) AS percentage
        FROM token_management tm
        LEFT JOIN student_table s ON s.serial = tm.student_id
        LEFT JOIN examination_table et ON et.examination_id = tm.examination_id

        LEFT JOIN (
            SELECT token_id, COUNT(*) AS total_questions
            FROM question_set
            GROUP BY token_id
        ) qs ON qs.token_id = tm.token_id

        LEFT JOIN (
            SELECT token_id, SUM(score) AS total_score
            FROM student_attempt_log
            WHERE status = 'open'
            GROUP BY token_id
        ) sal ON sal.token_id = tm.token_id

        WHERE tm.examination_id = ?
        ORDER BY s.surname ASC, tm.token_id ASC
    ";

    $stmt = $mysqli->prepare($query);
    $stmt->bind_param("s", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    echo json_encode($data);
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Exam Results</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">

</head>
<body class="hold-transition">

<div class="wrapper">
    <h2 class="mb-4">View Exam Results</h2>

    <form id="examForm" class="row g-3 mb-4">
  


<div class="col-md-6">
    <label for="exam_id" class="form-label">Select Examination</label>

    <select class="form-control" id="exam_id" required>
        <option value="">-- Select Examination --</option>

        <?php
        $examQuery = $mysqli->query("
            SELECT examination_id, examination_title
            FROM examination_table
            ORDER BY examination_title ASC
        ");

        while($exam = $examQuery->fetch_assoc()):
        ?>
            <option value="<?= htmlspecialchars($exam['examination_id']) ?>">
                <?= htmlspecialchars($exam['examination_title']) ?>
                (<?= htmlspecialchars($exam['examination_id']) ?>)
            </option>
        <?php endwhile; ?>
    </select>
</div>
		
		
		
		
		
        <div class="col-md-3 align-self-end">
            <button type="submit" class="btn btn-primary">Fetch Results</button>
        </div>
    </form>

    <div id="resultArea" class="table-responsive" style="display:none;">

       <h2  id='hasde'></h2>	
 
		<table class="table table-bordered table-hover">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th>Student Name</th>
                    <th>School ID</th>
                    <th>Token ID</th>
                    <th>Total Questions</th>
                    <th>Score</th>
                    <th>Percentage</th>
                </tr>
            </thead>
            <tbody id="resultTable"></tbody>
        </table>
    </div>

    <div id="noResults" class="alert alert-warning" style="display:none;">No results found.</div>

  </div>


<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>




    <script>
    document.getElementById("examForm").addEventListener("submit", function(e) {
        e.preventDefault();
        const exam_id = document.getElementById("exam_id").value.trim();
        if (!exam_id) return;
		var bbbdh = '';
        fetch("exam_result.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-Requested-With": "fetch"
            },
            body: JSON.stringify({ exam_id })
        })
        .then(res => res.json())
        .then(data => {
            const tableBody = document.getElementById("resultTable");
            tableBody.innerHTML = "";
            if (data.length > 0) {
				
				

                data.forEach((row, index) => {
                    tableBody.innerHTML += `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${row.full_name}</td>
                            <td>${row.school_id}</td>
                            <td>${row.token_id}</td>
                            <td>${row.total_questions}</td>
                            <td>${row.total_score}</td>
                            <td>${row.percentage ?? 0}%</td>
                        </tr>
                    `;
					
					bbbdh = row.examination_title;
                });
                document.getElementById("resultArea").style.display = "block";
                document.getElementById("noResults").style.display = "none";
				
				document.getElementById("hasde").innerHTML = bbbdh;

            } else {
                document.getElementById("resultArea").style.display = "none";
                document.getElementById("noResults").style.display = "block";
            }
        })
        .catch(err => {
            console.error("Error:", err);
            document.getElementById("resultArea").style.display = "none";
            document.getElementById("noResults").style.display = "block";
        });
    });
    </script>
</body>
</html>
