Debugging version

This commit is contained in:
Flatlogic Bot 2025-11-26 13:37:47 +00:00
parent 4db23e4317
commit c693b9a3c9
17 changed files with 641 additions and 354 deletions

View File

@ -4,37 +4,72 @@ require_once __DIR__ . '/db/config.php';
$message = ''; $message = '';
$error = ''; $error = '';
$editing_class = null;
$school_id = $_SESSION['school_id']; $school_id = $_SESSION['school_id'];
// Handle POST request to add a new class $pdo = db();
// Handle Delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
try {
$delete_id = $_POST['delete_id'];
$stmt = $pdo->prepare("DELETE FROM classes WHERE id = ? AND school_id = ?");
$stmt->execute([$delete_id, $school_id]);
$message = "Class deleted successfully.";
} catch (PDOException $e) {
$error = "Error deleting class: " . $e->getMessage();
}
}
// Handle POST request to add or update a class
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['class_name'])) { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['class_name'])) {
$className = trim($_POST['class_name']); $className = trim($_POST['class_name']);
$class_id = $_POST['class_id'] ?? null;
if (empty($className)) { if (empty($className)) {
$error = 'Class name cannot be empty.'; $error = 'Class name cannot be empty.';
} else { } else {
try { // Check for duplicates before inserting/updating
$pdo = db(); $stmt = $pdo->prepare("SELECT id FROM classes WHERE name = ? AND school_id = ? AND id != ?");
$stmt = $pdo->prepare("INSERT INTO classes (name, school_id) VALUES (?, ?)"); $stmt->execute([$className, $school_id, $class_id ?? 0]);
if ($stmt->execute([$className, $school_id])) { if ($stmt->fetch()) {
$message = "Class '" . htmlspecialchars($className) . "' created successfully!"; $error = "Error: Class '" . htmlspecialchars($className) . "' already exists.";
} else { } else {
$error = 'Failed to create class.'; try {
} if ($class_id) {
} catch (PDOException $e) { // Update existing class
if ($e->errorInfo[1] == 1062) { // Duplicate entry $stmt = $pdo->prepare("UPDATE classes SET name = ? WHERE id = ? AND school_id = ?");
$error = "Error: Class '" . htmlspecialchars($className) . "' already exists."; $stmt->execute([$className, $class_id, $school_id]);
} else { $message = "Class updated successfully!";
} else {
// Insert new class
$stmt = $pdo->prepare("INSERT INTO classes (name, school_id) VALUES (?, ?)");
$stmt->execute([$className, $school_id]);
$message = "Class created successfully!";
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage(); $error = 'Database error: ' . $e->getMessage();
} }
} }
} }
} }
// Handle Edit request
if (isset($_GET['edit_id'])) {
try {
$edit_id = $_GET['edit_id'];
$stmt = $pdo->prepare("SELECT * FROM classes WHERE id = ? AND school_id = ?");
$stmt->execute([$edit_id, $school_id]);
$editing_class = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = "Error fetching class: " . $e->getMessage();
}
}
// Fetch all classes to display // Fetch all classes to display
$classes = []; $classes = [];
try { try {
$pdo = db(); $classes_stmt = $pdo->prepare("SELECT * FROM classes WHERE school_id = ? ORDER BY name ASC");
$classes_stmt = $pdo->prepare("SELECT id, name, created_at FROM classes WHERE school_id = ? ORDER BY created_at DESC");
$classes_stmt->execute([$school_id]); $classes_stmt->execute([$school_id]);
$classes = $classes_stmt->fetchAll(PDO::FETCH_ASSOC); $classes = $classes_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
@ -70,6 +105,7 @@ try {
<ul class="dropdown-menu" aria-labelledby="manageDropdown"> <ul class="dropdown-menu" aria-labelledby="manageDropdown">
<li><a class="dropdown-item active" href="/admin_classes.php">Classes</a></li> <li><a class="dropdown-item active" href="/admin_classes.php">Classes</a></li>
<li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li> <li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li>
<li><a class="dropdown-item" href="/admin_elective_groups.php">Elective Groups</a></li>
<li><a class="dropdown-item" href="/admin_teachers.php">Teachers</a></li> <li><a class="dropdown-item" href="/admin_teachers.php">Teachers</a></li>
<li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li> <li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li>
<li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li> <li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li>
@ -100,16 +136,20 @@ try {
<div class="alert alert-danger"><?php echo $error; ?></div> <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?> <?php endif; ?>
<!-- Create Class Form --> <!-- Create/Edit Class Form -->
<div class="card mb-4"> <div class="card mb-4">
<div class="card-body"> <div class="card-body">
<h5 class="card-title">Create a New Class</h5> <h5 class="card-title"><?php echo $editing_class ? 'Edit Class' : 'Create a New Class'; ?></h5>
<form action="admin_classes.php" method="POST"> <form action="admin_classes.php" method="POST">
<input type="hidden" name="class_id" value="<?php echo $editing_class['id'] ?? ''; ?>">
<div class="mb-3"> <div class="mb-3">
<label for="class_name" class="form-label">Class Name</label> <label for="class_name" class="form-label">Class Name</label>
<input type="text" class="form-control" id="class_name" name="class_name" placeholder="e.g., Form 1 North" required> <input type="text" class="form-control" id="class_name" name="class_name" value="<?php echo htmlspecialchars($editing_class['name'] ?? ''); ?>" placeholder="e.g., Form 1 North" required>
</div> </div>
<button type="submit" class="btn btn-primary">Create Class</button> <button type="submit" class="btn btn-primary"><?php echo $editing_class ? 'Update Class' : 'Create Class'; ?></button>
<?php if ($editing_class): ?>
<a href="admin_classes.php" class="btn btn-secondary">Cancel Edit</a>
<?php endif; ?>
</form> </form>
</div> </div>
</div> </div>
@ -118,22 +158,34 @@ try {
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<h5 class="card-title">Existing Classes</h5> <h5 class="card-title">Existing Classes</h5>
<?php if (empty($classes) && !$error): ?> <?php if (empty($classes)): ?>
<p class="text-muted">No classes have been created yet. Use the form above to add the first one.</p> <p class="text-muted">No classes have been created yet.</p>
<?php else: <?php else: ?>
if(!empty($classes)) : ?> <div class="table-responsive">
<ul class="list-group list-group-flush"> <table class="table table-striped">
<?php foreach ($classes as $class): <thead>
// Corrected: removed unnecessary escaping around $class['name'] <tr>
// Corrected: removed unnecessary escaping around $class['created_at'] <th>Name</th>
?> <th>Actions</th>
<li class="list-group-item d-flex justify-content-between align-items-center"> </tr>
<?php echo htmlspecialchars($class['name']); ?> </thead>
<small class="text-muted">Created: <?php echo date("M j, Y", strtotime($class['created_at'])); ?></small> <tbody>
</li> <?php foreach ($classes as $class): ?>
<?php endforeach; ?> <tr>
</ul> <td><?php echo htmlspecialchars($class['name']); ?></td>
<?php endif; endif; ?> <td>
<a href="?edit_id=<?php echo $class['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
<form action="admin_classes.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this class?');">
<input type="hidden" name="delete_id" value="<?php echo $class['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div> </div>
</div> </div>

View File

@ -1,134 +0,0 @@
<?php
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/db/config.php';
$message = '';
$error = '';
$teacher = null;
$school_id = $_SESSION['school_id'];
if (!isset($_GET['id'])) {
header("Location: admin_teachers.php");
exit;
}
$teacher_id = $_GET['id'];
$pdo = db();
// Handle POST request to update teacher
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$can_edit_workload = isset($_POST['can_edit_workload']) ? 1 : 0;
try {
$stmt = $pdo->prepare("UPDATE teachers SET can_edit_workload = ? WHERE id = ? AND school_id = ?");
if ($stmt->execute([$can_edit_workload, $teacher_id, $school_id])) {
$message = 'Teacher updated successfully!';
} else {
$error = 'Failed to update teacher.';
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
}
}
// Fetch teacher data
try {
$stmt = $pdo->prepare("SELECT t.id, t.name, u.email, t.can_edit_workload FROM teachers t JOIN users u ON t.user_id = u.id WHERE t.id = ? AND t.school_id = ?");
$stmt->execute([$teacher_id, $school_id]);
$teacher = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$teacher) {
header("Location: admin_teachers.php?error=not_found");
exit;
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin: Edit Teacher - Haki Schedule</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-white sticky-top shadow-sm">
<div class="container">
<a class="navbar-brand fw-bold" href="/">Haki Schedule</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="/">Home</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle active" href="#" id="manageDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Manage
</a>
<ul class="dropdown-menu" aria-labelledby="manageDropdown">
<li><a class="dropdown-item" href="/admin_classes.php">Classes</a></li>
<li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li>
<li><a class="dropdown-item active" href="/admin_teachers.php">Teachers</a></li>
<li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li>
<li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li>
</ul>
</li>
<li class="nav-item"><a class="nav-link" href="/timetable.php">Class Timetable</a></li>
<li class="nav-item"><a class="nav-link" href="/teacher_timetable.php">Teacher Timetable</a></li>
<li class="nav-item"><a class="nav-link" href="/logout.php">Logout</a></li>
</ul>
</div>
</div>
</nav>
<main class="container py-5">
<div class="row justify-content-center">
<div class="col-lg-8">
<h1 class="h2 fw-bold mb-4">Edit Teacher</h1>
<?php if ($message): ?>
<div class="alert alert-success"><?php echo $message; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<form action="admin_edit_teacher.php?id=<?php echo $teacher['id']; ?>" method="POST">
<div class="mb-3">
<label for="teacher_name" class="form-label">Teacher Name</label>
<input type="text" class="form-control" id="teacher_name" name="teacher_name" value="<?php echo htmlspecialchars($teacher['name']); ?>" readonly>
</div>
<div class="mb-3">
<label for="teacher_email" class="form-label">Teacher Email</label>
<input type="email" class="form-control" id="teacher_email" name="teacher_email" value="<?php echo htmlspecialchars($teacher['email']); ?>" readonly>
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="can_edit_workload" name="can_edit_workload" value="1" <?php echo $teacher['can_edit_workload'] ? 'checked' : ''; ?>>
<label class="form-check-label" for="can_edit_workload">Can edit their own workload</label>
</div>
<button type="submit" class="btn btn-primary">Update Teacher</button>
<a href="admin_teachers.php" class="btn btn-secondary">Back to Teachers</a>
</form>
</div>
</div>
</div>
</div>
</main>
<footer class="bg-dark text-white py-4 mt-5">
<div class="container text-center">
<p>&copy; <?php echo date("Y"); ?> Haki Schedule. All Rights Reserved.</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

204
admin_elective_groups.php Normal file
View File

@ -0,0 +1,204 @@
<?php
require_once __DIR__ . '/includes/auth_check.php';
require_once __DIR__ . '/db/config.php';
$message = '';
$error = '';
$editing_group = null;
$school_id = $_SESSION['school_id'];
$pdo = db();
// Handle Delete request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
try {
$delete_id = $_POST['delete_id'];
$stmt = $pdo->prepare("DELETE FROM elective_groups WHERE id = ? AND school_id = ?");
$stmt->execute([$delete_id, $school_id]);
$message = "Elective group deleted successfully.";
} catch (PDOException $e) {
$error = "Error deleting group: " . $e->getMessage();
}
}
// Handle POST request to add or update a group
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['group_name'])) {
$groupName = trim($_POST['group_name']);
$group_id = $_POST['group_id'] ?? null;
if (empty($groupName)) {
$error = 'Group name cannot be empty.';
} else {
// Check for duplicates before inserting
$stmt = $pdo->prepare("SELECT id FROM elective_groups WHERE name = ? AND school_id = ? AND id != ?");
$stmt->execute([$groupName, $school_id, $group_id ?? 0]);
if ($stmt->fetch()) {
$error = "Error: Elective group '" . htmlspecialchars($groupName) . "' already exists.";
} else {
try {
if ($group_id) {
// Update existing group
$stmt = $pdo->prepare("UPDATE elective_groups SET name = ? WHERE id = ? AND school_id = ?");
$stmt->execute([$groupName, $group_id, $school_id]);
$message = "Elective group updated successfully!";
} else {
// Insert new group
$stmt = $pdo->prepare("INSERT INTO elective_groups (name, school_id) VALUES (?, ?)");
$stmt->execute([$groupName, $school_id]);
$message = "Elective group created successfully!";
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
}
}
}
}
// Handle Edit request
if (isset($_GET['edit_id'])) {
try {
$edit_id = $_GET['edit_id'];
$stmt = $pdo->prepare("SELECT * FROM elective_groups WHERE id = ? AND school_id = ?");
$stmt->execute([$edit_id, $school_id]);
$editing_group = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = "Error fetching group: " . $e->getMessage();
}
}
// Fetch all groups to display
$groups = [];
try {
$groups_stmt = $pdo->prepare("SELECT * FROM elective_groups WHERE school_id = ? ORDER BY name ASC");
$groups_stmt->execute([$school_id]);
$groups = $groups_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin: Manage Elective Groups - Haki Schedule</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-white sticky-top shadow-sm">
<div class="container">
<a class="navbar-brand fw-bold" href="/">Haki Schedule</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="/">Home</a></li>
<?php if (isset($_SESSION['user_id'])): ?>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle active" href="#" id="manageDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Manage
</a>
<ul class="dropdown-menu" aria-labelledby="manageDropdown">
<li><a class="dropdown-item" href="/admin_classes.php">Classes</a></li>
<li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li>
<li><a class="dropdown-item active" href="/admin_elective_groups.php">Elective Groups</a></li>
<li><a class="dropdown-item" href="/admin_teachers.php">Teachers</a></li>
<li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li>
<li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li>
</ul>
</li>
<li class="nav-item"><a class="nav-link" href="/timetable.php">Class Timetable</a></li>
<li class="nav-item"><a class="nav-link" href="/teacher_timetable.php">Teacher Timetable</a></li>
<li class="nav-item"><a class="nav-link" href="/logout.php">Logout</a></li>
<?php else: ?>
<li class="nav-item"><a class="nav-link" href="/demo.php">Demo</a></li>
<li class="nav-item"><a class="nav-link" href="/login.php">Login</a></li>
<li class="nav-item"><a class="nav-link" href="/register.php">Register</a></li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>
<main class="container py-5">
<div class="row justify-content-center">
<div class="col-lg-8">
<h1 class="h2 fw-bold mb-4">Manage Elective Groups</h1>
<?php if ($message): ?>
<div class="alert alert-success"><?php echo $message; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>
<!-- Create/Edit Group Form -->
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title"><?php echo $editing_group ? 'Edit Group' : 'Create a New Group'; ?></h5>
<form action="admin_elective_groups.php" method="POST">
<input type="hidden" name="group_id" value="<?php echo $editing_group['id'] ?? ''; ?>">
<div class="mb-3">
<label for="group_name" class="form-label">Group Name</label>
<input type="text" class="form-control" id="group_name" name="group_name" value="<?php echo htmlspecialchars($editing_group['name'] ?? ''); ?>" placeholder="e.g., Humanities" required>
</div>
<button type="submit" class="btn btn-primary"><?php echo $editing_group ? 'Update Group' : 'Create Group'; ?></button>
<?php if ($editing_group): ?>
<a href="admin_elective_groups.php" class="btn btn-secondary">Cancel Edit</a>
<?php endif; ?>
</form>
</div>
</div>
<!-- Existing Groups List -->
<div class="card">
<div class="card-body">
<h5 class="card-title">Existing Elective Groups</h5>
<?php if (empty($groups)): ?>
<p class="text-muted">No elective groups have been created yet.</p>
<?php else: ?>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($groups as $group): ?>
<tr>
<td><?php echo htmlspecialchars($group['name']); ?></td>
<td>
<a href="?edit_id=<?php echo $group['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
<form action="admin_elective_groups.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this group?');">
<input type="hidden" name="delete_id" value="<?php echo $group['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</main>
<footer class="bg-dark text-white py-4 mt-5">
<div class="container text-center">
<p>&copy; <?php echo date("Y"); ?> Haki Schedule. All Rights Reserved.</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@ -24,29 +24,34 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
// Handle POST request to add or update a subject // Handle POST request to add or update a subject
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['subject_name'])) { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['subject_name'])) {
$subjectName = trim($_POST['subject_name']); $subjectName = trim($_POST['subject_name']);
$lessons_per_week = filter_input(INPUT_POST, 'lessons_per_week', FILTER_VALIDATE_INT, ['options' => ['default' => 1, 'min_range' => 1]]);
$has_double_lesson = isset($_POST['has_double_lesson']) ? 1 : 0; $has_double_lesson = isset($_POST['has_double_lesson']) ? 1 : 0;
$is_elective = isset($_POST['is_elective']) ? 1 : 0; $is_elective = isset($_POST['is_elective']) ? 1 : 0;
$elective_group_id = !empty($_POST['elective_group_id']) ? $_POST['elective_group_id'] : null;
$subject_id = $_POST['subject_id'] ?? null; $subject_id = $_POST['subject_id'] ?? null;
if (empty($subjectName)) { if (empty($subjectName)) {
$error = 'Subject name cannot be empty.'; $error = 'Subject name cannot be empty.';
} else { } else {
try { // Check for duplicates before inserting/updating
if ($subject_id) { $stmt = $pdo->prepare("SELECT id FROM subjects WHERE name = ? AND school_id = ? AND id != ?");
// Update existing subject $stmt->execute([$subjectName, $school_id, $subject_id ?? 0]);
$stmt = $pdo->prepare("UPDATE subjects SET name = ?, has_double_lesson = ?, is_elective = ? WHERE id = ? AND school_id = ?"); if ($stmt->fetch()) {
$stmt->execute([$subjectName, $has_double_lesson, $is_elective, $subject_id, $school_id]); $error = "Error: Subject '" . htmlspecialchars($subjectName) . "' already exists.";
$message = "Subject updated successfully!"; } else {
} else { try {
// Insert new subject if ($subject_id) {
$stmt = $pdo->prepare("INSERT INTO subjects (name, has_double_lesson, is_elective, school_id) VALUES (?, ?, ?, ?)"); // Update existing subject
$stmt->execute([$subjectName, $has_double_lesson, $is_elective, $school_id]); $stmt = $pdo->prepare("UPDATE subjects SET name = ?, lessons_per_week = ?, has_double_lesson = ?, is_elective = ?, elective_group_id = ? WHERE id = ? AND school_id = ?");
$message = "Subject created successfully!"; $stmt->execute([$subjectName, $lessons_per_week, $has_double_lesson, $is_elective, $elective_group_id, $subject_id, $school_id]);
} $message = "Subject updated successfully!";
} catch (PDOException $e) { } else {
if ($e->errorInfo[1] == 1062) { // Duplicate entry // Insert new subject
$error = "Error: Subject '" . htmlspecialchars($subjectName) . "' already exists."; $stmt = $pdo->prepare("INSERT INTO subjects (name, lessons_per_week, has_double_lesson, is_elective, elective_group_id, school_id) VALUES (?, ?, ?, ?, ?, ?)");
} else { $stmt->execute([$subjectName, $lessons_per_week, $has_double_lesson, $is_elective, $elective_group_id, $school_id]);
$message = "Subject created successfully!";
}
} catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage(); $error = 'Database error: ' . $e->getMessage();
} }
} }
@ -68,13 +73,23 @@ if (isset($_GET['edit_id'])) {
// Fetch all subjects to display // Fetch all subjects to display
$subjects = []; $subjects = [];
try { try {
$subjects_stmt = $pdo->prepare("SELECT * FROM subjects WHERE school_id = ? ORDER BY name ASC"); $subjects_stmt = $pdo->prepare("SELECT s.*, eg.name as elective_group_name FROM subjects s LEFT JOIN elective_groups eg ON s.elective_group_id = eg.id WHERE s.school_id = ? ORDER BY s.name ASC");
$subjects_stmt->execute([$school_id]); $subjects_stmt->execute([$school_id]);
$subjects = $subjects_stmt->fetchAll(PDO::FETCH_ASSOC); $subjects = $subjects_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage(); $error = 'Database error: ' . $e->getMessage();
} }
// Fetch all elective groups for the dropdown
$elective_groups = [];
try {
$stmt = $pdo->prepare("SELECT * FROM elective_groups WHERE school_id = ? ORDER BY name ASC");
$stmt->execute([$school_id]);
$elective_groups = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = 'Database error while fetching elective groups: ' . $e->getMessage();
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
@ -145,6 +160,10 @@ try {
<label for="subject_name" class="form-label">Subject Name</label> <label for="subject_name" class="form-label">Subject Name</label>
<input type="text" class="form-control" id="subject_name" name="subject_name" value="<?php echo htmlspecialchars($editing_subject['name'] ?? ''); ?>" placeholder="e.g., Mathematics" required> <input type="text" class="form-control" id="subject_name" name="subject_name" value="<?php echo htmlspecialchars($editing_subject['name'] ?? ''); ?>" placeholder="e.g., Mathematics" required>
</div> </div>
<div class="col-md-6 mb-3">
<label for="lessons_per_week" class="form-label">Lessons per Week</label>
<input type="number" class="form-control" id="lessons_per_week" name="lessons_per_week" value="<?php echo htmlspecialchars($editing_subject['lessons_per_week'] ?? '1'); ?>" min="1" required>
</div>
</div> </div>
<div class="mb-3 form-check"> <div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="has_double_lesson" name="has_double_lesson" value="1" <?php echo !empty($editing_subject['has_double_lesson']) ? 'checked' : ''; ?>> <input type="checkbox" class="form-check-input" id="has_double_lesson" name="has_double_lesson" value="1" <?php echo !empty($editing_subject['has_double_lesson']) ? 'checked' : ''; ?>>
@ -154,6 +173,17 @@ try {
<input type="checkbox" class="form-check-input" id="is_elective" name="is_elective" value="1" <?php echo !empty($editing_subject['is_elective']) ? 'checked' : ''; ?>> <input type="checkbox" class="form-check-input" id="is_elective" name="is_elective" value="1" <?php echo !empty($editing_subject['is_elective']) ? 'checked' : ''; ?>>
<label class="form-check-label" for="is_elective">Is Elective</label> <label class="form-check-label" for="is_elective">Is Elective</label>
</div> </div>
<div class="mb-3">
<label for="elective_group_id" class="form-label">Elective Group (Optional)</label>
<select class="form-select" id="elective_group_id" name="elective_group_id">
<option value="">None</option>
<?php foreach ($elective_groups as $group): ?>
<option value="<?php echo $group['id']; ?>" <?php echo (isset($editing_subject['elective_group_id']) && $editing_subject['elective_group_id'] == $group['id']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($group['name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" class="btn btn-primary"><?php echo $editing_subject ? 'Update Subject' : 'Create Subject'; ?></button> <button type="submit" class="btn btn-primary"><?php echo $editing_subject ? 'Update Subject' : 'Create Subject'; ?></button>
<?php if ($editing_subject): ?> <?php if ($editing_subject): ?>
<a href="admin_subjects.php" class="btn btn-secondary">Cancel Edit</a> <a href="admin_subjects.php" class="btn btn-secondary">Cancel Edit</a>
@ -174,8 +204,10 @@ try {
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Lessons / Week</th>
<th>Double Lesson</th> <th>Double Lesson</th>
<th>Is Elective</th> <th>Is Elective</th>
<th>Elective Group</th>
<th>Actions</th> <th>Actions</th>
</tr> </tr>
</thead> </thead>
@ -183,8 +215,10 @@ try {
<?php foreach ($subjects as $subject): ?> <?php foreach ($subjects as $subject): ?>
<tr> <tr>
<td><?php echo htmlspecialchars($subject['name']); ?></td> <td><?php echo htmlspecialchars($subject['name']); ?></td>
<td><?php echo htmlspecialchars($subject['lessons_per_week']); ?></td>
<td><?php echo $subject['has_double_lesson'] ? 'Yes' : 'No'; ?></td> <td><?php echo $subject['has_double_lesson'] ? 'Yes' : 'No'; ?></td>
<td><?php echo $subject['is_elective'] ? 'Yes' : 'No'; ?></td> <td><?php echo $subject['is_elective'] ? 'Yes' : 'No'; ?></td>
<td><?php echo htmlspecialchars($subject['elective_group_name'] ?? 'N/A'); ?></td>
<td> <td>
<a href="?edit_id=<?php echo $subject['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a> <a href="?edit_id=<?php echo $subject['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
<form action="admin_subjects.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this subject?');"> <form action="admin_subjects.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this subject?');">

View File

@ -4,69 +4,131 @@ require_once __DIR__ . '/db/config.php';
$message = ''; $message = '';
$error = ''; $error = '';
$editing_teacher = null;
$school_id = $_SESSION['school_id']; $school_id = $_SESSION['school_id'];
// Handle POST request to add a new teacher $pdo = db();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$teacherName = trim($_POST['teacher_name'] ?? ''); // Handle Delete request
$teacherEmail = trim($_POST['teacher_email'] ?? ''); if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
$can_edit_workload = isset($_POST['can_edit_workload']) ? 1 : 0; try {
$delete_id = $_POST['delete_id'];
// Also delete the associated user account
$stmt = $pdo->prepare("SELECT user_id FROM teachers WHERE id = ? AND school_id = ?");
$stmt->execute([$delete_id, $school_id]);
$user_id = $stmt->fetchColumn();
$pdo->beginTransaction();
$stmt = $pdo->prepare("DELETE FROM teachers WHERE id = ?");
$stmt->execute([$delete_id]);
if ($user_id) {
$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$user_id]);
}
$pdo->commit();
$message = "Teacher deleted successfully.";
} catch (PDOException $e) {
$pdo->rollBack();
$error = "Error deleting teacher: " . $e->getMessage();
}
}
// Handle POST request to add or update a teacher
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['teacher_name'])) {
$teacherName = trim($_POST['teacher_name']);
$teacherEmail = trim($_POST['teacher_email']);
$password = $_POST['password'] ?? null;
$teacher_id = $_POST['teacher_id'] ?? null;
if (empty($teacherName) || empty($teacherEmail)) { if (empty($teacherName) || empty($teacherEmail)) {
$error = 'Teacher name and email cannot be empty.'; $error = 'Teacher name and email are required.';
} elseif (!filter_var($teacherEmail, FILTER_VALIDATE_EMAIL)) { } elseif (!filter_var($teacherEmail, FILTER_VALIDATE_EMAIL)) {
$error = 'Invalid email format.'; $error = 'Invalid email format.';
} elseif (!$teacher_id && empty($password)) {
$error = 'Password is required for new teachers.';
} else { } else {
try { try {
$pdo = db();
$pdo->beginTransaction(); $pdo->beginTransaction();
// Check if user with this email already exists // Check for duplicate teacher name
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?"); $stmt = $pdo->prepare("SELECT id FROM teachers WHERE name = ? AND school_id = ? AND id != ?");
$stmt->execute([$teacherEmail]); $stmt->execute([$teacherName, $school_id, $teacher_id ?? 0]);
if ($stmt->fetch()) { if ($stmt->fetch()) {
$error = 'A user with this email already exists.'; throw new Exception("A teacher with this name already exists.");
$pdo->rollBack(); }
} else {
// Generate a random password
$password = bin2hex(random_bytes(8));
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Create a user account for the teacher if ($teacher_id) {
$stmt = $pdo->prepare("INSERT INTO users (username, password, email, school_id, role) VALUES (?, ?, ?, ?, 'teacher')"); // Update existing teacher
$stmt->execute([$teacherEmail, $hashed_password, $teacherEmail, $school_id]); $stmt = $pdo->prepare("UPDATE teachers SET name = ? WHERE id = ? AND school_id = ?");
$stmt->execute([$teacherName, $teacher_id, $school_id]);
// Also update user email
$stmt = $pdo->prepare("SELECT user_id FROM teachers WHERE id = ?");
$stmt->execute([$teacher_id]);
$user_id = $stmt->fetchColumn();
if ($user_id) {
$sql = "UPDATE users SET email = ?, username = ?";
$params = [$teacherEmail, $teacherEmail];
if (!empty($password)) {
$sql .= ", password = ?";
$params[] = password_hash($password, PASSWORD_DEFAULT);
}
$sql .= " WHERE id = ?";
$params[] = $user_id;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
}
$message = "Teacher updated successfully!";
} else {
// Check for duplicate email in users table
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$teacherEmail]);
if ($stmt->fetch()) {
throw new Exception("A user with this email already exists.");
}
// Insert new user
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (school_id, username, email, password, role) VALUES (?, ?, ?, ?, 'teacher')");
$stmt->execute([$school_id, $teacherEmail, $teacherEmail, $hashed_password]);
$user_id = $pdo->lastInsertId(); $user_id = $pdo->lastInsertId();
// Create the teacher // Insert new teacher
$stmt = $pdo->prepare("INSERT INTO teachers (name, user_id, school_id, can_edit_workload) VALUES (?, ?, ?, ?)"); $stmt = $pdo->prepare("INSERT INTO teachers (name, school_id, user_id) VALUES (?, ?, ?)");
if ($stmt->execute([$teacherName, $user_id, $school_id, $can_edit_workload])) { $stmt->execute([$teacherName, $school_id, $user_id]);
$pdo->commit(); $message = "Teacher created successfully!";
$message = 'Teacher "' . htmlspecialchars($teacherName) . '" created successfully! Their password is: ' . $password;
} else {
$error = 'Failed to create teacher.';
$pdo->rollBack();
}
}
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) { // Duplicate entry
$error = 'Error: A teacher with this email already exists.';
} else {
$error = 'Database error: ' . $e->getMessage();
} }
$pdo->commit();
} catch (Exception $e) {
if ($pdo->inTransaction()) { if ($pdo->inTransaction()) {
$pdo->rollBack(); $pdo->rollBack();
} }
$error = $e->getMessage();
} }
} }
} }
// Handle Edit request
if (isset($_GET['edit_id'])) {
try {
$edit_id = $_GET['edit_id'];
$stmt = $pdo->prepare("SELECT t.*, u.email FROM teachers t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ? AND t.school_id = ?");
$stmt->execute([$edit_id, $school_id]);
$editing_teacher = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error = "Error fetching teacher: " . $e->getMessage();
}
}
// Fetch all teachers to display // Fetch all teachers to display
$teachers = []; $teachers = [];
try { try {
$pdo = db(); $teachers_stmt = $pdo->prepare("SELECT t.*, u.email FROM teachers t LEFT JOIN users u ON t.user_id = u.id WHERE t.school_id = ? ORDER BY t.name ASC");
$stmt = $pdo->prepare("SELECT t.id, t.name, u.email, t.can_edit_workload, t.created_at FROM teachers t JOIN users u ON t.user_id = u.id WHERE t.school_id = ? ORDER BY t.created_at DESC"); $teachers_stmt->execute([$school_id]);
$stmt->execute([$school_id]); $teachers = $teachers_stmt->fetchAll(PDO::FETCH_ASSOC);
$teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { } catch (PDOException $e) {
$error = 'Database error: ' . $e->getMessage(); $error = 'Database error: ' . $e->getMessage();
} }
@ -100,6 +162,7 @@ try {
<ul class="dropdown-menu" aria-labelledby="manageDropdown"> <ul class="dropdown-menu" aria-labelledby="manageDropdown">
<li><a class="dropdown-item" href="/admin_classes.php">Classes</a></li> <li><a class="dropdown-item" href="/admin_classes.php">Classes</a></li>
<li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li> <li><a class="dropdown-item" href="/admin_subjects.php">Subjects</a></li>
<li><a class="dropdown-item" href="/admin_elective_groups.php">Elective Groups</a></li>
<li><a class="dropdown-item active" href="/admin_teachers.php">Teachers</a></li> <li><a class="dropdown-item active" href="/admin_teachers.php">Teachers</a></li>
<li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li> <li><a class="dropdown-item" href="/admin_workloads.php">Workloads</a></li>
<li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li> <li><a class="dropdown-item" href="/admin_timeslots.php">Timeslots</a></li>
@ -130,24 +193,31 @@ try {
<div class="alert alert-danger"><?php echo $error; ?></div> <div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?> <?php endif; ?>
<!-- Create Teacher Form --> <!-- Create/Edit Teacher Form -->
<div class="card mb-4"> <div class="card mb-4">
<div class="card-body"> <div class="card-body">
<h5 class="card-title">Create a New Teacher</h5> <h5 class="card-title"><?php echo $editing_teacher ? 'Edit Teacher' : 'Create a New Teacher'; ?></h5>
<form action="admin_teachers.php" method="POST"> <form action="admin_teachers.php" method="POST">
<input type="hidden" name="teacher_id" value="<?php echo $editing_teacher['id'] ?? ''; ?>">
<div class="mb-3"> <div class="mb-3">
<label for="teacher_name" class="form-label">Teacher Name</label> <label for="teacher_name" class="form-label">Teacher Name</label>
<input type="text" class="form-control" id="teacher_name" name="teacher_name" placeholder="e.g., John Doe" required> <input type="text" class="form-control" id="teacher_name" name="teacher_name" value="<?php echo htmlspecialchars($editing_teacher['name'] ?? ''); ?>" required>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="teacher_email" class="form-label">Teacher Email</label> <label for="teacher_email" class="form-label">Teacher Email</label>
<input type="email" class="form-control" id="teacher_email" name="teacher_email" placeholder="e.g., john.doe@example.com" required> <input type="email" class="form-control" id="teacher_email" name="teacher_email" value="<?php echo htmlspecialchars($editing_teacher['email'] ?? ''); ?>" required>
</div> </div>
<div class="mb-3 form-check"> <div class="mb-3">
<input type="checkbox" class="form-check-input" id="can_edit_workload" name="can_edit_workload" value="1"> <label for="password" class="form-label">Password</label>
<label class="form-check-label" for="can_edit_workload">Can edit their own workload</label> <input type="password" class="form-control" id="password" name="password" <?php echo $editing_teacher ? '' : 'required'; ?>>
<?php if ($editing_teacher): ?>
<small class="form-text text-muted">Leave blank to keep the current password.</small>
<?php endif; ?>
</div> </div>
<button type="submit" class="btn btn-primary">Create Teacher</button> <button type="submit" class="btn btn-primary"><?php echo $editing_teacher ? 'Update Teacher' : 'Create Teacher'; ?></button>
<?php if ($editing_teacher): ?>
<a href="admin_teachers.php" class="btn btn-secondary">Cancel Edit</a>
<?php endif; ?>
</form> </form>
</div> </div>
</div> </div>
@ -156,18 +226,15 @@ try {
<div class="card"> <div class="card">
<div class="card-body"> <div class="card-body">
<h5 class="card-title">Existing Teachers</h5> <h5 class="card-title">Existing Teachers</h5>
<?php if (empty($teachers) && !$error): ?> <?php if (empty($teachers)): ?>
<p class="text-muted">No teachers have been created yet. Use the form above to add the first one.</p> <p class="text-muted">No teachers have been created yet.</p>
<?php else: <?php else: ?>
if(!empty($teachers)) : ?>
<div class="table-responsive"> <div class="table-responsive">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th>Email</th> <th>Email</th>
<th>Can Edit Workload</th>
<th>Created</th>
<th>Actions</th> <th>Actions</th>
</tr> </tr>
</thead> </thead>
@ -176,15 +243,19 @@ try {
<tr> <tr>
<td><?php echo htmlspecialchars($teacher['name']); ?></td> <td><?php echo htmlspecialchars($teacher['name']); ?></td>
<td><?php echo htmlspecialchars($teacher['email']); ?></td> <td><?php echo htmlspecialchars($teacher['email']); ?></td>
<td><?php echo $teacher['can_edit_workload'] ? 'Yes' : 'No'; ?></td> <td>
<td><?php echo date("M j, Y", strtotime($teacher['created_at'])); ?></td> <a href="?edit_id=<?php echo $teacher['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
<td><a href="admin_edit_teacher.php?id=<?php echo $teacher['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a></td> <form action="admin_teachers.php" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this teacher?');">
<input type="hidden" name="delete_id" value="<?php echo $teacher['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>
</table> </table>
</div> </div>
<?php endif; endif; ?> <?php endif; ?>
</div> </div>
</div> </div>

View File

@ -92,13 +92,13 @@ try {
$workloads = []; $workloads = [];
try { try {
$workloads_stmt = $pdo->prepare(" $workloads_stmt = $pdo->prepare("
SELECT w.id, c.name as class_name, s.name as subject_name, t.name as teacher_name, w.lessons_per_week, w.created_at, w.class_id, w.subject_id, w.teacher_id SELECT w.id, c.name as class_name, s.name as subject_name, t.name as teacher_name, w.lessons_per_week, w.class_id, w.subject_id, w.teacher_id
FROM workloads w FROM workloads w
JOIN classes c ON w.class_id = c.id JOIN classes c ON w.class_id = c.id
JOIN subjects s ON w.subject_id = s.id JOIN subjects s ON w.subject_id = s.id
JOIN teachers t ON w.teacher_id = t.id JOIN teachers t ON w.teacher_id = t.id
WHERE w.school_id = ? WHERE w.school_id = ?
ORDER BY w.created_at DESC ORDER BY c.name, s.name, t.name
"); ");
$workloads_stmt->execute([$school_id]); $workloads_stmt->execute([$school_id]);
$workloads = $workloads_stmt->fetchAll(PDO::FETCH_ASSOC); $workloads = $workloads_stmt->fetchAll(PDO::FETCH_ASSOC);

View File

@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS `elective_groups` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`school_id` INT NOT NULL,
FOREIGN KEY (`school_id`) REFERENCES `schools`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `subjects` ADD COLUMN `elective_group_id` INT DEFAULT NULL,
ADD FOREIGN KEY (`elective_group_id`) REFERENCES `elective_groups`(`id`) ON DELETE SET NULL;

View File

@ -0,0 +1,5 @@
ALTER TABLE `elective_groups` ADD UNIQUE `unique_school_name`(`school_id`, `name`);
ALTER TABLE `subjects` ADD UNIQUE `unique_school_name`(`school_id`, `name`);
ALTER TABLE `classes` ADD UNIQUE `unique_school_name`(`school_id`, `name`);
ALTER TABLE `teachers` ADD UNIQUE `unique_school_name`(`school_id`, `name`);
ALTER TABLE `teachers` ADD UNIQUE `unique_school_teacher`(`school_id`, `name`);

View File

@ -0,0 +1 @@
ALTER TABLE subjects ADD COLUMN lessons_per_week INT NOT NULL DEFAULT 1;

View File

@ -0,0 +1,4 @@
ALTER TABLE timeslots
ADD COLUMN name VARCHAR(255) NOT NULL,
ADD COLUMN is_break TINYINT(1) NOT NULL DEFAULT 0,
DROP COLUMN day_of_week;

View File

@ -0,0 +1 @@
ALTER TABLE schedules ADD COLUMN day_of_week INT NOT NULL AFTER class_id;

View File

@ -0,0 +1 @@
ALTER TABLE `schedules` ADD `lesson_display_name` VARCHAR(255);

View File

@ -0,0 +1 @@
ALTER TABLE `schedules` ADD `teacher_display_name` VARCHAR(255);

View File

@ -0,0 +1 @@
ALTER TABLE schedules ADD COLUMN is_double BOOLEAN NOT NULL DEFAULT 0;

View File

@ -0,0 +1 @@
ALTER TABLE schedules ADD COLUMN is_elective BOOLEAN NOT NULL DEFAULT 0, ADD COLUMN is_horizontal_elective BOOLEAN NOT NULL DEFAULT 0;

View File

@ -178,7 +178,7 @@ foreach ($teacher_schedule_raw as $lesson) {
<select name="teacher_id" id="teacher_id" class="form-select" onchange="this.form.submit()"> <select name="teacher_id" id="teacher_id" class="form-select" onchange="this.form.submit()">
<option value="">-- Select a Teacher --</option> <option value="">-- Select a Teacher --</option>
<?php foreach ($teachers as $teacher): ?> <?php foreach ($teachers as $teacher): ?>
<option value="<?php echo $teacher['id']; ?>" <?php echo ($selected_teacher_id == $teacher['id']['id']) ? 'selected' : ''; ?>> <option value="<?php echo $teacher['id']; ?>" <?php echo ($selected_teacher_id == $teacher['id']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($teacher['name']); ?> <?php echo htmlspecialchars($teacher['name']); ?>
</option> </option>
<?php endforeach; ?> <?php endforeach; ?>

View File

@ -13,7 +13,8 @@ function get_workloads($pdo) {
s.id as subject_id, s.id as subject_id,
s.name as subject_name, s.name as subject_name,
s.has_double_lesson, s.has_double_lesson,
s.elective_group, s.elective_group_id,
eg.name as elective_group_name,
t.id as teacher_id, t.id as teacher_id,
t.name as teacher_name, t.name as teacher_name,
w.lessons_per_week w.lessons_per_week
@ -21,6 +22,7 @@ function get_workloads($pdo) {
JOIN classes c ON w.class_id = c.id JOIN classes c ON w.class_id = c.id
JOIN subjects s ON w.subject_id = s.id JOIN subjects s ON w.subject_id = s.id
JOIN teachers t ON w.teacher_id = t.id JOIN teachers t ON w.teacher_id = t.id
LEFT JOIN elective_groups eg ON s.elective_group_id = eg.id
ORDER BY c.name, s.name ORDER BY c.name, s.name
"); ");
return $stmt->fetchAll(PDO::FETCH_ASSOC); return $stmt->fetchAll(PDO::FETCH_ASSOC);
@ -45,7 +47,7 @@ function get_grade_from_class_name($class_name) {
// --- Scoring and Placement Logic --- // --- Scoring and Placement Logic ---
function find_best_slot_for_lesson($lesson, $is_double, &$class_timetables, &$teacher_timetables, $all_class_ids, $days_of_week, $periods_per_day) { function find_best_slot_for_lesson($lesson, $is_double, &$class_timetables, &$teacher_timetables, $all_class_ids, $days_of_week, $periods_per_day) {
$best_slot = null; $best_slot = null;
$highest_score = -1; $highest_score = -1000;
$class_id = $lesson['type'] === 'horizontal_elective' ? null : $lesson['class_id']; $class_id = $lesson['type'] === 'horizontal_elective' ? null : $lesson['class_id'];
$teachers_in_lesson = array_unique(array_column($lesson['component_lessons'], 'teacher_id')); $teachers_in_lesson = array_unique(array_column($lesson['component_lessons'], 'teacher_id'));
@ -58,7 +60,7 @@ function find_best_slot_for_lesson($lesson, $is_double, &$class_timetables, &$te
// 1. Check basic availability // 1. Check basic availability
$slot_available = true; $slot_available = true;
if ($is_double) { if ($is_double) {
if ($period + 1 >= $periods_per_day) continue; if ($period + 1 >= $periods_per_day) continue; // Not enough space for a double
foreach ($class_ids_in_lesson as $cid) { foreach ($class_ids_in_lesson as $cid) {
if (isset($class_timetables[$cid][$day][$period]) || isset($class_timetables[$cid][$day][$period + 1])) { if (isset($class_timetables[$cid][$day][$period]) || isset($class_timetables[$cid][$day][$period + 1])) {
$slot_available = false; break; $slot_available = false; break;
@ -86,28 +88,55 @@ function find_best_slot_for_lesson($lesson, $is_double, &$class_timetables, &$te
if (!$slot_available) continue; if (!$slot_available) continue;
// 2. Apply scoring rules // 2. Apply scoring rules
// A. Penalize placing the same subject on the same day
foreach ($class_ids_in_lesson as $cid) { foreach ($class_ids_in_lesson as $cid) {
$lessons_on_day = 0;
for ($p = 0; $p < $periods_per_day; $p++) { for ($p = 0; $p < $periods_per_day; $p++) {
if (isset($class_timetables[$cid][$day][$p]) && $class_timetables[$cid][$day][$p]['subject_name'] === $lesson['display_name']) { if (isset($class_timetables[$cid][$day][$p]) && $class_timetables[$cid][$day][$p]['subject_name'] === $lesson['display_name']) {
$current_score -= 50; $lessons_on_day++;
}
}
$current_score -= $lessons_on_day * 50; // Heavy penalty for each existing lesson of same subject
}
// B. Penalize creating gaps for teachers and classes
foreach ($teachers_in_lesson as $teacher_id) {
// Check for gap before the lesson
if ($period > 0 && !isset($teacher_timetables[$teacher_id][$day][$period - 1])) {
if (isset($teacher_timetables[$teacher_id][$day][$period - 2])) $current_score -= 25; // Gap of 1
}
// Check for gap after the lesson
$after_period = $is_double ? $period + 2 : $period + 1;
if ($after_period < $periods_per_day && !isset($teacher_timetables[$teacher_id][$day][$after_period])) {
if (isset($teacher_timetables[$teacher_id][$day][$after_period + 1])) $current_score -= 25; // Gap of 1
}
}
foreach ($class_ids_in_lesson as $cid) {
if ($period > 0 && !isset($class_timetables[$cid][$day][$period - 1])) {
if (isset($class_timetables[$cid][$day][$period - 2])) $current_score -= 10;
}
$after_period = $is_double ? $period + 2 : $period + 1;
if ($after_period < $periods_per_day && !isset($class_timetables[$cid][$day][$after_period])) {
if (isset($class_timetables[$cid][$day][$after_period + 1])) $current_score -= 10;
}
}
// C. Penalize placing a double lesson of the same subject in parallel with another class
if ($is_double) {
$subject_name_to_check = $lesson['display_name'];
foreach ($all_class_ids as $cid) {
if (in_array($cid, $class_ids_in_lesson)) continue; // Don't check against itself
if (isset($class_timetables[$cid][$day][$period]) && $class_timetables[$cid][$day][$period]['is_double'] && $class_timetables[$cid][$day][$period]['subject_name'] === $subject_name_to_check) {
$current_score -= 200; // Very high penalty for parallel doubles of same subject
break;
} }
} }
} }
foreach ($teachers_in_lesson as $teacher_id) { // D. Prefer ends of day for double lessons
if ($period > 0 && isset($teacher_timetables[$teacher_id][$day][$period - 1])) $current_score -= 15;
$after_period = $is_double ? $period + 2 : $period + 1;
if ($after_period < $periods_per_day && isset($teacher_timetables[$teacher_id][$day][$after_period])) $current_score -= 15;
}
if ($is_double) { if ($is_double) {
$subject_name_to_check = $lesson['display_name']; if ($period == 0 || $period + 1 == $periods_per_day -1) {
foreach ($all_class_ids as $cid) { $current_score += 10;
if (in_array($cid, $class_ids_in_lesson)) continue;
if (isset($class_timetables[$cid][$day][$period]) && $class_timetables[$cid][$day][$period]['is_double'] && $class_timetables[$cid][$day][$period]['subject_name'] === $subject_name_to_check) {
$current_score -= 500;
break;
}
} }
} }
@ -117,8 +146,6 @@ function find_best_slot_for_lesson($lesson, $is_double, &$class_timetables, &$te
} }
} }
} }
return $best_slot;
}
// --- Main Scheduling Engine --- // --- Main Scheduling Engine ---
function generate_timetable($workloads, $classes, $days_of_week, $periods_per_day) { function generate_timetable($workloads, $classes, $days_of_week, $periods_per_day) {
@ -129,50 +156,47 @@ function generate_timetable($workloads, $classes, $days_of_week, $periods_per_da
$teacher_timetables = []; $teacher_timetables = [];
// --- Lesson Preparation --- // --- Lesson Preparation ---
$horizontal_elective_doubles = []; $all_lessons = [];
$horizontal_elective_singles = [];
$other_workloads = [];
$workloads_by_grade_and_elective_group = []; $workloads_by_grade_and_elective_group = [];
// 1. Group horizontal electives
foreach ($workloads as $workload) { foreach ($workloads as $workload) {
if (!empty($workload['elective_group'])) { if (!empty($workload['elective_group_id'])) {
$grade_name = get_grade_from_class_name($workload['class_name']); $grade_name = get_grade_from_class_name($workload['class_name']);
$workloads_by_grade_and_elective_group[$grade_name][$workload['elective_group']][] = $workload; $workloads_by_grade_and_elective_group[$grade_name][$workload['elective_group_id']][] = $workload;
} else { } else {
$other_workloads[] = $workload; // This will be handled in the next step
} }
} }
$processed_workload_ids = [];
foreach ($workloads_by_grade_and_elective_group as $grade_name => $elective_groups) { foreach ($workloads_by_grade_and_elective_group as $grade_name => $elective_groups) {
foreach ($elective_groups as $elective_group_name => $group_workloads) { foreach ($elective_groups as $elective_group_id => $group_workloads) {
$participating_class_ids = array_unique(array_column($group_workloads, 'class_id')); $participating_class_ids = array_unique(array_column($group_workloads, 'class_id'));
if (count($participating_class_ids) > 1) { if (count($participating_class_ids) > 1) {
$first = $group_workloads[0]; $first = $group_workloads[0];
$block = [ $block = [
'type' => 'horizontal_elective', 'type' => 'horizontal_elective',
'display_name' => $elective_group_name, 'display_name' => $first['elective_group_name'],
'participating_class_ids' => $participating_class_ids, 'participating_class_ids' => $participating_class_ids,
'lessons_per_week' => $first['lessons_per_week'], 'lessons_per_week' => $first['lessons_per_week'],
'has_double_lesson' => $first['has_double_lesson'], 'has_double_lesson' => $first['has_double_lesson'],
'component_lessons' => $group_workloads 'component_lessons' => $group_workloads,
'priority' => 4 // Highest priority
]; ];
$all_lessons[] = $block;
if ($block['has_double_lesson'] && $block['lessons_per_week'] >= 2) { foreach($group_workloads as $w) $processed_workload_ids[] = $w['id'];
$horizontal_elective_doubles[] = $block;
for ($i = 0; $i < $block['lessons_per_week'] - 2; $i++) $horizontal_elective_singles[] = $block;
} else {
for ($i = 0; $i < $block['lessons_per_week']; $i++) $horizontal_elective_singles[] = $block;
}
} else {
foreach($group_workloads as $workload) $other_workloads[] = $workload;
} }
} }
} }
$double_lessons = []; // 2. Group remaining lessons (single, elective, and normal doubles)
$single_lessons = []; $remaining_workloads = array_filter($workloads, function($w) use ($processed_workload_ids) {
return !in_array($w['id'], $processed_workload_ids);
});
$workloads_by_class = []; $workloads_by_class = [];
foreach ($other_workloads as $workload) { foreach ($remaining_workloads as $workload) {
$workloads_by_class[$workload['class_id']][] = $workload; $workloads_by_class[$workload['class_id']][] = $workload;
} }
@ -180,92 +204,104 @@ function generate_timetable($workloads, $classes, $days_of_week, $periods_per_da
$elective_groups = []; $elective_groups = [];
$individual_lessons = []; $individual_lessons = [];
foreach ($class_workloads as $workload) { foreach ($class_workloads as $workload) {
if (!empty($workload['elective_group'])) { if (!empty($workload['elective_group_id'])) {
$elective_groups[$workload['elective_group']][] = $workload; $elective_groups[$workload['elective_group_id']][] = $workload;
} else { } else {
$individual_lessons[] = $workload; $individual_lessons[] = $workload;
} }
} }
foreach ($elective_groups as $group_name => $group_workloads) { foreach ($elective_groups as $group_id => $group_workloads) {
$first = $group_workloads[0]; $first = $group_workloads[0];
$block = [ $all_lessons[] = [
'type' => 'elective', 'class_id' => $class_id, 'display_name' => $group_name, 'type' => 'elective', 'class_id' => $class_id, 'display_name' => $first['elective_group_name'],
'lessons_per_week' => $first['lessons_per_week'], 'has_double_lesson' => $first['has_double_lesson'], 'lessons_per_week' => $first['lessons_per_week'], 'has_double_lesson' => $first['has_double_lesson'],
'component_lessons' => $group_workloads 'component_lessons' => $group_workloads,
'priority' => 3
]; ];
if ($block['has_double_lesson'] && $block['lessons_per_week'] >= 2) {
$double_lessons[] = $block;
for ($i = 0; $i < $block['lessons_per_week'] - 2; $i++) $single_lessons[] = $block;
} else {
for ($i = 0; $i < $block['lessons_per_week']; $i++) $single_lessons[] = $block;
}
} }
foreach ($individual_lessons as $workload) { foreach ($individual_lessons as $workload) {
$lesson = [ $all_lessons[] = [
'type' => 'single', 'class_id' => $workload['class_id'], 'display_name' => $workload['subject_name'], 'type' => 'single', 'class_id' => $workload['class_id'], 'display_name' => $workload['subject_name'],
'lessons_per_week' => $workload['lessons_per_week'], 'has_double_lesson' => $workload['has_double_lesson'], 'lessons_per_week' => $workload['lessons_per_week'], 'has_double_lesson' => $workload['has_double_lesson'],
'component_lessons' => [$workload] 'component_lessons' => [$workload],
'priority' => $workload['has_double_lesson'] ? 2 : 1
]; ];
if ($lesson['has_double_lesson'] && $lesson['lessons_per_week'] >= 2) {
$double_lessons[] = $lesson;
for ($i = 0; $i < $lesson['lessons_per_week'] - 2; $i++) $single_lessons[] = $lesson;
} else {
for ($i = 0; $i < $lesson['lessons_per_week']; $i++) $single_lessons[] = $lesson;
}
} }
} }
// 3. Explode lessons into single and double instances
$final_lesson_list = [];
foreach ($all_lessons as $lesson_block) {
$num_doubles = 0;
$num_singles = $lesson_block['lessons_per_week'];
if ($lesson_block['has_double_lesson'] && $lesson_block['lessons_per_week'] >= 2) {
$num_doubles = 1;
$num_singles -= 2;
}
for ($i=0; $i < $num_doubles; $i++) {
$final_lesson_list[] = ['is_double' => true, 'lesson_details' => $lesson_block];
}
for ($i=0; $i < $num_singles; $i++) {
$final_lesson_list[] = ['is_double' => false, 'lesson_details' => $lesson_block];
}
}
// 4. Sort by priority (desc) and then shuffle to vary timetable
usort($final_lesson_list, function($a, $b) {
$prio_a = $a['lesson_details']['priority'];
$prio_b = $b['lesson_details']['priority'];
if ($prio_a != $prio_b) return $prio_b - $prio_a;
if ($a['is_double'] != $b['is_double']) return $b['is_double'] - $a['is_double'];
return rand(-1, 1);
});
// --- Placement using Scoring --- // --- Placement using Scoring ---
$all_class_ids = array_column($classes, 'id'); $all_class_ids = array_column($classes, 'id');
$all_lessons_in_order = [
'horizontal_doubles' => $horizontal_elective_doubles, 'doubles' => $double_lessons,
'horizontal_singles' => $horizontal_elective_singles, 'singles' => $single_lessons
];
foreach ($all_lessons_in_order as $type => $lessons) { foreach ($final_lesson_list as $lesson_item) {
shuffle($lessons); $lesson = $lesson_item['lesson_details'];
foreach ($lessons as $lesson) { $is_double = $lesson_item['is_double'];
$is_double = ($type === 'doubles' || $type === 'horizontal_doubles');
$best_slot = find_best_slot_for_lesson($lesson, $is_double, $class_timetables, $teacher_timetables, $all_class_ids, $days_of_week, $periods_per_day);
if ($best_slot) { $best_slot = find_best_slot_for_lesson($lesson, $is_double, $class_timetables, $teacher_timetables, $all_class_ids, $days_of_week, $periods_per_day);
$day = $best_slot['day'];
$period = $best_slot['period'];
$class_ids_to_place = ($lesson['type'] === 'horizontal_elective') ? $lesson['participating_class_ids'] : [$lesson['class_id']];
$teachers_to_place = array_unique(array_column($lesson['component_lessons'], 'teacher_id'));
$subject_id = null; if ($best_slot) {
$teacher_id = null; $day = $best_slot['day'];
if ($lesson['type'] === 'single' && count($lesson['component_lessons']) === 1) { $period = $best_slot['period'];
$subject_id = $lesson['component_lessons'][0]['subject_id']; $class_ids_to_place = ($lesson['type'] === 'horizontal_elective') ? $lesson['participating_class_ids'] : [$lesson['class_id']];
$teacher_id = $lesson['component_lessons'][0]['teacher_id']; $teachers_to_place = array_unique(array_column($lesson['component_lessons'], 'teacher_id'));
$subject_id = null;
$teacher_id = null;
// For single-teacher, single-subject lessons, store the IDs directly
if (count($lesson['component_lessons']) === 1) {
$subject_id = $lesson['component_lessons'][0]['subject_id'];
$teacher_id = $lesson['component_lessons'][0]['teacher_id'];
}
$lesson_info = [
'subject_id' => $subject_id,
'teacher_id' => $teacher_id,
'subject_name' => $lesson['display_name'],
'teacher_name' => count($teachers_to_place) > 1 ? 'Multiple' : $lesson['component_lessons'][0]['teacher_name'],
'is_double' => $is_double,
'is_elective' => $lesson['type'] === 'elective',
'is_horizontal_elective' => $lesson['type'] === 'horizontal_elective'
];
if ($is_double) {
foreach ($class_ids_to_place as $cid) {
$class_timetables[$cid][$day][$period] = $lesson_info;
$class_timetables[$cid][$day][$period + 1] = $lesson_info;
} }
foreach ($teachers_to_place as $tid) {
$lesson_info = [ $teacher_timetables[$tid][$day][$period] = true;
'subject_id' => $subject_id, $teacher_timetables[$tid][$day][$period + 1] = true;
'teacher_id' => $teacher_id,
'subject_name' => $lesson['display_name'],
'teacher_name' => count($teachers_to_place) > 1 ? 'Multiple' : $lesson['component_lessons'][0]['teacher_name'],
'is_double' => $is_double,
'is_elective' => $lesson['type'] === 'elective',
'is_horizontal_elective' => $lesson['type'] === 'horizontal_elective'
];
if ($is_double) {
foreach ($class_ids_to_place as $cid) {
$class_timetables[$cid][$day][$period] = $lesson_info;
$class_timetables[$cid][$day][$period + 1] = $lesson_info;
}
foreach ($teachers_to_place as $tid) {
$teacher_timetables[$tid][$day][$period] = true;
$teacher_timetables[$tid][$day][$period + 1] = true;
}
} else {
foreach ($class_ids_to_place as $cid) $class_timetables[$cid][$day][$period] = $lesson_info;
foreach ($teachers_to_place as $tid) $teacher_timetables[$tid][$day][$period] = true;
} }
} else {
foreach ($class_ids_to_place as $cid) $class_timetables[$cid][$day][$period] = $lesson_info;
foreach ($teachers_to_place as $tid) $teacher_timetables[$tid][$day][$period] = true;
} }
} }
} }
@ -296,9 +332,9 @@ function save_timetable($pdo, $class_timetables, $timeslots) {
':teacher_id' => $lesson['teacher_id'], ':teacher_id' => $lesson['teacher_id'],
':lesson_display_name' => $lesson['subject_name'], ':lesson_display_name' => $lesson['subject_name'],
':teacher_display_name' => $lesson['teacher_name'], ':teacher_display_name' => $lesson['teacher_name'],
':is_double' => $lesson['is_double'], ':is_double' => (int)$lesson['is_double'],
':is_elective' => $lesson['is_elective'], ':is_elective' => (int)$lesson['is_elective'],
':is_horizontal_elective' => $lesson['is_horizontal_elective'] ':is_horizontal_elective' => (int)$lesson['is_horizontal_elective']
]); ]);
} }
} }