<?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';

$exam_id = $_GET['exam_id'] ?? '';
if(empty($exam_id) || !is_numeric($exam_id)){
    die("Invalid exam ID.");
}

// Handle transfer student POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['transfer_student'])) {
        $student_id = $_POST['student_id'] ?? '';
        $new_exam_id = $_POST['new_exam_id'] ?? '';
        if (!empty($student_id) && !empty($new_exam_id) && is_numeric($student_id) && is_numeric($new_exam_id)) {
            // Check if student already assigned to new exam
            $stmtCheck = $pdo->prepare("SELECT id FROM student_exams WHERE student_id = ? AND exam_id = ?");
            $stmtCheck->execute([$student_id, $new_exam_id]);
            if ($stmtCheck->fetch()) {
                $transfer_error = "Student is already assigned to the selected exam.";
            } else {
                // Update student_exams to new exam
                $stmtUpdate = $pdo->prepare("UPDATE student_exams SET exam_id = ?, status = 'assigned', completed_at = NULL WHERE student_id = ? AND exam_id = ?");
                $stmtUpdate->execute([$new_exam_id, $student_id, $exam_id]);
                $transfer_success = "Student transferred successfully.";
            }
        } else {
            $transfer_error = "Invalid student or exam selection.";
        }
    } elseif (isset($_POST['remove_student'])) {
        $student_id = $_POST['student_id'] ?? '';
        if (!empty($student_id) && is_numeric($student_id)) {
            // Delete student exam assignment
            $stmtDelete = $pdo->prepare("DELETE FROM student_exams WHERE student_id = ? AND exam_id = ?");
            $stmtDelete->execute([$student_id, $exam_id]);
            if ($stmtDelete->rowCount() > 0) {
                $remove_success = "Student removed from exam successfully.";
            } else {
                $remove_error = "Failed to remove student from exam.";
            }
        } else {
            $remove_error = "Invalid student selection.";
        }
    } elseif (isset($_POST['approve_result'])) {
        $student_id = $_POST['student_id'] ?? '';
        $approve = $_POST['approve'] ?? '0';
        if (!empty($student_id) && is_numeric($student_id)) {
            $approve_val = $approve === '1' ? 1 : 0;
            $stmtApprove = $pdo->prepare("UPDATE student_exams SET result_approved = ? WHERE student_id = ? AND exam_id = ?");
            $stmtApprove->execute([$approve_val, $student_id, $exam_id]);
            $approve_success = "Result approval status updated.";
        } else {
            $approve_error = "Invalid student selection for approval.";
        }
    } elseif (isset($_POST['bulk_approve'])) {
        $selected_students = $_POST['selected_students'] ?? [];
        $bulk_exam_id = $_POST['bulk_exam_id'] ?? '';
        if (!empty($selected_students) && is_array($selected_students) && !empty($bulk_exam_id) && is_numeric($bulk_exam_id)) {
            $placeholders = implode(',', array_fill(0, count($selected_students), '?'));
            $params = array_merge([1], $selected_students, [$bulk_exam_id]);
            $stmtBulkApprove = $pdo->prepare("UPDATE student_exams SET result_approved = ? WHERE student_id IN ($placeholders) AND exam_id = ?");
            $stmtBulkApprove->execute($params);
            $approve_success = "Selected results approved successfully.";
        } else {
            $approve_error = "No students selected or exam not selected for bulk approval.";
        }
    } elseif (isset($_POST['bulk_disapprove'])) {
        $selected_students = $_POST['selected_students'] ?? [];
        $bulk_exam_id = $_POST['bulk_exam_id'] ?? '';
        if (!empty($selected_students) && is_array($selected_students) && !empty($bulk_exam_id) && is_numeric($bulk_exam_id)) {
            $placeholders = implode(',', array_fill(0, count($selected_students), '?'));
            $params = array_merge([0], $selected_students, [$bulk_exam_id]);
            $stmtBulkDisapprove = $pdo->prepare("UPDATE student_exams SET result_approved = ? WHERE student_id IN ($placeholders) AND exam_id = ?");
            $stmtBulkDisapprove->execute($params);
            $approve_success = "Selected results disapproved successfully.";
        } else {
            $approve_error = "No students selected or exam not selected for bulk disapproval.";
        }
    }
}

// Fetch exam details
$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$exam){
    die("Exam not found.");
}

// Fetch students assigned to the exam
$stmt = $pdo->prepare("
    SELECT s.id AS student_id, s.student_id AS student_code, s.name, se.status, se.completed_at, se.start_time, 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);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Exam Students - <?php echo htmlspecialchars($exam['exam_name']); ?></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>Students Assigned to Exam: <?php echo htmlspecialchars($exam['exam_name']); ?></h2>
    <a href="edit_exam.php?exam_id=<?php echo $exam['id']; ?>" class="btn btn-primary mb-3">Edit Exam</a>

    <?php if (!empty($transfer_error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($transfer_error); ?></div>
    <?php endif; ?>
    <?php if (!empty($transfer_success)): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($transfer_success); ?></div>
    <?php endif; ?>
    <?php if (!empty($remove_error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($remove_error); ?></div>
    <?php endif; ?>
    <?php if (!empty($remove_success)): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($remove_success); ?></div>
    <?php endif; ?>
    <?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)): ?>
        <p>No students assigned to this exam.</p>
    <?php else: ?>
        <?php
        // Fetch all exams for transfer dropdown
        $stmt2 = $pdo->query("SELECT id, exam_name FROM exams ORDER BY exam_name");
        $all_exams = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        ?>
        <form method="POST" action="admin_exam_students.php?exam_id=<?php echo $exam['id']; ?>" onsubmit="return confirm('Are you sure you want to approve results for selected students?');">
        <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>Status</th>
                    
                  
                    <th>Result Approved</th>
                    <th>Actions</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 htmlspecialchars($student['status']); ?></td>
            
                   
                    <td>
                        <?php echo $student['result_approved'] ? 'Approved' : 'Not Approved'; ?>
                    </td>
                    <td>
                        <form method="POST" action="admin_exam_students.php?exam_id=<?php echo $exam['id']; ?>" onsubmit="return confirm('Are you sure you want to transfer this student to the selected exam?');" style="display:inline-block;">
                            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student['student_id']); ?>">
                            <select name="new_exam_id" class="form-select form-select-sm" required>
                                <option value="">Select Exam</option>
                                <?php foreach($all_exams as $ex): ?>
                                    <?php if($ex['id'] != $exam['id']): ?>
                                    <option value="<?php echo htmlspecialchars($ex['id'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($ex['exam_name'], ENT_QUOTES, 'UTF-8'); ?></option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" name="transfer_student" class="btn btn-sm btn-warning mt-1">Transfer</button>
                        </form>
                        <a href="view_student_responses.php?student_id=<?php echo urlencode($student['student_id']); ?>&exam_id=<?php echo urlencode($exam['id']); ?>" class="btn btn-sm btn-info ms-1">View Responses</a>
                        <a href="view_student_responses.php?student_id=<?php echo urlencode($student['student_id']); ?>&exam_id=<?php echo urlencode($exam['id']); ?>&print=1" target="_blank" class="btn btn-sm btn-primary ms-1">Print Responses</a>
                        <form method="POST" action="admin_exam_students.php?exam_id=<?php echo $exam['id']; ?>" style="display:inline-block;" onsubmit="return confirm('Are you sure you want to approve this result?');">
                            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student['student_id']); ?>">
                            <input type="hidden" name="approve" value="1">
                            <button type="submit" name="approve_result" class="btn btn-sm btn-success ms-1">Approve</button>
                        </form>
                        <form method="POST" action="admin_exam_students.php?exam_id=<?php echo $exam['id']; ?>" style="display:inline-block;" onsubmit="return confirm('Are you sure you want to disapprove this result?');">
                            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student['student_id']); ?>">
                            <input type="hidden" name="approve" value="0">
                            <button type="submit" name="approve_result" class="btn btn-sm btn-secondary ms-1">Disapprove</button>
                        </form>
                        <form method="POST" action="admin_exam_students.php?exam_id=<?php echo $exam['id']; ?>" style="display:inline-block;" onsubmit="return confirm('Are you sure you want to remove this student from the exam?');">
                            <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student['student_id']); ?>">
                            <button type="submit" name="remove_student" class="btn btn-sm btn-danger ms-1">Remove</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="d-flex align-items-center mt-2">
            <select name="bulk_exam_id" class="form-select w-auto me-2" required>
                <option value="">Select Exam for Bulk Approval</option>
                <?php foreach($all_exams as $ex): ?>
                    <option value="<?php echo htmlspecialchars($ex['id'], ENT_QUOTES, 'UTF-8'); ?>">
                        <?php echo htmlspecialchars($ex['exam_name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" name="bulk_approve" class="btn btn-primary me-2">Approve Selected Results</button>
            <button type="submit" name="bulk_disapprove" class="btn btn-secondary">Disapprove Selected Results</button>
        </div>
        </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_dashboard.php" class="btn btn-secondary mt-3">Back to Dashboard</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
