-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanage_reminder.php
More file actions
934 lines (855 loc) · 40 KB
/
Copy pathmanage_reminder.php
File metadata and controls
934 lines (855 loc) · 40 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
<?php
/**
* Manage Reminders
*
* This script provides functionality for managing reminders in the database.
* It allows users to add new reminders, edit existing ones, and delete them.
* The interface includes a responsive popup form for data entry and a table for displaying existing reminders.
* The script uses PHP sessions for message handling and includes basic input sanitization for security.
*/
ob_start();
require 'session_config.php';
// Check if the user is logged in
if (!isset($_SESSION['username'])) {
header("Location: index.php");
exit;
}
// Generate CSRF token if not already set
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
require 'header.php';
require 'dbcon.php';
// Get the current user ID and name from the session
$currentUserId = $_SESSION['user_id'] ?? null;
$currentUserName = $_SESSION['name'] ?? '';
$isAdmin = (($_SESSION['role'] ?? '') === 'admin');
// Function to redirect with a message
function redirectToPage($message)
{
$_SESSION['message'] = $message;
header('Location: manage_reminder.php');
exit();
}
// Handle form submission for adding, editing, or deleting reminders
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Validate CSRF token
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed');
}
// View-only roles (vivarium_manager, iacuc_member) may read reminders but
// not create, edit, archive, restore or delete them. $uiCanWrite is set in
// header.php.
if (!$uiCanWrite) {
redirectToPage('Your role has view-only access and cannot modify reminders.');
}
// Determine the action to perform
if (isset($_POST['add']) || isset($_POST['edit'])) {
// Only read form fields for add/edit actions
$title = trim($_POST['title']);
$description = trim($_POST['description']);
$assignedBy = $currentUserId;
$assignedTo = implode(',', $_POST['assigned_to'] ?? []);
$recurrenceType = trim($_POST['recurrence_type']);
$dayOfWeek = !empty($_POST['day_of_week']) ? trim($_POST['day_of_week']) : null;
$dayOfMonth = !empty($_POST['day_of_month']) ? (int)$_POST['day_of_month'] : null;
$timeOfDay = trim($_POST['time_of_day']);
$status = trim($_POST['status']);
$cageId = empty($_POST['cage_id']) ? NULL : trim($_POST['cage_id']);
}
if (isset($_POST['add'])) {
// Multi-cage: create one reminder per selected cage (or one with NULL if none selected)
$cageIds = $_POST['cage_ids'] ?? [];
if (empty($cageIds)) {
$cageIds = [null]; // Single reminder with no cage
}
$stmt = $con->prepare("INSERT INTO reminders (cage_id, title, description, assigned_by, assigned_to, recurrence_type, day_of_week, day_of_month, time_of_day, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insertCount = 0;
$lastError = '';
foreach ($cageIds as $singleCageId) {
$singleCageId = !empty($singleCageId) ? trim($singleCageId) : null;
$stmt->bind_param("sssissssss", $singleCageId, $title, $description, $assignedBy, $assignedTo, $recurrenceType, $dayOfWeek, $dayOfMonth, $timeOfDay, $status);
if ($stmt->execute()) {
$insertCount++;
} else {
$lastError = $stmt->error;
}
}
$stmt->close();
if ($insertCount > 0) {
// Notify assigned-to users about the new reminder
try {
$notifAssignees = array_filter(array_map('intval', explode(',', $assignedTo)));
foreach ($notifAssignees as $uid) {
if ($uid > 0) {
$nTitle = "New Reminder: $title";
$nMessage = "$currentUserName created a reminder for you ($recurrenceType)";
$nLink = "manage_reminder.php";
$nStmt = $con->prepare("INSERT INTO notifications (user_id, title, message, link, type) VALUES (?, ?, ?, ?, 'reminder')");
$nStmt->bind_param("isss", $uid, $nTitle, $nMessage, $nLink);
$nStmt->execute();
$nStmt->close();
}
}
} catch (Exception $e) { error_log("Notification error: " . $e->getMessage()); }
$msg = $insertCount === 1 ? "Reminder added successfully." : "$insertCount reminders added successfully (one per cage).";
redirectToPage($msg);
} else {
redirectToPage("Error: " . $lastError);
}
} elseif (isset($_POST['edit'])) {
$id = (int)$_POST['id'];
$stmt = $con->prepare("UPDATE reminders SET cage_id = ?, title = ?, description = ?, assigned_to = ?, recurrence_type = ?, day_of_week = ?, day_of_month = ?, time_of_day = ?, status = ? WHERE id = ?");
$stmt->bind_param("sssisssssi", $cageId, $title, $description, $assignedTo, $recurrenceType, $dayOfWeek, $dayOfMonth, $timeOfDay, $status, $id);
if ($stmt->execute()) {
// Notify assigned-to users about the update
try {
$notifAssignees = array_filter(array_map('intval', explode(',', $assignedTo)));
foreach ($notifAssignees as $uid) {
if ($uid > 0) {
$nTitle = "Reminder Updated: $title";
$nMessage = "$currentUserName updated a reminder assigned to you";
$nLink = "manage_reminder.php";
$nStmt = $con->prepare("INSERT INTO notifications (user_id, title, message, link, type) VALUES (?, ?, ?, ?, 'reminder')");
$nStmt->bind_param("isss", $uid, $nTitle, $nMessage, $nLink);
$nStmt->execute();
$nStmt->close();
}
}
} catch (Exception $e) { error_log("Notification error: " . $e->getMessage()); }
redirectToPage("Reminder updated successfully.");
} else {
redirectToPage("Error: " . $stmt->error);
}
$stmt->close();
} elseif (isset($_POST['archive'])) {
$id = (int)$_POST['id'];
// Fetch reminder details for notification
$fetchStmt = $con->prepare("SELECT title, assigned_to FROM reminders WHERE id = ?");
$fetchStmt->bind_param("i", $id);
$fetchStmt->execute();
$fetchStmt->bind_result($archTitle, $archAssignedTo);
$fetchStmt->fetch();
$fetchStmt->close();
$stmt = $con->prepare("UPDATE reminders SET status = 'inactive' WHERE id = ?");
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
// Notify assigned-to users
try {
$notifAssignees = array_filter(array_map('intval', explode(',', $archAssignedTo)));
foreach ($notifAssignees as $uid) {
if ($uid > 0) {
$nTitle = "Reminder Archived: $archTitle";
$nMessage = "$currentUserName archived a reminder assigned to you";
$nLink = "manage_reminder.php";
$nStmt = $con->prepare("INSERT INTO notifications (user_id, title, message, link, type) VALUES (?, ?, ?, ?, 'reminder')");
$nStmt->bind_param("isss", $uid, $nTitle, $nMessage, $nLink);
$nStmt->execute();
$nStmt->close();
}
}
} catch (Exception $e) { error_log("Notification error: " . $e->getMessage()); }
redirectToPage("Reminder archived successfully.");
} else {
redirectToPage("Error: " . $stmt->error);
}
$stmt->close();
} elseif (isset($_POST['restore'])) {
$id = (int)$_POST['id'];
// Fetch reminder details for notification
$fetchStmt = $con->prepare("SELECT title, assigned_to FROM reminders WHERE id = ?");
$fetchStmt->bind_param("i", $id);
$fetchStmt->execute();
$fetchStmt->bind_result($restTitle, $restAssignedTo);
$fetchStmt->fetch();
$fetchStmt->close();
$stmt = $con->prepare("UPDATE reminders SET status = 'active' WHERE id = ?");
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
// Notify assigned-to users
try {
$notifAssignees = array_filter(array_map('intval', explode(',', $restAssignedTo)));
foreach ($notifAssignees as $uid) {
if ($uid > 0) {
$nTitle = "Reminder Restored: $restTitle";
$nMessage = "$currentUserName restored a reminder assigned to you";
$nLink = "manage_reminder.php";
$nStmt = $con->prepare("INSERT INTO notifications (user_id, title, message, link, type) VALUES (?, ?, ?, ?, 'reminder')");
$nStmt->bind_param("isss", $uid, $nTitle, $nMessage, $nLink);
$nStmt->execute();
$nStmt->close();
}
}
} catch (Exception $e) { error_log("Notification error: " . $e->getMessage()); }
$_SESSION['message'] = "Reminder restored successfully.";
header('Location: manage_reminder.php?show_archived=1');
exit();
} else {
$_SESSION['message'] = "Error: " . $stmt->error;
header('Location: manage_reminder.php?show_archived=1');
exit();
}
$stmt->close();
} elseif (isset($_POST['delete'])) {
$id = (int)$_POST['id'];
// Fetch reminder details for notification before deleting
$fetchStmt = $con->prepare("SELECT title, assigned_to FROM reminders WHERE id = ?");
$fetchStmt->bind_param("i", $id);
$fetchStmt->execute();
$fetchStmt->bind_result($delTitle, $delAssignedTo);
$fetchStmt->fetch();
$fetchStmt->close();
$stmt = $con->prepare("DELETE FROM reminders WHERE id = ?");
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
// Notify assigned-to users
try {
$notifAssignees = array_filter(array_map('intval', explode(',', $delAssignedTo)));
foreach ($notifAssignees as $uid) {
if ($uid > 0) {
$nTitle = "Reminder Deleted: $delTitle";
$nMessage = "$currentUserName permanently deleted a reminder";
$nLink = "manage_reminder.php";
$nStmt = $con->prepare("INSERT INTO notifications (user_id, title, message, link, type) VALUES (?, ?, ?, ?, 'reminder')");
$nStmt->bind_param("isss", $uid, $nTitle, $nMessage, $nLink);
$nStmt->execute();
$nStmt->close();
}
}
} catch (Exception $e) { error_log("Notification error: " . $e->getMessage()); }
$_SESSION['message'] = "Reminder deleted permanently.";
header('Location: manage_reminder.php?show_archived=1');
exit();
} else {
$_SESSION['message'] = "Error: " . $stmt->error;
header('Location: manage_reminder.php?show_archived=1');
exit();
}
$stmt->close();
}
}
// Fetch users for the dropdown
$userQuery = "SELECT id, name FROM users";
$userResult = $con->query($userQuery);
$users = $userResult ? array_column($userResult->fetch_all(MYSQLI_ASSOC), 'name', 'id') : [];
// Determine if showing archived or active reminders
$showArchived = isset($_GET['show_archived']) && $_GET['show_archived'] === '1';
$reminderStatus = $showArchived ? 'inactive' : 'active';
// Fetch reminders for display (filtered by status)
$reminderStmt = $con->prepare("SELECT * FROM reminders WHERE status = ?");
$reminderStmt->bind_param("s", $reminderStatus);
$reminderStmt->execute();
$reminderResult = $reminderStmt->get_result();
// Fetch cages for the dropdown
$cageQuery = "SELECT cage_id FROM cages";
$cageResult = $con->query($cageQuery);
$cages = $cageResult ? array_column($cageResult->fetch_all(MYSQLI_ASSOC), 'cage_id') : [];
ob_end_flush(); // Flush the output buffer
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Reminders</title>
<!-- Include necessary styles and scripts -->
<!-- Bootstrap 5.3 loaded via header.php -->
<!-- Font Awesome loaded via header.php -->
<!-- Select2 CSS loaded via header.php -->
<style>
/* Popup and Overlay Styles */
.popup-form,
.view-popup-form {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: var(--bs-body-bg);
padding: 20px;
border: 1px solid var(--bs-border-color);
border-radius: 10px;
z-index: 1000;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 800px;
overflow-y: auto;
max-height: 90vh;
}
.popup-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
/* Button and Form Styles */
.add-button {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-bottom: 20px;
}
.add-button .btn {
margin-bottom: 20px;
}
.ml-2 {
margin-left: 10px;
/* Adjust the spacing between buttons as needed */
}
.form-buttons {
display: flex;
gap: 10px;
justify-content: space-between;
}
.form-buttons button {
width: 100%;
margin-bottom: 10px;
}
.required-asterisk {
color: red;
}
.radio-group label {
margin-right: 15px;
}
.radio-group input[type="radio"] {
margin-right: 5px;
}
.form-control[readonly] {
background-color: var(--bs-tertiary-bg);
cursor: not-allowed;
}
/* Table Styles (base styles from header.php) */
.table {
table-layout: auto;
}
/* Specific Column Widths */
.table th:nth-child(1),
.table td:nth-child(1) {
width: 60px;
text-align: center;
}
.table th:nth-child(5),
.table td:nth-child(5) {
width: 160px;
}
/* Action button styles handled by unified styles in header.php */
/* Mobile table card layout handled by unified styles in header.php */
.pr-0 {
padding-right: 0 !important;
}
.pl-0 {
padding-left: 0 !important;
}
.form-control {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-primary {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
/* Styles for the View Popup */
#viewPopupOverlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
#viewPopupForm {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: var(--bs-body-bg);
padding: 20px;
border: 1px solid var(--bs-border-color);
border-radius: 10px;
z-index: 1001;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 80%;
max-width: 600px;
overflow-y: auto;
max-height: 90vh;
}
#viewPopupForm .mb-3 {
margin-bottom: 15px;
}
#viewPopupForm label {
font-weight: bold;
}
#viewPopupForm p {
background-color: var(--bs-tertiary-bg);
padding: 10px;
border-radius: 5px;
}
/* Archived reminder rows */
tr.reminder-archived {
opacity: 0.6;
}
tr.reminder-archived td[data-label="Status"] {
color: var(--bs-secondary-color);
font-style: italic;
}
</style>
</head>
<body>
<div class="container mt-4 content" style="max-width: 900px;">
<?php include('message.php'); ?>
<h1 class="text-center">Manage Reminders</h1>
<?php if (isset($_SESSION['message'])) : ?>
<div class="alert alert-info">
<?= htmlspecialchars($_SESSION['message']); ?>
<?php unset($_SESSION['message']); ?>
</div>
<?php endif; ?>
<!-- Button row: Add New + Archive Toggle -->
<div class="add-button">
<?php if (!$showArchived && $uiCanWrite): ?>
<button id="addNewReminderButton" class="btn btn-primary"><i class="fas fa-plus"></i> Add New Reminder</button>
<?php endif; ?>
<a href="manage_reminder.php<?= $showArchived ? '' : '?show_archived=1'; ?>"
class="btn <?= $showArchived ? 'btn-outline-warning' : 'btn-outline-secondary'; ?>">
<i class="fas <?= $showArchived ? 'fa-box-open' : 'fa-archive'; ?> me-1"></i>
<?= $showArchived ? 'Show Active' : 'Show Archived'; ?>
</a>
</div>
<!-- Popup form for adding and editing reminders -->
<div class="popup-overlay" id="popupOverlay"></div>
<div class="popup-form" id="popupForm">
<button type="button" class="popup-close-btn" id="closePopupBtn" aria-label="Close">×</button>
<h4 id="formTitle">Add New Reminder</h4>
<form id="reminderForm" action="manage_reminder.php" method="post">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
<input type="hidden" name="id" id="id">
<div class="mb-3">
<label for="title">Title <span class="required-asterisk">*</span></label>
<input type="text" name="title" id="title" class="form-control" maxlength="100" required>
<small id="titleCounter" class="form-text text-muted">0/100 characters used</small>
</div>
<div class="mb-3">
<label for="description">Description <span class="required-asterisk">*</span></label>
<textarea name="description" id="description" class="form-control" rows="3" maxlength="500" required></textarea>
<small id="descriptionCounter" class="form-text text-muted">0/500 characters used</small>
</div>
<div class="mb-3">
<label for="assigned_to">Assigned To <span class="required-asterisk">*</span></label>
<select name="assigned_to[]" id="assigned_to" class="form-control" multiple required>
<?php foreach ($users as $userId => $name) : ?>
<option value="<?= htmlspecialchars($userId); ?>"><?= htmlspecialchars($name); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label>Recurrence Type <span class="required-asterisk">*</span></label>
<select name="recurrence_type" id="recurrence_type" class="form-control" required>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
</select>
</div>
<div class="mb-3" id="weeklyOptions" style="display: none;">
<label for="day_of_week">Day of the Week <span class="required-asterisk">*</span></label>
<select name="day_of_week" id="day_of_week" class="form-control">
<option value="">Select Day</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
</div>
<div class="mb-3" id="monthlyOptions" style="display: none;">
<label for="day_of_month">Day of the Month (1-28) <span class="required-asterisk">*</span></label>
<input type="number" name="day_of_month" id="day_of_month" class="form-control" min="1" max="28">
</div>
<div class="mb-3">
<label for="time_of_day">Time of Day <span class="required-asterisk">*</span></label>
<input type="time" name="time_of_day" id="time_of_day" class="form-control" required>
</div>
<!-- Status is managed via archive/restore buttons -->
<input type="hidden" name="status" id="status" value="active">
<div class="mb-3">
<label for="cage_id" id="cageIdLabel">Cage ID</label>
<select name="cage_ids[]" id="cage_id" class="form-control" multiple>
<?php foreach ($cages as $cageId) : ?>
<option value="<?= htmlspecialchars($cageId); ?>"><?= htmlspecialchars($cageId); ?></option>
<?php endforeach; ?>
</select>
<small class="form-text text-muted" id="cageIdHint">Select multiple cages to create a separate reminder for each.</small>
</div>
<div class="form-buttons">
<button type="submit" name="add" id="addButton" class="btn btn-primary"><i class="fas fa-plus"></i> Add Reminder</button>
<button type="submit" name="edit" id="editButton" class="btn btn-success" style="display: none;"><i class="fas fa-save"></i> Update Reminder</button>
<button type="button" class="btn btn-secondary" id="cancelButton">Cancel</button>
</div>
</form>
</div>
<!-- Popup form for viewing reminders -->
<div class="popup-overlay" id="viewPopupOverlay"></div>
<div class="popup-form" id="viewPopupForm">
<button type="button" class="popup-close-btn" id="closeViewPopupBtn" aria-label="Close">×</button>
<h4>View Reminder Details</h4>
<div class="mb-3">
<label>Title:</label>
<p id="viewTitle"></p>
</div>
<div class="mb-3">
<label>Description:</label>
<p id="viewDescription"></p>
</div>
<div class="mb-3">
<label>Assigned To:</label>
<p id="viewAssignedTo"></p>
</div>
<div class="mb-3">
<label>Recurrence Type:</label>
<p id="viewRecurrenceType"></p>
</div>
<div class="mb-3">
<label>Time of Day:</label>
<p id="viewTimeOfDay"></p>
</div>
<div class="mb-3">
<label>Status:</label>
<p id="viewStatus"></p>
</div>
<div class="mb-3">
<label>Cage ID:</label>
<p id="viewCageId"></p>
</div>
<div class="form-buttons">
<button type="button" class="btn btn-secondary" id="closeViewButton">Close</button>
</div>
</div>
<!-- Table for displaying reminders -->
<h3><?= $showArchived ? 'Archived Reminders' : 'Active Reminders'; ?></h3>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Recurrence</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if ($reminderResult->num_rows === 0): ?>
<tr>
<td colspan="5" class="text-center py-4">
<?php if ($showArchived): ?>
<i class="fas fa-archive fa-3x text-muted d-block mb-2"></i>
<p class="text-muted mb-0">No archived reminders found.</p>
<?php else: ?>
<i class="fas fa-bell-slash fa-3x text-muted d-block mb-2"></i>
<p class="text-muted mb-0">No reminders found. Click "Add New Reminder" to create one.</p>
<?php endif; ?>
</td>
</tr>
<?php endif; ?>
<?php while ($row = $reminderResult->fetch_assoc()) : ?>
<tr class="<?= $showArchived ? 'reminder-archived' : ''; ?>">
<td data-label="ID"><?= htmlspecialchars($row['id']); ?></td>
<td data-label="Title"><?= htmlspecialchars($row['title']); ?></td>
<td data-label="Recurrence">
<?= ucfirst($row['recurrence_type']); ?>
<?php if ($row['recurrence_type'] == 'weekly') : ?>
(<?= $row['day_of_week']; ?>)
<?php elseif ($row['recurrence_type'] == 'monthly') : ?>
(Day <?= $row['day_of_month']; ?>)
<?php endif; ?>
at <?= date('h:i A', strtotime($row['time_of_day'])); ?>
</td>
<td data-label="Status"><?= htmlspecialchars(ucfirst($row['status'])); ?></td>
<td data-label="Actions" class="table-actions">
<div class="action-buttons">
<!-- View button (always visible) -->
<button class="btn btn-info btn-sm viewButton" data-id="<?= $row['id']; ?>">
<i class="fas fa-eye"></i>
</button>
<?php if ($uiCanWrite): ?>
<?php if ($showArchived): ?>
<!-- Archived view: Restore + Delete Forever -->
<form action="manage_reminder.php" method="post" style="display:inline-block;">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
<input type="hidden" name="id" value="<?= $row['id']; ?>">
<button type="submit" name="restore" class="btn btn-success btn-sm" title="Restore"
onclick="return confirm('Restore this reminder back to active?');">
<i class="fas fa-undo"></i>
</button>
</form>
<form action="manage_reminder.php" method="post" style="display:inline-block;">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
<input type="hidden" name="id" value="<?= $row['id']; ?>">
<button type="submit" name="delete" class="btn btn-danger btn-sm" title="Delete Forever"
onclick="return confirm('PERMANENTLY delete this reminder?\n\nThis action CANNOT be undone.') && confirm('Are you absolutely sure?');">
<i class="fas fa-trash"></i>
</button>
</form>
<?php else: ?>
<!-- Active view: Edit + Archive -->
<button class="btn btn-warning btn-sm editButton" data-id="<?= $row['id']; ?>">
<i class="fas fa-edit"></i>
</button>
<form action="manage_reminder.php" method="post" style="display:inline-block;">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
<input type="hidden" name="id" value="<?= $row['id']; ?>">
<button type="submit" name="archive" class="btn btn-secondary btn-sm" title="Archive"
onclick="return confirm('Archive this reminder?');">
<i class="fas fa-archive"></i>
</button>
</form>
<?php endif; ?>
<?php endif; // $uiCanWrite ?>
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
<!-- Include necessary scripts -->
<!-- jQuery loaded via header.php -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Map PHP users array to JavaScript
const users = <?= json_encode($users); ?>;
// JavaScript code to handle form interactions
$(document).ready(function() {
$('#assigned_to').select2({
placeholder: "Select users",
allowClear: true,
dropdownParent: $('#popupForm')
});
// Initialize cage_id as multi-select with Select2
$('#cage_id').select2({
placeholder: "Select Cages",
allowClear: true,
dropdownParent: $('#popupForm')
});
// Show/hide recurrence options based on selected recurrence type
$('#recurrence_type').on('change', function() {
const recurrenceType = $(this).val();
if (recurrenceType === 'weekly') {
$('#weeklyOptions').show();
$('#monthlyOptions').hide();
$('#day_of_month').val('');
} else if (recurrenceType === 'monthly') {
$('#weeklyOptions').hide();
$('#monthlyOptions').show();
$('#day_of_week').val('');
} else {
$('#weeklyOptions').hide();
$('#monthlyOptions').hide();
$('#day_of_week').val('');
$('#day_of_month').val('');
}
});
// Open the add reminder form
$('#addNewReminderButton').on('click', function() {
resetForm();
setCageMode('add');
$('#formTitle').text('Add New Reminder');
$('#addButton').show();
$('#editButton').hide();
$('#popupOverlay').show();
$('#popupForm').show();
});
// Close the form
$('#cancelButton, #closePopupBtn').on('click', function() {
$('#popupOverlay').hide();
$('#popupForm').hide();
});
// Close view popup
$('#closeViewPopupBtn').on('click', function() {
$('#viewPopupOverlay').hide();
$('#viewPopupForm').hide();
});
// Close the form when clicking outside
$('#popupOverlay').on('click', function() {
$('#popupOverlay').hide();
$('#popupForm').hide();
});
// Edit reminder
$('.editButton').on('click', function() {
const id = $(this).data('id');
fetchReminderData(id);
});
// Character counters
$('#title').on('input', function() {
const currentLength = $(this).val().length;
$('#titleCounter').text(`${currentLength}/100 characters used`);
});
$('#description').on('input', function() {
const currentLength = $(this).val().length;
$('#descriptionCounter').text(`${currentLength}/500 characters used`);
});
// View reminder
$('.viewButton').on('click', function() {
const id = $(this).data('id');
fetchViewReminderData(id);
});
// Close the view popup
$('#closeViewButton').on('click', function() {
$('#viewPopupOverlay').hide();
$('#viewPopupForm').hide();
});
// Close the view popup when clicking outside
$('#viewPopupOverlay').on('click', function() {
$('#viewPopupOverlay').hide();
$('#viewPopupForm').hide();
});
// Stop propagation when clicking inside the view popup
$('#viewPopupForm').on('click', function(e) {
e.stopPropagation();
});
});
// Toggle cage_id between multi-select (add) and single-select (edit)
function setCageMode(mode) {
var $cage = $('#cage_id');
// Destroy existing Select2
if ($cage.hasClass('select2-hidden-accessible')) {
$cage.select2('destroy');
}
$cage.val(null);
if (mode === 'add') {
$cage.attr('multiple', true).attr('name', 'cage_ids[]');
$('#cageIdLabel').text('Cage IDs');
$('#cageIdHint').show();
$cage.select2({
placeholder: "Select Cages",
allowClear: true,
dropdownParent: $('#popupForm')
});
} else {
$cage.removeAttr('multiple').attr('name', 'cage_id');
$('#cageIdLabel').text('Cage ID');
$('#cageIdHint').hide();
$cage.select2({
placeholder: "Select Cage",
allowClear: true,
dropdownParent: $('#popupForm')
});
}
}
// Reset form fields
function resetForm() {
$('#reminderForm')[0].reset();
$('#assigned_to').val(null).trigger('change');
$('#cage_id').val(null).trigger('change');
$('#weeklyOptions').hide();
$('#monthlyOptions').hide();
$('#titleCounter').text(`0/100 characters used`);
$('#descriptionCounter').text(`0/500 characters used`);
$('#assigned_by').val('<?= $currentUserName; ?>');
}
// Fetch reminder data for editing
function fetchReminderData(id) {
$.ajax({
url: 'get_reminder.php',
type: 'GET',
data: {
id: id
},
dataType: 'json',
success: function(response) {
if (response.error) {
alert(response.error);
return;
}
// Switch cage_id to single-select mode for editing
setCageMode('edit');
// Populate form fields
$('#id').val(response.id);
$('#title').val(response.title);
$('#description').val(response.description);
$('#assigned_to').val(response.assigned_to.split(',')).trigger('change');
$('#recurrence_type').val(response.recurrence_type).trigger('change');
$('#day_of_week').val(response.day_of_week);
$('#day_of_month').val(response.day_of_month);
$('#time_of_day').val(response.time_of_day);
$('#status').val(response.status);
$('#cage_id').val(response.cage_id).trigger('change');
// Update character counters
$('#titleCounter').text(`${response.title.length}/100 characters used`);
$('#descriptionCounter').text(`${response.description.length}/500 characters used`);
// Show the form
$('#formTitle').text('Edit Reminder');
$('#addButton').hide();
$('#editButton').show();
$('#popupOverlay').show();
$('#popupForm').show();
},
error: function(xhr, status, error) {
alert('Error fetching reminder data: ' + error);
}
});
}
// Function to fetch and display reminder data in the view popup
function fetchViewReminderData(id) {
$.ajax({
url: 'get_reminder.php',
type: 'GET',
data: {
id: id
},
dataType: 'json',
success: function(response) {
if (response.error) {
alert(response.error);
return;
}
// Populate the view popup with reminder details
$('#viewTitle').text(response.title);
$('#viewDescription').text(response.description);
// Get assigned to names
let assignedToNames = [];
if (response.assigned_to) {
const assignedToIds = response.assigned_to.split(',');
assignedToIds.forEach(function(id) {
const name = users[id];
if (name) {
assignedToNames.push(name);
} else {
assignedToNames.push('Unknown');
}
});
}
$('#viewAssignedTo').text(assignedToNames.join(', '));
// Display recurrence type and details
let recurrenceDetails = response.recurrence_type;
if (response.recurrence_type === 'weekly') {
recurrenceDetails += ' (' + response.day_of_week + ')';
} else if (response.recurrence_type === 'monthly') {
recurrenceDetails += ' (Day ' + response.day_of_month + ')';
}
$('#viewRecurrenceType').text(recurrenceDetails);
$('#viewTimeOfDay').text(response.time_of_day);
$('#viewStatus').text(response.status);
$('#viewCageId').text(response.cage_id);
// Show the view popup
$('#viewPopupOverlay').show();
$('#viewPopupForm').show();
},
error: function(xhr, status, error) {
alert('Error fetching reminder data: ' + error);
}
});
}
</script>
<?php require 'footer.php'; ?>
</body>
</html>