<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
if(!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true){
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

$selected_exam_id = $_POST['exam_id'] ?? '';
$students = [];
$approve_success = '';
$approve_error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['load_students'])) {
    if (!empty($selected_exam_id) && is_numeric($selected_exam_id)) {
        $stmt = $pdo->prepare("
            SELECT s.id AS student_id, s.student_id AS student_code, s.name, se.result_approved
            FROM student_exams se
            JOIN students s ON se.student_id = s.id
            WHERE se.exam_id = ?
            ORDER BY s.name
        ");
        $stmt->execute([$selected_exam_id]);
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $approve_error = "Please select a valid exam.";
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['bulk_approve']) || isset($_POST['bulk_disapprove']))) {
    $selected_students = $_POST['selected_students'] ?? [];
    $exam_id = $_POST['exam_id'] ?? '';
    if (!empty($selected_students) && is_array($selected_students) && !empty($exam_id) && is_numeric($exam_id)) {
        $approve_val = isset($_POST['bulk_approve']) ? 1 : 0;
        $placeholders = implode(',', array_fill(0, count($selected_students), '?'));
        $params = array_merge([$approve_val], $selected_students, [$exam_id]);
        $stmtBulk = $pdo->prepare("UPDATE student_exams SET result_approved = ? WHERE student_id IN ($placeholders) AND exam_id = ?");
        $stmtBulk->execute($params);
        $approve_success = "Selected results updated successfully.";

        // Reload students after update
        $stmt = $pdo->prepare("
            SELECT s.id AS student_id, s.student_id AS student_code, s.name, se.result_approved
            FROM student_exams se
            JOIN students s ON se.student_id = s.id
            WHERE se.exam_id = ?
            ORDER BY s.name
        ");
        $stmt->execute([$exam_id]);
        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $selected_exam_id = $exam_id;
    } else {
        $approve_error = "No students selected or exam not selected.";
    }
}

// Fetch all exams for dropdown
$stmt2 = $pdo->query("SELECT id, exam_name FROM exams ORDER BY exam_name");
$all_exams = $stmt2->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Bulk Result Approval</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Bulk Result Approval</h2>
    <form method="POST" action="bulk_result_approve.php" class="mb-3">
        <div class="row g-2 align-items-center">
            <div class="col-auto">
                <label for="exam_id" class="col-form-label">Select Exam:</label>
            </div>
            <div class="col-auto">
                <select name="exam_id" id="exam_id" class="form-select" required>
                    <option value="">Select Exam</option>
                    <?php foreach($all_exams as $ex): ?>
                        <option value="<?php echo htmlspecialchars($ex['id'], ENT_QUOTES, 'UTF-8'); ?>" <?php if($ex['id'] == $selected_exam_id) echo 'selected'; ?>>
                            <?php echo htmlspecialchars($ex['exam_name'], ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" name="load_students" class="btn btn-primary">Load Students</button>
            </div>
        </div>
    </form>

    <?php if (!empty($approve_error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($approve_error); ?></div>
    <?php endif; ?>
    <?php if (!empty($approve_success)): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($approve_success); ?></div>
    <?php endif; ?>

    <?php if (!empty($students)): ?>
    <form method="POST" action="bulk_result_approve.php" onsubmit="return confirm('Are you sure you want to update the approval status for selected students?');">
        <input type="hidden" name="exam_id" value="<?php echo htmlspecialchars($selected_exam_id); ?>">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select_all"></th>
                    <th>Student Code</th>
                    <th>Name</th>
                    <th>Result Approved</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($students as $student): ?>
                <tr>
                    <td><input type="checkbox" name="selected_students[]" value="<?php echo htmlspecialchars($student['student_id']); ?>"></td>
                    <td><?php echo htmlspecialchars($student['student_code']); ?></td>
                    <td><?php echo htmlspecialchars($student['name']); ?></td>
                    <td><?php echo $student['result_approved'] ? 'Approved' : 'Not Approved'; ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <button type="submit" name="bulk_approve" class="btn btn-success me-2">Approve Selected</button>
        <button type="submit" name="bulk_disapprove" class="btn btn-danger">Disapprove Selected</button>
    </form>
    <script>
        document.getElementById('select_all').addEventListener('change', function() {
            var checkboxes = document.querySelectorAll('input[name="selected_students[]"]');
            for (var checkbox of checkboxes) {
                checkbox.checked = this.checked;
            }
        });
    </script>
    <?php endif; ?>
    <a href="admin_exam_students.php?exam_id=<?php echo htmlspecialchars($selected_exam_id); ?>" class="btn btn-secondary mt-3">Back to Exam Students</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
