'Unauthorized']);
exit;
}
$teacherID = $_POST['Teacher_ID'] ?? '';
$year = (int)($_POST['Semester_Year'] ?? 0);
if (!$teacherID || !$year) {
echo json_encode(['error' => 'Missing parameters']);
exit;
}
// Semester: First Monday of August (year) to June 30 (year+1)
$augustFirst = new DateTime("$year-08-01");
$dayOfWeek = (int)$augustFirst->format('N');
$daysUntilMonday = ($dayOfWeek === 1) ? 0 : (8 - $dayOfWeek) % 7;
$semesterStart = clone $augustFirst;
$semesterStart->modify("+$daysUntilMonday days");
$semesterEnd = new DateTime(($year + 1) . '-06-30');
$startStr = $semesterStart->format('Y-m-d');
$endStr = $semesterEnd->format('Y-m-d');
$stmt = $mysqli->prepare("
SELECT
c.Course_Name,
cgsm.Course_Hours,
tca.Time_Slot,
tca.Start_Date,
tca.End_Date,
mg.Group_Name,
p.Program_Name,
tca.Course_ID,
tca.Group_ID,
tca.Program_ID
FROM teacher_course_assignments tca
JOIN course_group_schedule_main cgsm ON tca.Schedule_ID = cgsm.Schedule_ID
JOIN Courses c ON tca.Course_ID = c.Course_ID
LEFT JOIN manager_group_name mg ON tca.Group_ID = mg.Group_ID
LEFT JOIN Programs p ON tca.Program_ID = p.Program_ID
WHERE tca.Teacher_ID = ?
AND tca.Start_Date >= ?
AND tca.End_Date <= ?
ORDER BY tca.Start_Date
");
$stmt->bind_param('iss', $teacherID, $startStr, $endStr);
$stmt->execute();
$result = $stmt->get_result();
$rows = [];
$totalHours = 0;
$countedCourses = [];
while ($r = $result->fetch_assoc()) {
// Only count hours once per unique Course + Group + Program
$courseKey = $r['Program_ID'] . '|' . $r['Group_ID'] . '|' . $r['Course_ID'];
if (!isset($countedCourses[$courseKey])) {
$countedCourses[$courseKey] = true;
$totalHours += (int)$r['Course_Hours'];
}
// Remove dedup key columns from output
unset($r['Course_ID'], $r['Group_ID'], $r['Program_ID']);
$rows[] = $r;
}
$stmt->close();
echo json_encode(['rows' => $rows, 'totalHours' => $totalHours]);