/home/techb158/workloadmatch.com/workloadmatch.com/BackUp/Manager
Edit: /home/techb158/workloadmatch.com/workloadmatch.com/BackUp/Manager/ajax_replace_saturday - Copy.php (13452B)
prepare("SELECT Time_Slot, Time_From, Time_To, class_days, Weekend_Class, Group_Name FROM Manager_Group_Name WHERE Group_ID = ?");
$stmt->bind_param("i", $Group_ID);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
// Retrieve time slots for the group
function fetch_slot_times($mysqli, $slotLabels, $managerStart, $managerEnd) {
$timeFrom = [];
$timeTo = [];
foreach ($slotLabels as $label) {
$label = trim($label);
$stmt = $mysqli->prepare("SELECT Time_From, Time_To FROM Time_Slot_Programs WHERE Time_Slot = ?");
$stmt->bind_param("s", $label);
$stmt->execute();
$result = $stmt->get_result();
$validSlotFound = false;
while ($row = $result->fetch_assoc()) {
$slotStart = new DateTime($row['Time_From']);
$slotEnd = new DateTime($row['Time_To']);
if ($slotStart >= $managerStart && $slotEnd <= $managerEnd) {
$timeFrom[] = $slotStart->format("H:i:s");
$timeTo[] = $slotEnd->format("H:i:s");
$validSlotFound = true;
break;
}
}
if (!$validSlotFound && count($slotLabels) === 1) {
$timeFrom[] = $managerStart->format("H:i:s");
$timeTo[] = $managerEnd->format("H:i:s");
}
}
return [$timeFrom, $timeTo];
}
// Collect all holiday dates in the current year
function get_holidays($mysqli, $Start_Date) {
$holidays = [];
$res = $mysqli->query("SELECT Event_Start, Event_End FROM Events WHERE Calendar_Year = YEAR('$Start_Date')");
while ($row = $res->fetch_assoc()) {
$start = new DateTime($row['Event_Start']);
$end = new DateTime($row['Event_End']);
while ($start <= $end) {
$holidays[] = $start->format('Y-m-d');
$start->modify('+1 day');
}
}
return $holidays;
}
// Collect all retake dates for the group and program
function get_retake_dates($mysqli, $Program_ID, $Group_ID) {
$retakeDates = [];
$stmt = $mysqli->prepare("SELECT Retake_Date FROM Retake_Records WHERE Program_ID = ? AND Group_ID = ?");
$stmt->bind_param("ii", $Program_ID, $Group_ID);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
$retakeDates[] = $row['Retake_Date'];
}
return $retakeDates;
}
// Generate all valid class dates, excluding holidays, retakes, and July
function generate_valid_dates($Start_Date, $End_Date, $classDays, $holidayDates, $retakeDates) {
$validDates = [];
$cur = new DateTime($Start_Date);
$end = $End_Date ? new DateTime($End_Date) : null;
while (!$end || $cur <= $end) {
$day = $cur->format('l');
$dateStr = $cur->format('Y-m-d');
$month = (int) $cur->format('m');
if ($month === 7 || !in_array($day, $classDays) || in_array($dateStr, $holidayDates) || in_array($dateStr, $retakeDates)) {
$cur->modify('+1 day');
continue;
}
$validDates[] = $dateStr;
$cur->modify('+1 day');
if ($end === null && count($validDates) > 365) break; // Prevent infinite loop in fallback
}
return $validDates;
}
// Calculate the average duration of one session
function calculate_session_length($timeFrom, $timeTo) {
$sessionLength = 0;
foreach ($timeFrom as $i => $from) {
$fromTime = new DateTime($from);
$toTime = new DateTime($timeTo[$i]);
$sessionLength += ($toTime->getTimestamp() - $fromTime->getTimestamp()) / 3600;
}
$slotCount = count($timeFrom);
return $slotCount > 0 ? $sessionLength / $slotCount : 3;
}
// Calculate the number of sessions required for each course
function calculate_course_sessions($mysqli, $Program_ID, $sessionLength) {
$courseSessions = [];
$res = $mysqli->query("SELECT Course_ID, Course_Time FROM Courses WHERE Program_ID = $Program_ID");
while ($row = $res->fetch_assoc()) {
$courseID = $row['Course_ID'];
$courseHours = $row['Course_Time'];
$courseSessions[$courseID] = ceil($courseHours / $sessionLength);
}
return $courseSessions;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
error_log("AJAX Request Received:\n" . print_r($_POST, true));
$saturdayDate = $_POST['date'] ?? '';
$Program_ID = intval($_POST['Program_ID'] ?? 0);
$Group_ID = intval($_POST['Group_ID'] ?? 0);
$Start_Date = $_POST['Start_Date'] ?? '';
$End_Date = $_POST['End_Date'] ?? '';
$selectedCourses = $_POST['Selected_Courses'] ?? [];
$priorityCourses = $_POST['Priority_Course'] ?? [];
if (!$Program_ID || !$Group_ID || !$saturdayDate || !$Start_Date) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields.']);
exit;
}
$group = get_group_info($mysqli, $Group_ID);
if (!$group) {
echo json_encode(['status' => 'error', 'message' => 'Group info not found.']);
exit;
}
$classDays = explode(',', $group['class_days']);
$slotLabels = explode(',', $group['Time_Slot']);
$managerStart = new DateTime(trim($group['Time_From']));
$managerEnd = new DateTime(trim($group['Time_To']));
list($timeFrom, $timeTo) = fetch_slot_times($mysqli, $slotLabels, $managerStart, $managerEnd);
$sessionLength = calculate_session_length($timeFrom, $timeTo);
$courseSessions = calculate_course_sessions($mysqli, $Program_ID, $sessionLength);
$holidayDates = get_holidays($mysqli, $Start_Date);
$retakeDates = get_retake_dates($mysqli, $Program_ID, $Group_ID);
// Remove the selected Saturday from dates
$validDates = generate_valid_dates($Start_Date, $End_Date, $classDays, $holidayDates, $retakeDates);
$validDates = array_filter($validDates, fn($d) => $d !== $saturdayDate);
// Find a new weekday to insert
$cur = new DateTime($saturdayDate);
$cur->modify('+1 day');
$replacementDate = '';
while (true) {
$day = $cur->format('l');
$dateStr = $cur->format('Y-m-d');
if ($day !== 'Saturday' && in_array($day, $classDays) && !in_array($dateStr, $holidayDates) && !in_array($dateStr, $retakeDates)) {
$replacementDate = $dateStr;
break;
}
$cur->modify('+1 day');
}
$validDates[] = $replacementDate;
sort($validDates);
// Re-generate schedule
usort($selectedCourses, function ($a, $b) use ($priorityCourses) {
$priorityA = $priorityCourses[$a] ?? PHP_INT_MAX;
$priorityB = $priorityCourses[$b] ?? PHP_INT_MAX;
return $priorityA <=> $priorityB;
});
$schedule = [];
$remainingSessions = [];
foreach ($selectedCourses as $courseID) {
$remainingSessions[$courseID] = $courseSessions[$courseID] ?? 0;
}
$courseQueue = $selectedCourses;
$currentCourses = [0 => null, 1 => null];
foreach ([0, 1] as $slotIndex) {
foreach ($courseQueue as $courseID) {
if ($remainingSessions[$courseID] > 0) {
$currentCourses[$slotIndex] = $courseID;
break;
}
}
}
$courseNames = [];
$courseRes = $mysqli->query("SELECT Course_ID, Course_Name FROM Courses");
while ($row = $courseRes->fetch_assoc()) {
$courseNames[$row['Course_ID']] = $row['Course_Name'];
}
foreach ($validDates as $date) {
foreach ([0, 1] as $slotIndex) {
$from = $timeFrom[$slotIndex] ?? null;
$to = $timeTo[$slotIndex] ?? null;
if (!$from || !$to || !$currentCourses[$slotIndex]) continue;
$courseID = $currentCourses[$slotIndex];
$schedule[] = [
'Date' => $date,
'Slot' => "Slot " . ($slotIndex + 1),
'Time' => format_time_slot_range($slotLabels[$slotIndex], $from, $to, (new DateTime($date))->format('l')),
'Course_ID' => $courseID
];
$remainingSessions[$courseID]--;
if ($remainingSessions[$courseID] <= 0) {
$currentCourses[$slotIndex] = null;
foreach ($courseQueue as $nextCourseID) {
if ($remainingSessions[$nextCourseID] > 0) {
$currentCourses[$slotIndex] = $nextCourseID;
break;
}
}
}
}
if (!$currentCourses[0] && !$currentCourses[1]) break;
}
ob_clean();
$table = "
\n| Date | Slot | Time | Course | Action |
\n";
foreach ($schedule as $row) {
$dayName = (new DateTime($row['Date']))->format('l');
$slotIndex = (int) filter_var($row['Slot'], FILTER_SANITIZE_NUMBER_INT) - 1;
$slotName = format_time_slot_label($slotLabels[$slotIndex], $dayName);
$courseName = $courseNames[$row['Course_ID']] ?? "Course #{$row['Course_ID']}";
$isSaturday = $dayName === 'Saturday';
$table .= "\n";
$table .= "| ($dayName) {$row['Date']} | \n";
$table .= "$slotName | \n";
$table .= "{$row['Time']} | \n";
$table .= "$courseName | \n";
$table .= "";
if ($isSaturday) {
$table .= " ";
} else {
$table .= "-";
}
$table .= " |
\n";
}
$table .= "
";
echo json_encode([
'status' => 'success',
'html' => $table
]);
exit;
}
/*
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$saturdayDate = $_POST['date'] ?? '';
$Program_ID = intval($_POST['Program_ID'] ?? 0);
$Group_ID = intval($_POST['Group_ID'] ?? 0);
error_log("🔧 [AJAX] Replace Request: " . print_r($_POST, true));
if (!$Program_ID || !$Group_ID || !$saturdayDate) {
echo json_encode(['status' => 'error', 'message' => 'Missing required data.']);
exit;
}
// Get group info
$group = get_group_info($mysqli, $Group_ID);
if (!$group) {
echo json_encode(['status' => 'error', 'message' => 'Group not found.']);
exit;
}
// Get class days, slots, time ranges
$classDays = explode(',', $group['class_days']);
$slotLabels = explode(',', $group['Time_Slot']);
$managerStart = new DateTime(trim($group['Time_From']));
$managerEnd = new DateTime(trim($group['Time_To']));
list($timeFrom, $timeTo) = fetch_slot_times($mysqli, $slotLabels, $managerStart, $managerEnd);
$holidayDates = get_holidays($mysqli, $saturdayDate);
$retakeDates = get_retake_dates($mysqli, $Program_ID, $Group_ID);
// Find next available weekday
$cur = new DateTime($saturdayDate);
$cur->modify('+1 day');
$replacementDate = '';
$maxAttempts = 20;
$tries = 0;
while ($tries < $maxAttempts) {
$day = $cur->format('l');
$dateStr = $cur->format('Y-m-d');
if ($day !== 'Saturday' && in_array($day, $classDays) && !in_array($dateStr, $holidayDates) && !in_array($dateStr, $retakeDates)) {
$replacementDate = $dateStr;
break;
}
$cur->modify('+1 day');
$tries++;
}
if (!$replacementDate) {
echo json_encode(['status' => 'error', 'message' => 'No replacement weekday found.']);
exit;
}
// Use first slot and time for simplicity
$slotIndex = 0;
$slotName = $slotLabels[$slotIndex] ?? 'Morning';
$slotTime = format_time_slot_range($slotName, $timeFrom[$slotIndex], $timeTo[$slotIndex], (new DateTime($replacementDate))->format('l'));
// Render new table row
$rowId = "row-$replacementDate";
$newRowHtml = "
" .
"| (" . (new DateTime($replacementDate))->format('l') . ") $replacementDate | " .
"$slotName | " .
"$slotTime | " .
"Replaced Saturday Class | " .
"- | " .
"
";
echo json_encode([
'status' => 'success',
'original' => $saturdayDate,
'replacement' => $replacementDate,
'newRowHtml' => $newRowHtml
]);
exit;
}
*/
// If not POST
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
exit;