-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalendar_events.php
More file actions
250 lines (224 loc) · 8.93 KB
/
Copy pathcalendar_events.php
File metadata and controls
250 lines (224 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<?php
/**
* Calendar Events API Endpoint
*
* Returns a JSON array of events for FullCalendar.
* Fetches tasks and reminders for the logged-in user within a date range.
* FullCalendar sends ?start=YYYY-MM-DD&end=YYYY-MM-DD automatically.
*/
require 'session_config.php';
require 'dbcon.php';
header('Content-Type: application/json');
// Auth check
if (!isset($_SESSION['username'])) {
echo json_encode(['error' => 'Authentication required.']);
exit;
}
$currentUserId = $_SESSION['user_id'];
$isAdmin = (isset($_SESSION['role']) && $_SESSION['role'] === 'admin');
// View mode: 'all' shows everything (admin only), 'mine' filters to current user
$viewMode = $_GET['view'] ?? ($isAdmin ? 'all' : 'mine');
if (!$isAdmin) {
$viewMode = 'mine'; // Non-admins always see only their own
}
$showAll = ($viewMode === 'all');
// Parse date range from FullCalendar
$start = $_GET['start'] ?? date('Y-m-01');
$end = $_GET['end'] ?? date('Y-m-t');
// Validate date format
if (!preg_match('/^\d{4}-\d{2}-\d{2}/', $start) || !preg_match('/^\d{4}-\d{2}-\d{2}/', $end)) {
echo json_encode(['error' => 'Invalid date format.']);
exit;
}
// Extract just the date part (FullCalendar may send datetime strings)
$start = substr($start, 0, 10);
$end = substr($end, 0, 10);
// Fetch users lookup for name resolution
$userQuery = "SELECT id, name FROM users";
$userResult = $con->query($userQuery);
$users = $userResult ? array_column($userResult->fetch_all(MYSQLI_ASSOC), 'name', 'id') : [];
$events = [];
// Status color map
$colorMap = [
'Pending' => '#dc3545',
'In Progress' => '#ffc107',
'Completed' => '#198754',
];
$textColorMap = [
'Pending' => '#ffffff',
'In Progress' => '#000000',
'Completed' => '#ffffff',
];
// ============================================================
// FETCH TASKS WITH completion_date IN RANGE
// ============================================================
if ($showAll) {
$taskSQL = "SELECT * FROM tasks
WHERE completion_date IS NOT NULL
AND completion_date BETWEEN ? AND ?
ORDER BY completion_date ASC";
$stmt = $con->prepare($taskSQL);
$stmt->bind_param("ss", $start, $end);
} else {
$taskSQL = "SELECT * FROM tasks
WHERE completion_date IS NOT NULL
AND completion_date BETWEEN ? AND ?
AND (assigned_by = ? OR FIND_IN_SET(?, assigned_to))
ORDER BY completion_date ASC";
$stmt = $con->prepare($taskSQL);
$stmt->bind_param("ssii", $start, $end, $currentUserId, $currentUserId);
}
$stmt->execute();
$taskResult = $stmt->get_result();
while ($task = $taskResult->fetch_assoc()) {
$events[] = buildTaskEvent($task, $task['completion_date'], $users, $colorMap, $textColorMap);
}
$stmt->close();
// ============================================================
// FETCH TASKS WITHOUT completion_date (show on creation_date)
// ============================================================
if ($showAll) {
$taskSQL2 = "SELECT * FROM tasks
WHERE completion_date IS NULL
AND DATE(creation_date) BETWEEN ? AND ?
ORDER BY creation_date ASC";
$stmt2 = $con->prepare($taskSQL2);
$stmt2->bind_param("ss", $start, $end);
} else {
$taskSQL2 = "SELECT * FROM tasks
WHERE completion_date IS NULL
AND DATE(creation_date) BETWEEN ? AND ?
AND (assigned_by = ? OR FIND_IN_SET(?, assigned_to))
ORDER BY creation_date ASC";
$stmt2 = $con->prepare($taskSQL2);
$stmt2->bind_param("ssii", $start, $end, $currentUserId, $currentUserId);
}
$stmt2->execute();
$taskResult2 = $stmt2->get_result();
while ($task = $taskResult2->fetch_assoc()) {
$eventDate = date('Y-m-d', strtotime($task['creation_date']));
$events[] = buildTaskEvent($task, $eventDate, $users, $colorMap, $textColorMap);
}
$stmt2->close();
// ============================================================
// FETCH AND EXPAND REMINDERS
// ============================================================
if ($showAll) {
$reminderSQL = "SELECT * FROM reminders WHERE status = 'active'";
$rStmt = $con->prepare($reminderSQL);
} else {
$reminderSQL = "SELECT * FROM reminders
WHERE status = 'active'
AND (assigned_by = ? OR FIND_IN_SET(?, assigned_to))";
$rStmt = $con->prepare($reminderSQL);
$rStmt->bind_param("ii", $currentUserId, $currentUserId);
}
$rStmt->execute();
$reminderResult = $rStmt->get_result();
$rangeStart = new DateTime($start);
$rangeEnd = new DateTime($end);
while ($reminder = $reminderResult->fetch_assoc()) {
$occurrences = [];
switch ($reminder['recurrence_type']) {
case 'daily':
$current = clone $rangeStart;
while ($current <= $rangeEnd) {
$occurrences[] = $current->format('Y-m-d');
$current->modify('+1 day');
}
break;
case 'weekly':
$dayOfWeek = $reminder['day_of_week'];
if ($dayOfWeek) {
$current = clone $rangeStart;
while ($current->format('l') !== $dayOfWeek) {
$current->modify('+1 day');
}
while ($current <= $rangeEnd) {
$occurrences[] = $current->format('Y-m-d');
$current->modify('+7 days');
}
}
break;
case 'monthly':
$dayOfMonth = (int)$reminder['day_of_month'];
if ($dayOfMonth > 0) {
$current = clone $rangeStart;
$current->setDate((int)$current->format('Y'), (int)$current->format('m'), 1);
while ($current <= $rangeEnd) {
$lastDay = (int)$current->format('t');
$targetDay = min($dayOfMonth, $lastDay);
$occurrenceDate = clone $current;
$occurrenceDate->setDate(
(int)$current->format('Y'),
(int)$current->format('m'),
$targetDay
);
if ($occurrenceDate >= $rangeStart && $occurrenceDate <= $rangeEnd) {
$occurrences[] = $occurrenceDate->format('Y-m-d');
}
$current->modify('+1 month');
}
}
break;
}
// Resolve assigned_to names
$assignedToNames = array_map(function ($id) use ($users) {
return $users[trim($id)] ?? 'Unknown';
}, array_filter(explode(',', $reminder['assigned_to'])));
foreach ($occurrences as $date) {
$events[] = [
'id' => 'reminder-' . $reminder['id'] . '-' . $date,
'title' => $reminder['title'],
'start' => $date,
'allDay' => true,
'backgroundColor' => '#6f42c1',
'borderColor' => '#6f42c1',
'textColor' => '#ffffff',
'extendedProps' => [
'type' => 'reminder',
'reminderId' => (int)$reminder['id'],
'description' => $reminder['description'],
'recurrenceType' => $reminder['recurrence_type'],
'timeOfDay' => $reminder['time_of_day'],
'assignedBy' => $users[$reminder['assigned_by']] ?? 'Unknown',
'assignedTo' => implode(', ', $assignedToNames),
'cageId' => $reminder['cage_id'],
'status' => $reminder['status'],
],
];
}
}
$rStmt->close();
// Output
echo json_encode($events);
$con->close();
// ============================================================
// HELPER FUNCTION
// ============================================================
function buildTaskEvent($task, $eventDate, $users, $colorMap, $textColorMap) {
$assignedToNames = array_map(function ($id) use ($users) {
return $users[trim($id)] ?? 'Unknown';
}, array_filter(explode(',', $task['assigned_to'])));
return [
'id' => 'task-' . $task['id'],
'title' => $task['title'],
'start' => $eventDate,
'allDay' => true,
'backgroundColor' => $colorMap[$task['status']] ?? '#0d6efd',
'borderColor' => $colorMap[$task['status']] ?? '#0d6efd',
'textColor' => $textColorMap[$task['status']] ?? '#ffffff',
'extendedProps' => [
'type' => 'task',
'taskId' => (int)$task['id'],
'description' => $task['description'],
'status' => $task['status'],
'assignedBy' => $users[$task['assigned_by']] ?? 'Unknown',
'assignedTo' => implode(', ', $assignedToNames),
'completionDate' => $task['completion_date'],
'creationDate' => $task['creation_date'],
'cageId' => $task['cage_id'],
],
];
}
?>