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

require_once 'connectiondb.php';

// Handle result approval POST request
$approval_success = '';
$approval_error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['result_approval_action'])) {
    $student_id = $_POST['student_id'] ?? '';
    $exam_id = $_POST['exam_id'] ?? '';
    $action = $_POST['result_approval_action'] ?? '';

    if (!empty($student_id) && !empty($exam_id) && in_array($action, ['approve', 'disapprove'])) {
        $result_approved = ($action === 'approve') ? 1 : 0;
        $stmtUpdate = $pdo->prepare("UPDATE student_exams SET result_approved = ? WHERE student_id = ? AND exam_id = ?");
        if ($stmtUpdate->execute([$result_approved, $student_id, $exam_id])) {
            $approval_success = "Result has been " . ($result_approved ? "approved" : "disapproved") . " successfully.";
        } else {
            $approval_error = "Failed to update the result approval status.";
        }
    } else {
        $approval_error = "Invalid data provided for result approval.";
    }
}

// Handle bulk exam assignment POST request
$assign_success = '';

$assign_error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_exam'])) {
    $selected_students = $_POST['selected_students'] ?? [];
    $exam_id_to_assign = $_POST['exam_id'] ?? '';
    if (!empty($selected_students) && !empty($exam_id_to_assign) && is_numeric($exam_id_to_assign)) {
        $placeholders = implode(',', array_fill(0, count($selected_students), '?'));
        // Check existing assignments to avoid duplicates
        $stmtCheck = $pdo->prepare("SELECT student_id FROM student_exams WHERE exam_id = ? AND student_id IN ($placeholders)");
        $stmtCheck->execute(array_merge([$exam_id_to_assign], $selected_students));
        $already_assigned = $stmtCheck->fetchAll(PDO::FETCH_COLUMN);
        $to_assign = array_diff($selected_students, $already_assigned);
        if (!empty($to_assign)) {
            $stmtInsert = $pdo->prepare("INSERT INTO student_exams (student_id, exam_id, status) VALUES (?, ?, 'assigned')");
            foreach ($to_assign as $student_id) {
                $stmtInsert->execute([$student_id, $exam_id_to_assign]);
            }
            $assign_success = "Exam assigned to " . count($to_assign) . " student(s) successfully.";
        } else {
            $assign_error = "Selected students are already assigned to this exam.";
        }
    } else {
        $assign_error = "Please select students and an exam to assign.";
    }
}


$search_term = $_GET['search'] ?? '';
$search_term = trim($search_term);

if ($search_term !== '') {
    $search_term_wildcard = '%' . $search_term . '%';
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.student_id, s.name
        FROM students s
        LEFT JOIN student_exams se ON s.id = se.student_id
        LEFT JOIN exams e ON se.exam_id = e.id
        WHERE s.student_id LIKE ? OR s.name LIKE ? OR e.exam_name LIKE ?
        ORDER BY s.name
    ");
    $stmt->execute([$search_term_wildcard, $search_term_wildcard, $search_term_wildcard]);
} else {
    $stmt = $pdo->query("SELECT id, student_id, name FROM students ORDER BY name");
}
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch exams taken by students with exam IDs
$student_ids = array_column($students, 'id');
$exams_taken = [];
if (!empty($student_ids)) {
    $placeholders = implode(',', array_fill(0, count($student_ids), '?'));
    $stmt2 = $pdo->prepare("
        SELECT se.student_id, e.id as exam_id, e.exam_name
        FROM student_exams se
        JOIN exams e ON se.exam_id = e.id
        WHERE se.student_id IN ($placeholders) AND se.status = 'completed'
        ORDER BY e.exam_name
    ");
    $stmt2->execute($student_ids);
    $rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $row) {
        $exams_taken[$row['student_id']][] = ['exam_id' => $row['exam_id'], 'exam_name' => $row['exam_name']];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>All Students - MCQ Exam Portal</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet"/>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>All Students</h2>
    <?php if($assign_error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($assign_error); ?></div>
    <?php endif; ?>
    <?php if($assign_success): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($assign_success); ?></div>
    <?php endif; ?>
    <?php if(empty($students)): ?>
        <p>No students found.</p>
    <?php else: ?>
        <form method="GET" action="admin_all_students.php" class="mb-3">
            <div class="input-group">
                <input type="text" name="search" class="form-control" placeholder="Search by Student ID or Name" value="<?php echo htmlspecialchars($search_term); ?>" />
                <button type="submit" class="btn btn-primary">Search</button>
            </div>
        </form>
        <form method="POST" action="admin_all_students.php">
        <table id="students_table" class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select_all" /></th>
                    <th>Student ID</th>
                    <th>Name</th>
                    <th>Exams Taken</th>
                    <th>View Responses</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['id']); ?>" class="student_checkbox" /></td>
                    <td><?php echo htmlspecialchars($student['student_id']); ?></td>
                    <td><?php echo htmlspecialchars($student['name']); ?></td>
                    <td>
                        <?php
                        if (isset($exams_taken[$student['id']])) {
                            $exam_names = array_map(function($exam) {
                                return $exam['exam_name'];
                            }, $exams_taken[$student['id']]);
                            echo htmlspecialchars(implode(', ', $exam_names));
                        } else {
                            echo '<em>None</em>';
                        }
                        ?>
                    </td>
<td>
    <?php if (isset($exams_taken[$student['id']]) && count($exams_taken[$student['id']]) > 0): ?>
        <?php foreach ($exams_taken[$student['id']] as $exam): ?>
            <div class="mb-1">
                <a href="view_student_responses.php?student_id=<?php echo urlencode($student['id']); ?>&exam_id=<?php echo urlencode($exam['exam_id']); ?>" class="btn btn-sm btn-info me-1">
                    <?php echo htmlspecialchars($exam['exam_name']); ?>
                </a>
                <!--<a href="admin_edit_answers.php?student_id=<?php echo urlencode($student['student_id']); ?>&exam_id=<?php echo urlencode($exam['exam_id']); ?>" class="btn btn-sm btn-warning">-->
                <!--    EA-->
                <!--</a>-->
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <span class="text-muted">No exams</span>
    <?php endif; ?>
</td>
                    <td>
                        <a href="edit_student.php?student_id=<?php echo urlencode($student['id']); ?>" class="btn btn-sm btn-primary ms-1">Edit</a>
                        <a href="delete_student.php?student_id=<?php echo urlencode($student['id']); ?>" class="btn btn-sm btn-danger ms-1" onclick="return confirm('Are you sure you want to delete this student? This action cannot be undone.');">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="mb-3">
            <label for="exam_id" class="form-label">Assign Exam to Selected Students:</label>
            <select name="exam_id" id="exam_id" class="form-select" required>
                <option value="">Select Exam</option>
                <?php
                $stmtExams = $pdo->query("SELECT id, exam_name FROM exams ORDER BY exam_name");
                $exams = $stmtExams->fetchAll(PDO::FETCH_ASSOC);
                foreach ($exams as $exam) {
                    echo '<option value="' . htmlspecialchars($exam['id']) . '">' . htmlspecialchars($exam['exam_name']) . '</option>';
                }
                ?>
            </select>
        </div>
        <button type="submit" name="assign_exam" class="btn btn-primary">Assign Exam</button>
        </form>
    <?php endif; ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script>
document.getElementById('select_all').addEventListener('change', function() {
    var checkboxes = document.querySelectorAll('.student_checkbox');
    for (let checkbox of checkboxes) {
        checkbox.checked = this.checked;
    }
});
$(document).ready(function() {
    $('#students_table').DataTable({
        "order": [[1, "asc"]],
        "columnDefs": [
            { "orderable": false, "targets": [0, 4, 5] }
        ]
    });
});
</script>
</body>
</html>
