false, 'message' => 'Invalid activity ID']); exit(); } // Check if activity exists $check_sql = "SELECT id, name, date, time_in, time_out FROM activities WHERE id = ?"; $check_stmt = mysqli_prepare($conn, $check_sql); mysqli_stmt_bind_param($check_stmt, "i", $activity_id); mysqli_stmt_execute($check_stmt); $result = mysqli_stmt_get_result($check_stmt); $activity = mysqli_fetch_assoc($result); if (!$activity) { echo json_encode(['success' => false, 'message' => 'Activity not found']); exit(); } // Check if activity is currently ongoing $today = date('Y-m-d'); $current_time = date('H:i:s'); if ($activity['date'] == $today && $current_time >= $activity['time_in'] && $current_time <= $activity['time_out']) { echo json_encode([ 'success' => false, 'message' => 'Cannot delete an activity that is currently ongoing. Please wait until it ends.' ]); exit(); } // Start transaction mysqli_begin_transaction($conn); try { // Get attendance count for logging $attendance_count_sql = "SELECT COUNT(*) as count FROM attendance WHERE activity_id = ?"; $attendance_stmt = mysqli_prepare($conn, $attendance_count_sql); mysqli_stmt_bind_param($attendance_stmt, "i", $activity_id); mysqli_stmt_execute($attendance_stmt); $attendance_result = mysqli_stmt_get_result($attendance_stmt); $attendance_count = mysqli_fetch_assoc($attendance_result)['count']; // First, delete attendance records $delete_attendance_sql = "DELETE FROM attendance WHERE activity_id = ?"; $stmt1 = mysqli_prepare($conn, $delete_attendance_sql); mysqli_stmt_bind_param($stmt1, "i", $activity_id); $attendance_deleted = mysqli_stmt_execute($stmt1); if (!$attendance_deleted) { throw new Exception('Failed to delete attendance records'); } // Then delete the activity $delete_activity_sql = "DELETE FROM activities WHERE id = ?"; $stmt2 = mysqli_prepare($conn, $delete_activity_sql); mysqli_stmt_bind_param($stmt2, "i", $activity_id); $activity_deleted = mysqli_stmt_execute($stmt2); if (!$activity_deleted) { throw new Exception('Failed to delete activity'); } // Commit transaction mysqli_commit($conn); // Log the deletion $log_message = "Activity deleted via AJAX: '{$activity['name']}' (ID: {$activity_id}). "; $log_message .= "Deleted {$attendance_count} attendance records."; log_action($conn, $_SESSION['user_id'], 'delete_activity', $log_message); echo json_encode([ 'success' => true, 'message' => 'Activity deleted successfully!', 'deleted_id' => $activity_id, 'attendance_count' => $attendance_count ]); } catch (Exception $e) { mysqli_rollback($conn); echo json_encode([ 'success' => false, 'message' => 'Error: ' . $e->getMessage() ]); } exit(); } // Generate CSRF token for this page $csrf_token = bin2hex(random_bytes(32)); $_SESSION['csrf_token'] = $csrf_token; // Get all activities with related data $activities = []; $sql = "SELECT a.*, u.full_name as created_by_name, c.code as course_code, c.name as course_name, d.code as department_code, d.name as department_name FROM activities a LEFT JOIN users u ON a.created_by = u.id LEFT JOIN courses c ON a.course_id = c.id LEFT JOIN departments d ON a.department_id = d.id ORDER BY a.date DESC, a.time_in ASC"; $result = query($conn, $sql); while ($row = mysqli_fetch_assoc($result)) { $activities[] = $row; } // Statistics calculation $today = date('Y-m-d'); $upcoming_count = 0; $ongoing_count = 0; $past_count = 0; foreach ($activities as $activity) { $activity_date = $activity['date']; $current_time = date('H:i:s'); $activity_start = $activity['time_in']; $activity_end = $activity['time_out']; if ($activity_date > $today) { $upcoming_count++; } elseif ($activity_date == $today && $current_time >= $activity_start && $current_time <= $activity_end) { $ongoing_count++; } elseif ($activity_date < $today || ($activity_date == $today && $current_time > $activity_end)) { $past_count++; } } include '../includes/header.php'; ?>

Manage Activities

Schedule and manage activities, events, and classes.

Schedule New Activity
Total Activities
All scheduled
Upcoming
Future activities
Ongoing
Happening now
Past Activities
Completed
$today || ($activity['date'] == $today && date('H:i:s') < $activity['time_in'])): $has_upcoming = true; ?>
Activity Date & Time Location Participants Status Actions

-
All Students'; break; case 'specific_course': echo '' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . ''; break; case 'specific_department': echo '' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . ''; break; } ?> Active Inactive

No upcoming activities scheduled

= $activity['time_in'] && $current_time <= $activity['time_out']): $has_ongoing = true; // Calculate time remaining $end_time = strtotime($activity['time_out']); $remaining = $end_time - time(); $hours = floor($remaining / 3600); $minutes = floor(($remaining % 3600) / 60); ?>
Activity Time Location Duration Participants Actions

-
Ends in
' . $duration . ' hours'; ?> All Students'; break; case 'specific_course': echo '' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . ''; break; case 'specific_department': echo '' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . ''; break; } ?>

No ongoing activities at the moment

$activity['time_out'])): $has_past = true; // Get attendance count for this activity $attendance_sql = "SELECT COUNT(*) as count FROM attendance WHERE activity_id = " . $activity['id']; $attendance_result = query($conn, $attendance_sql); $attendance_count = mysqli_fetch_assoc($attendance_result)['count']; ?>
Activity Date Time Location Attendance Actions

- attended

No past activities found

Activity Date & Time Location Participants Created By Status Actions

No activities found. Schedule your first activity!


-
All Students'; break; case 'specific_course': echo '' . htmlspecialchars($activity['course_code'] ?? 'Specific Course') . ''; break; case 'specific_department': echo '' . htmlspecialchars($activity['department_name'] ?? 'Specific Department') . ''; break; } ?>
Active Inactive
$(document).ready(function() { let currentActivityId = null; // Initialize DataTables const upcomingTable = $("#upcomingTable").DataTable({ pageLength: 10, lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], order: [[1, "asc"]], responsive: true, columnDefs: [ { orderable: false, targets: [5] } ] }); const ongoingTable = $("#ongoingTable").DataTable({ pageLength: 10, lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], order: [[1, "asc"]], responsive: true, columnDefs: [ { orderable: false, targets: [5] } ] }); const pastTable = $("#pastTable").DataTable({ pageLength: 10, lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], order: [[1, "desc"]], responsive: true, columnDefs: [ { orderable: false, targets: [5] } ] }); const allTable = $("#allTable").DataTable({ pageLength: 10, lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], order: [[1, "desc"]], responsive: true, columnDefs: [ { orderable: false, targets: [6] } ] }); // Delete button click $(document).on("click", ".delete-activity-btn", function() { currentActivityId = $(this).data("id"); const activityName = $(this).data("name"); $("#deleteActivityName").text(activityName); $("#deleteModal").modal("show"); }); // Confirm delete $("#confirmDeleteBtn").click(function() { if (!currentActivityId) return; const $btn = $(this); const originalText = $btn.html(); $btn.html(\' Deleting...\').prop("disabled", true); $.ajax({ url: "manage_activities.php", method: "POST", data: { ajax_delete: true, activity_id: currentActivityId, csrf_token: "' . $csrf_token . '" }, dataType: "json", success: function(response) { $btn.html(originalText).prop("disabled", false); $("#deleteModal").modal("hide"); if (response.success) { // Remove row from all tables $("#activityRow-" + currentActivityId).fadeOut(300, function() { $(this).remove(); // Update counters updateCounters(); // Show success message showMessage(response.message, "success"); }); } else { showMessage(response.message, "danger"); } }, error: function(xhr, status, error) { $btn.html(originalText).prop("disabled", false); showMessage("Error deleting activity. Please try again.", "danger"); console.error("Delete error:", error); } }); }); function updateCounters() { // Get current counts const totalRows = $("#allActivitiesBody tr:not(#noActivitiesRow)").length; const upcomingRows = $("#upcomingTable tbody tr:not(#noUpcomingRow)").length; const ongoingRows = $("#ongoingTable tbody tr:not(#noOngoingRow)").length; const pastRows = $("#pastTable tbody tr:not(#noPastRow)").length; // Update counters $("#activitiesCount").text(totalRows); $("#totalCount").text(totalRows); $("#upcomingBadge").text(upcomingRows); // Update badges $("#upcoming-tab .badge").text(upcomingRows); $("#ongoing-tab .badge").text(ongoingRows); $("#past-tab .badge").text(pastRows); $("#all-tab .badge").text(totalRows); // Show/hide empty messages if (upcomingRows === 0 && $("#noUpcomingRow").length === 0) { $("#upcomingTable tbody").append(\'

No upcoming activities scheduled

\'); } if (ongoingRows === 0 && $("#noOngoingRow").length === 0) { $("#ongoingTable tbody").append(\'

No ongoing activities at the moment

\'); } if (pastRows === 0 && $("#noPastRow").length === 0) { $("#pastTable tbody").append(\'

No past activities found

\'); } if (totalRows === 0 && $("#noActivitiesRow").length === 0) { $("#allActivitiesBody").append(\'

No activities found. Schedule your first activity!

\'); } } function showMessage(message, type) { const $alert = $("#messageAlert"); $alert.removeClass("alert-success alert-danger alert-warning alert-info") .addClass("alert-" + type) .html(\'\' + message + \'\') .find("i").addClass(type === "success" ? "bi-check-circle" : "bi-exclamation-circle").end() .show(); // Auto-hide after 5 seconds setTimeout(() => { $alert.fadeOut(); }, 5000); } // Auto-refresh ongoing tab setInterval(function() { const activeTab = document.querySelector("#activityTabs .nav-link.active"); if (activeTab && activeTab.id === "ongoing-tab") { location.reload(); } }, 60000); // Initialize counters updateCounters(); }); '; include '../includes/footer.php'; ?>