-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.php
More file actions
1862 lines (1703 loc) · 104 KB
/
Copy pathdashboard.php
File metadata and controls
1862 lines (1703 loc) · 104 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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// Load config first (before any output)
require_once 'config.php';
require_once 'config/email_config.php';
// Redirect if not logged in (must be before header.php sends any output)
if (!isLoggedIn()) {
header('Location: login.php?redirect=' . urlencode('dashboard.php'));
exit;
}
// Check if user can access dashboard
if (!canAccessDashboard()) {
header('Location: index.php');
exit;
}
$page_title = 'Dashboard - Buzón de Quejas';
$show_global_blobs = false; // Disable global header blobs for this page
include 'components/header.php';
require_once 'status_helper.php';
?>
<?php
// Allow all logged-in users to view the reports
// Only admins can modify them (handled in view_complaint.php)
// Get filter parameters (support arrays for multi-select)
$departments = isset($_GET['department']) ? (is_array($_GET['department']) ? $_GET['department'] : [$_GET['department']]) : [];
$departments = array_filter($departments, fn($v) => $v !== '');
$statuses = isset($_GET['status']) ? (is_array($_GET['status']) ? $_GET['status'] : [$_GET['status']]) : [];
$statuses = array_filter($statuses, fn($v) => $v !== '');
$categories = isset($_GET['category']) ? (is_array($_GET['category']) ? $_GET['category'] : [$_GET['category']]) : [];
$categories = array_filter($categories, fn($v) => $v !== '');
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$date_range = isset($_GET['date_range']) ? $_GET['date_range'] : 'this_year';
// Build query
$query = "SELECT DISTINCT c.*, u.name as user_name, u.email as user_email, cat.name as category_name,
GROUP_CONCAT(d.name ORDER BY d.name SEPARATOR '||') as department_names,
GROUP_CONCAT(d.id ORDER BY d.name SEPARATOR ',') as department_ids,
(SELECT COUNT(*) FROM attachments ca WHERE ca.complaint_id = c.id) as attachment_count,
(SELECT COUNT(*) FROM complaint_comments cm WHERE cm.complaint_id = c.id) as comment_count,
c.folio
FROM complaints c
LEFT JOIN users u ON c.user_id = u.id
LEFT JOIN categories cat ON c.category_id = cat.id
LEFT JOIN complaint_departments cd ON c.id = cd.complaint_id
LEFT JOIN departments d ON cd.department_id = d.id
WHERE 1=1";
// Check if dashboard restriction is enabled (used for manager filtering)
$stmt_restrict_early = $conn->prepare("SELECT setting_value FROM admin_settings WHERE setting_key = 'restrict_dashboard_access'");
$stmt_restrict_early->execute();
$result_restrict_early = $stmt_restrict_early->get_result();
$is_dashboard_restricted_for_managers = false;
if ($row_restrict_early = $result_restrict_early->fetch_assoc()) {
$is_dashboard_restricted_for_managers = $row_restrict_early['setting_value'] == '1';
}
// If user is a manager (not admin) AND dashboard restriction is enabled, only show complaints assigned to their departments
// If restriction is disabled, managers can see all reports
if (!isAdmin() && isset($_SESSION['role']) && $_SESSION['role'] === 'manager' && $is_dashboard_restricted_for_managers) {
// Get manager's email to find their departments
$manager_email = $_SESSION['email'];
// Get department IDs where this manager is assigned
$stmt_dept = $conn->prepare("SELECT id FROM departments WHERE email = ?");
$stmt_dept->bind_param("s", $manager_email);
$stmt_dept->execute();
$result_dept = $stmt_dept->get_result();
$manager_dept_ids = [];
while ($row_dept = $result_dept->fetch_assoc()) {
$manager_dept_ids[] = $row_dept['id'];
}
// If manager has departments, filter by them
if (!empty($manager_dept_ids)) {
$dept_ids_str = implode(',', array_map('intval', $manager_dept_ids));
$query .= " AND EXISTS (
SELECT 1 FROM complaint_departments cd_mgr
WHERE cd_mgr.complaint_id = c.id
AND cd_mgr.department_id IN ($dept_ids_str))";
} else {
// Manager has no departments assigned, show nothing
$query .= " AND 1=0";
}
}
// Multi-select filters
if (!empty($categories)) {
$cat_ids = implode(',', array_map('intval', $categories));
$query .= " AND c.category_id IN ($cat_ids)";
}
if (!empty($departments)) {
$dept_ids = implode(',', array_map('intval', $departments));
$query .= " AND EXISTS (
SELECT 1 FROM complaint_departments cd2
WHERE cd2.complaint_id = c.id
AND cd2.department_id IN ($dept_ids))";
}
if (!empty($statuses)) {
$escaped_statuses = array_map(fn($s) => "'" . $conn->real_escape_string($s) . "'", $statuses);
$query .= " AND c.status IN (" . implode(',', $escaped_statuses) . ")";
}
if ($search !== '') {
$escaped = $conn->real_escape_string($search);
$like = "'%" . $escaped . "%'";
$query .= " AND (c.folio LIKE $like OR c.description LIKE $like)";
}
if ($date_range && $date_range !== 'all') {
if ($date_range === 'this_year') {
$startOfYear = (new DateTime('first day of january ' . date('Y')))->format('Y-m-d 00:00:00');
$query .= " AND c.created_at >= '" . $conn->real_escape_string($startOfYear) . "'";
} else {
$query .= " AND c.created_at >= DATE_SUB(NOW(), INTERVAL " . intval($date_range) . " DAY)";
}
}
// Get quick statistics (Admins and Managers)
$stats = ['total' => 0, 'unattended' => 0, 'attended' => 0, 'unassigned' => 0,
'unattended_ontime' => 0, 'unattended_late' => 0, 'attended_ontime' => 0, 'attended_late' => 0];
if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))) {
// If user is a manager AND dashboard is restricted, filter stats by their departments
$is_manager = !isAdmin() && isset($_SESSION['role']) && $_SESSION['role'] === 'manager';
$stats_dept_filter = "";
if ($is_manager && $is_dashboard_restricted_for_managers) {
// Get manager's department IDs
$manager_email = $_SESSION['email'];
$stmt_mgr_dept = $conn->prepare("SELECT id FROM departments WHERE email = ?");
$stmt_mgr_dept->bind_param("s", $manager_email);
$stmt_mgr_dept->execute();
$result_mgr_dept = $stmt_mgr_dept->get_result();
$mgr_dept_ids = [];
while ($row_mgr_dept = $result_mgr_dept->fetch_assoc()) {
$mgr_dept_ids[] = $row_mgr_dept['id'];
}
if (!empty($mgr_dept_ids)) {
$mgr_dept_ids_str = implode(',', array_map('intval', $mgr_dept_ids));
$stats_dept_filter = " WHERE EXISTS (
SELECT 1 FROM complaint_departments cd_stats
WHERE cd_stats.complaint_id = c.id
AND cd_stats.department_id IN ($mgr_dept_ids_str))";
} else {
// Manager has no departments, show zero stats
$stats_dept_filter = " WHERE 1=0";
}
}
$stats_query = "SELECT
COUNT(*) as total,
SUM(CASE WHEN status IN ('unattended_ontime', 'unattended_late') THEN 1 ELSE 0 END) as unattended,
SUM(CASE WHEN status IN ('attended_ontime', 'attended_late') THEN 1 ELSE 0 END) as attended,
SUM(CASE WHEN NOT EXISTS (SELECT 1 FROM complaint_departments cd WHERE cd.complaint_id = c.id) THEN 1 ELSE 0 END) as unassigned,
SUM(CASE WHEN status = 'unattended_ontime' THEN 1 ELSE 0 END) as unattended_ontime,
SUM(CASE WHEN status = 'unattended_late' THEN 1 ELSE 0 END) as unattended_late,
SUM(CASE WHEN status = 'attended_ontime' THEN 1 ELSE 0 END) as attended_ontime,
SUM(CASE WHEN status = 'attended_late' THEN 1 ELSE 0 END) as attended_late
FROM complaints c" . $stats_dept_filter;
$stats_result = $conn->query($stats_query);
if ($stats_result) {
$stats = $stats_result->fetch_assoc();
}
}
// Pagination setup
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;
// Build count query with the same filters
$countQuery = "SELECT COUNT(DISTINCT c.id) as total
FROM complaints c
LEFT JOIN users u ON c.user_id = u.id
LEFT JOIN categories cat ON c.category_id = cat.id
LEFT JOIN complaint_departments cd ON c.id = cd.complaint_id
LEFT JOIN departments d ON cd.department_id = d.id
WHERE 1=1";
// Apply same manager filter to count query (only if restriction is enabled)
if (!isAdmin() && isset($_SESSION['role']) && $_SESSION['role'] === 'manager' && $is_dashboard_restricted_for_managers) {
$manager_email = $_SESSION['email'];
$stmt_dept2 = $conn->prepare("SELECT id FROM departments WHERE email = ?");
$stmt_dept2->bind_param("s", $manager_email);
$stmt_dept2->execute();
$result_dept2 = $stmt_dept2->get_result();
$manager_dept_ids2 = [];
while ($row_dept2 = $result_dept2->fetch_assoc()) {
$manager_dept_ids2[] = $row_dept2['id'];
}
if (!empty($manager_dept_ids2)) {
$dept_ids_str2 = implode(',', array_map('intval', $manager_dept_ids2));
$countQuery .= " AND EXISTS (
SELECT 1 FROM complaint_departments cd_mgr2
WHERE cd_mgr2.complaint_id = c.id
AND cd_mgr2.department_id IN ($dept_ids_str2))";
} else {
$countQuery .= " AND 1=0";
}
}
// Multi-select filters for count
if (!empty($categories)) {
$cat_ids = implode(',', array_map('intval', $categories));
$countQuery .= " AND c.category_id IN ($cat_ids)";
}
if (!empty($departments)) {
$dept_ids = implode(',', array_map('intval', $departments));
$countQuery .= " AND EXISTS (
SELECT 1 FROM complaint_departments cd2
WHERE cd2.complaint_id = c.id
AND cd2.department_id IN ($dept_ids))";
}
if (!empty($statuses)) {
$escaped_statuses = array_map(fn($s) => "'" . $conn->real_escape_string($s) . "'", $statuses);
$countQuery .= " AND c.status IN (" . implode(',', $escaped_statuses) . ")";
}
if ($search !== '') {
$escaped = $conn->real_escape_string($search);
$like = "'%" . $escaped . "%'";
$countQuery .= " AND (c.folio LIKE $like OR c.description LIKE $like)";
}
if ($date_range && $date_range !== 'all') {
if ($date_range === 'this_year') {
$startOfYear = (new DateTime('first day of january ' . date('Y')))->format('Y-m-d 00:00:00');
$countQuery .= " AND c.created_at >= '" . $conn->real_escape_string($startOfYear) . "'";
} else {
$countQuery .= " AND c.created_at >= DATE_SUB(NOW(), INTERVAL " . intval($date_range) . " DAY)";
}
}
$countRes = $conn->query($countQuery);
$total_rows = 0;
if ($countRes) {
$rowCount = $countRes->fetch_assoc();
$total_rows = isset($rowCount['total']) ? intval($rowCount['total']) : 0;
}
$total_pages = max(1, (int)ceil($total_rows / $per_page));
$query .= " GROUP BY c.id, c.description, c.status, c.created_at, c.attended_at, c.is_anonymous, c.user_id, u.name, u.email
ORDER BY c.created_at DESC
LIMIT " . intval($per_page) . " OFFSET " . intval($offset);
$result = $conn->query($query);
// Get categories and departments for filter
$cat_result = $conn->query("SELECT * FROM categories ORDER BY name");
$dept_result = $conn->query("SELECT * FROM departments ORDER BY name");
// Verificar si hay correos fallidos en la cola (solo admins)
$failed_emails_count = 0;
$failed_emails_error = '';
if (isAdmin()) {
$failed_q = $conn->query("SELECT COUNT(*) as cnt, MAX(error_message) as last_error FROM email_queue WHERE status = 'failed'");
if ($failed_q) {
$failed_row = $failed_q->fetch_assoc();
$failed_emails_count = intval($failed_row['cnt']);
$failed_emails_error = $failed_row['last_error'] ?? '';
}
}
?>
<!-- Institutional Background -->
<div class="fixed inset-0 overflow-hidden pointer-events-none -z-50">
<div class="absolute inset-0 bg-institutional">
<div class="absolute inset-0 bg-gradient-to-b from-slate-50/40 via-transparent to-slate-50/40 dark:from-slate-900/60 dark:via-transparent dark:to-slate-900/60"></div>
</div>
</div>
<!-- Liquid Glass Global Styles -->
<style>
/* Dashbord Filter Input Overrides */
.glass-input-dashboard {
background: rgba(255, 255, 255, 0.2) !important;
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.2) !important;
transition: all 0.3s ease;
}
.dark .glass-input-dashboard {
background: rgba(0, 0, 0, 0.3) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
}
.glass-input-dashboard:focus {
background: rgba(255, 255, 255, 0.3) !important;
border-color: rgba(59, 130, 246, 0.5) !important;
box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1) !important;
}
/* TomSelect Transparency and Overflow Fix */
.ts-wrapper {
position: relative;
z-index: 50;
}
.ts-control {
background: rgba(255, 255, 255, 0.2) !important;
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.2) !important;
border-radius: 0.75rem !important;
color: #111827 !important;
}
.dark .ts-control {
background: rgba(0, 0, 0, 0.3) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
color: #e2e8f0 !important;
}
.dark .ts-control input {
color: #e2e8f0 !important;
}
.dark .ts-control input::placeholder {
color: #94a3b8 !important;
}
.ts-control .item {
color: #fff !important;
border-radius: 0.375rem !important;
}
.dark .ts-control .item {
background: rgba(59, 130, 246, 0.2) !important;
color: #93c5fd !important;
border: 1px solid rgba(59, 130, 246, 0.3) !important;
border-radius: 0.375rem !important;
}
.ts-dropdown {
background: rgba(255, 255, 255, 0.95) !important;
backdrop-filter: blur(15px);
border: 1px solid rgba(0, 0, 0, 0.1) !important;
border-radius: 0.75rem !important;
z-index: 1000 !important;
position: absolute !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1) !important;
}
.dark .ts-dropdown {
background: #1e293b !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.4) !important;
}
.ts-dropdown .option {
color: #1f2937 !important;
border-radius: 0.375rem !important;
margin: 2px 4px !important;
}
.dark .ts-dropdown .option {
color: #e2e8f0 !important;
}
.ts-dropdown .option:hover,
.ts-dropdown .option.active {
background: rgba(59, 130, 246, 0.1) !important;
color: #2563eb !important;
}
.dark .ts-dropdown .option:hover,
.dark .ts-dropdown .option.active {
background: rgba(59, 130, 246, 0.2) !important;
color: #93c5fd !important;
}
.ts-dropdown .option.selected {
background: rgba(59, 130, 246, 0.15) !important;
color: #2563eb !important;
}
.dark .ts-dropdown .option.selected {
background: rgba(59, 130, 246, 0.25) !important;
color: #93c5fd !important;
}
/* Force dark text on filter labels and table headers for readability */
label.text-gray-500,
th.text-gray-500,
.text-gray-600 {
color: #111827 !important;
}
html.dark label.text-gray-500,
html.dark th.text-gray-500,
html.dark .text-gray-600 {
color: #e2e8f0 !important;
}
</style>
<main class="container mx-auto px-4 py-6 relative flex-grow">
<?php if (isAdmin() && $failed_emails_count > 0): ?>
<div class="mb-4 bg-amber-50 border border-amber-300 text-amber-800 px-5 py-3 rounded-lg flex items-center gap-3 shadow-sm">
<i class="ph-warning text-xl text-amber-500 flex-shrink-0"></i>
<div class="flex-1">
<span class="font-semibold"><?php echo $failed_emails_count; ?> correo(s) no se pudieron enviar.</span>
<?php if ($failed_emails_error): ?>
<span class="text-amber-700 text-sm ml-1"><?php echo htmlspecialchars($failed_emails_error); ?></span>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
<!-- Dashboard Header Card (Title + Buttons + Stats) -->
<div class="liquid-glass rounded-2xl p-5 mb-6">
<div class="flex flex-wrap items-center gap-3 mb-4">
<div class="flex items-center gap-3">
<div class="inline-flex items-center justify-center w-12 h-12 bg-blue-600 dark:bg-blue-500/20 rounded-xl flex-shrink-0 shadow-sm dark:shadow-none border border-transparent dark:border-blue-500/30">
<i class="ph-chart-bar text-white dark:text-blue-400 text-2xl"></i>
</div>
<h1 class="text-2xl font-bold text-gray-800 dark:text-white">Dashboard</h1>
</div>
<div class="flex items-center gap-2 ml-auto">
<?php if (isAdmin() && intval($stats['unassigned']) > 0): ?>
<button type="button"
onclick="openBulkAnalyzeModal()"
class="px-3 py-1.5 sm:px-4 sm:py-2 text-sm font-bold text-white bg-blue-600 hover:bg-blue-700 dark:bg-blue-500/10 dark:text-blue-400 dark:border dark:border-blue-400/30 dark:hover:bg-blue-500/20 rounded-lg shadow-sm transition-all flex items-center gap-2"
title="Analizar todos los reportes sin asignar con IA">
<i class="ph-sparkle text-lg"></i>
<span class="hidden sm:inline">Analizar con IA</span>
</button>
<?php endif; ?>
<?php if (isAdmin() && (intval($stats['unattended_ontime']) + intval($stats['unattended_late'])) > 0): ?>
<button type="button"
onclick="sendDepartmentReminders(this)"
class="px-3 py-1.5 sm:px-4 sm:py-2 text-sm font-bold text-white bg-amber-500 hover:bg-amber-600 dark:bg-amber-500/10 dark:text-amber-500 dark:border dark:border-amber-500/30 dark:hover:bg-amber-500/20 rounded-lg shadow-sm transition-all flex items-center gap-2 group"
title="Enviar recordatorio a departamentos con reportes pendientes">
<i class="ph-paper-plane-right text-lg group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform"></i>
<span class="hidden sm:inline">Enviar Recordatorios</span>
</button>
<?php endif; ?>
</div>
</div>
<!-- Quick Stats (Admins and Managers) -->
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<div class="grid grid-cols-2 md:grid-cols-3 lg:flex lg:flex-row gap-3 w-full">
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-gray-400">
<div class="w-12 h-12 rounded-xl bg-gray-500/10 dark:bg-gray-400/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-list-checks text-gray-600 dark:text-gray-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-gray-900 dark:text-white leading-none"><?php echo $stats['total']; ?></div>
<div class="text-[11px] uppercase tracking-widest text-gray-500 dark:text-gray-400 font-bold mt-1.5 whitespace-nowrap">Total</div>
</div>
</div>
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-green-500">
<div class="w-12 h-12 rounded-xl bg-green-500/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-check-circle text-green-600 dark:text-green-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-green-600 dark:text-green-400 leading-none"><?php echo intval($stats['attended_ontime']); ?></div>
<div class="mt-1.5" title="Atendido a tiempo">
<div class="text-[11px] uppercase tracking-widest text-green-600 dark:text-green-400/80 font-bold whitespace-nowrap leading-tight">Atendido</div>
<div class="text-[9px] uppercase tracking-widest text-green-500/70 font-semibold whitespace-nowrap leading-tight mt-0.5">a tiempo</div>
</div>
</div>
</div>
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-orange-500">
<div class="w-12 h-12 rounded-xl bg-orange-500/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-clock-afternoon text-orange-600 dark:text-orange-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-orange-600 dark:text-orange-400 leading-none"><?php echo intval($stats['attended_late']); ?></div>
<div class="mt-1.5" title="Atendido tarde">
<div class="text-[11px] uppercase tracking-widest text-orange-600 dark:text-orange-400/80 font-bold whitespace-nowrap leading-tight">Atendido</div>
<div class="text-[9px] uppercase tracking-widest text-orange-500/70 font-semibold whitespace-nowrap leading-tight mt-0.5">tarde</div>
</div>
</div>
</div>
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-blue-500">
<div class="w-12 h-12 rounded-xl bg-blue-500/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-hourglass-medium text-blue-600 dark:text-blue-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-blue-600 dark:text-blue-400 leading-none"><?php echo intval($stats['unattended_ontime']); ?></div>
<div class="mt-1.5" title="Sin atender a tiempo">
<div class="text-[11px] uppercase tracking-widest text-blue-600 dark:text-blue-400/80 font-bold whitespace-nowrap leading-tight">Sin atender</div>
<div class="text-[9px] uppercase tracking-widest text-blue-500/70 font-semibold whitespace-nowrap leading-tight mt-0.5">a tiempo</div>
</div>
</div>
</div>
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-red-500">
<div class="w-12 h-12 rounded-xl bg-red-500/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-warning text-red-600 dark:text-red-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-red-600 dark:text-red-400 leading-none"><?php echo intval($stats['unattended_late']); ?></div>
<div class="mt-1.5" title="Sin atender retrasado">
<div class="text-[11px] uppercase tracking-widest text-red-600 dark:text-red-400/80 font-bold whitespace-nowrap leading-tight">Sin atender</div>
<div class="text-[9px] uppercase tracking-widest text-red-500/70 font-semibold whitespace-nowrap leading-tight mt-0.5">retrasado</div>
</div>
</div>
</div>
<?php
$show_unassigned_stat = isAdmin() || !$is_dashboard_restricted_for_managers;
if ($show_unassigned_stat):
?>
<div class="liquid-glass rounded-xl p-3 flex items-center gap-3 flex-1 min-w-[120px] border-l-4 border-l-yellow-500">
<div class="w-12 h-12 rounded-xl bg-yellow-500/10 flex items-center justify-center flex-shrink-0">
<i class="ph-fill ph-folder text-yellow-600 dark:text-yellow-400 text-xl"></i>
</div>
<div class="min-w-0">
<div class="text-xl font-bold text-yellow-600 dark:text-yellow-400 leading-none"><?php echo $stats['unassigned']; ?></div>
<div class="text-[11px] uppercase tracking-widest text-yellow-600 dark:text-yellow-400/80 font-bold mt-1.5 whitespace-nowrap">Sin Asignar</div>
</div>
</div>
<?php endif; ?>
<div class="col-span-full md:col-span-1 lg:flex-1 flex">
<a href="statistics.php" class="w-full h-full flex items-center justify-center gap-2 p-3 text-xs font-bold text-indigo-700 dark:text-indigo-400 liquid-glass hover:bg-white/30 dark:hover:bg-white/10 rounded-xl border border-indigo-200/50 dark:border-indigo-500/30 transition-all">
<i class="ph-chart-line text-xl"></i>
<span>Ver más<span class="hidden md:inline xl:hidden"> estadísticas</span></span>
</a>
</div>
</div>
<?php endif; ?>
</div>
<!-- Compact Filters -->
<form method="GET" class="liquid-glass rounded-2xl p-4 mb-8 relative z-20" style="overflow: visible !important;" x-data="{ showFilters: false }">
<div class="flex flex-col xl:flex-row xl:items-end gap-3">
<!-- Search Bar & Toggle (Always Visible) -->
<div class="flex items-center gap-2 xl:flex-1" x-data="{ query: '<?php echo htmlspecialchars($search, ENT_QUOTES); ?>' }">
<div class="flex-grow relative">
<label for="q" class="hidden xl:block text-xs font-medium text-gray-500 mb-1">Búsqueda</label>
<div class="absolute inset-y-0 left-0 pl-2.5 flex items-center pointer-events-none xl:top-5">
<i class="ph-magnifying-glass text-gray-400"></i>
</div>
<input type="text" id="q" name="q" x-model="query"
placeholder="Folio o descripción..."
class="block w-full pl-8 pr-8 py-2 text-sm rounded-xl glass-input-dashboard text-gray-900 dark:text-white placeholder-gray-400" />
<!-- Clear Search X Button -->
<button type="button"
x-show="query.length > 0"
@click="query = ''; $nextTick(() => $el.closest('div').querySelector('input').focus())"
class="absolute inset-y-0 right-0 pr-2.5 flex items-center text-gray-400 hover:text-gray-600 cursor-pointer"
style="display: none;">
<i class="ph-x-circle text-lg bg-white"></i>
</button>
</div>
<!-- Mobile Search Button (Visible only when filters are collapsed) -->
<button type="submit"
x-show="!showFilters"
class="xl:hidden inline-flex items-center justify-center p-2 rounded-md border border-transparent bg-blue-600 text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-sm">
<i class="ph-magnifying-glass text-lg"></i>
</button>
<!-- Mobile Filter Toggle -->
<button type="button"
@click="showFilters = !showFilters"
class="xl:hidden inline-flex items-center justify-center p-2 rounded-xl glass-input-dashboard text-gray-700 dark:text-gray-300 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
<i class="ph-funnel text-lg" :class="showFilters ? 'text-blue-600' : 'text-gray-500'"></i>
</button>
</div>
<!-- Collapsible Filters (Hidden on Mobile by default, Visible on Desktop) -->
<div class="flex-wrap items-end gap-3 xl:flex"
:class="showFilters ? 'flex' : 'hidden'">
<div class="w-full sm:w-48">
<label for="category" class="block text-xs font-medium text-gray-500 mb-1">Categorías</label>
<select id="category" name="category[]" multiple class="tom-select-multi block w-full text-sm" placeholder="Todas">
<?php
$cat_result->data_seek(0);
while ($cat = $cat_result->fetch_assoc()):
?>
<option value="<?php echo $cat['id']; ?>" <?php echo in_array($cat['id'], $categories) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($cat['name']); ?>
</option>
<?php endwhile; ?>
</select>
</div>
<?php if (function_exists('isAdmin') ? isAdmin() : false): ?>
<div class="w-full sm:w-48">
<label for="department" class="block text-xs font-medium text-gray-500 mb-1">Departamentos</label>
<select id="department" name="department[]" multiple class="tom-select-multi block w-full text-sm" placeholder="Todos">
<?php
$dept_result->data_seek(0);
while ($dept = $dept_result->fetch_assoc()):
?>
<option value="<?php echo $dept['id']; ?>" <?php echo in_array($dept['id'], $departments) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($dept['name']); ?>
</option>
<?php endwhile; ?>
</select>
</div>
<?php endif; ?>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<div class="w-full sm:w-48">
<label for="status" class="block text-xs font-medium text-gray-500 mb-1">Estados</label>
<select id="status" name="status[]" multiple class="tom-select-multi block w-full text-sm" placeholder="Todos">
<option value="unattended_ontime" <?php echo in_array('unattended_ontime', $statuses) ? 'selected' : ''; ?>>Sin atender (a tiempo)</option>
<option value="unattended_late" <?php echo in_array('unattended_late', $statuses) ? 'selected' : ''; ?>>Sin atender (tarde)</option>
<option value="attended_ontime" <?php echo in_array('attended_ontime', $statuses) ? 'selected' : ''; ?>>Atendido</option>
<option value="attended_late" <?php echo in_array('attended_late', $statuses) ? 'selected' : ''; ?>>Atendido a destiempo</option>
<option value="invalid" <?php echo in_array('invalid', $statuses) ? 'selected' : ''; ?>>Inválido</option>
<option value="duplicate" <?php echo in_array('duplicate', $statuses) ? 'selected' : ''; ?>>Duplicado</option>
</select>
</div>
<?php endif; ?>
<div class="w-full sm:w-40">
<label for="date_range" class="block text-xs font-medium text-gray-500 mb-1">Fecha</label>
<select id="date_range" name="date_range" class="tom-select-single block w-full text-sm">
<option value="this_year" <?php echo $date_range == 'this_year' || $date_range == '' ? 'selected' : ''; ?>>Este año</option>
<option value="7" <?php echo $date_range == '7' ? 'selected' : ''; ?>>Últimos 7 días</option>
<option value="30" <?php echo $date_range == '30' ? 'selected' : ''; ?>>Últimos 30 días</option>
<option value="90" <?php echo $date_range == '90' ? 'selected' : ''; ?>>Últimos 90 días</option>
<option value="all" <?php echo $date_range == 'all' ? 'selected' : ''; ?>>Todo el tiempo</option>
</select>
</div>
<div class="flex items-center gap-2 w-full xl:w-auto">
<?php
$hasActiveFilters = !empty($departments) || !empty($categories) ||
!empty($statuses) || !empty($_GET['q']) ||
(isset($_GET['date_range']) && $_GET['date_range'] !== 'this_year' && $_GET['date_range'] !== '');
if ($hasActiveFilters):
?>
<a href="dashboard.php" class="flex-1 xl:flex-none inline-flex justify-center items-center px-3 py-2 text-sm font-medium text-gray-600 dark:text-gray-300 bg-gray-100/50 dark:bg-white/10 rounded-md hover:bg-gray-200 transition-colors">
<i class="ph-trash mr-1"></i>
Limpiar
</a>
<?php endif; ?>
<!-- Mobile Apply Button -->
<button type="submit" class="xl:hidden flex-1 inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 dark:bg-blue-500/15 dark:text-blue-400 dark:border dark:border-blue-400/30 dark:hover:bg-blue-500/25 rounded-lg shadow-sm transition-all">
<i class="ph-magnifying-glass mr-1.5"></i>
Aplicar Filtros
</button>
<!-- Desktop Filter Button -->
<button type="submit" class="hidden xl:inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 dark:bg-blue-500/15 dark:text-blue-400 dark:border dark:border-blue-400/30 dark:hover:bg-blue-500/25 rounded-lg shadow-sm transition-all">
<i class="ph-magnifying-glass mr-1.5"></i>
Buscar
</button>
</div>
</div>
</div>
</form>
<?php if (!empty($search)): ?>
<div class="mb-4 text-gray-600 text-sm">
Resultados de la búsqueda <span class="font-semibold">"<?php echo htmlspecialchars($search); ?>"</span>
<span class="text-gray-500">(<?php echo $total_rows; ?> <?php echo $total_rows == 1 ? 'coincidencia' : 'coincidencias'; ?>)</span>
</div>
<?php endif; ?>
<!-- Complaints List -->
<!-- Complaints List -->
<?php
// Fetch all rows to be used in both mobile and desktop views
$complaints = [];
while ($row = $result->fetch_assoc()) {
$complaints[] = $row;
}
?>
<!-- Mobile View (Cards) -->
<div class="xl:hidden space-y-4">
<?php foreach ($complaints as $row): ?>
<?php
$createdDate = new DateTime($row['created_at']);
$now = new DateTime();
$attendedDate = !empty($row['attended_at']) ? new DateTime($row['attended_at']) : null;
// Description logic
$rawDescription = isset($row['description']) ? $row['description'] : '';
$cleanDescription = trim(strip_tags($rawDescription));
$maxLen = 100;
if (function_exists('mb_strlen')) {
$descLen = mb_strlen($cleanDescription, 'UTF-8');
$shortDescription = $descLen > $maxLen ? mb_substr($cleanDescription, 0, $maxLen, 'UTF-8') . '…' : $cleanDescription;
} else {
$descLen = strlen($cleanDescription);
$shortDescription = $descLen > $maxLen ? substr($cleanDescription, 0, $maxLen) . '…' : $cleanDescription;
}
// Status logic
$statusInfo = getStatusDisplayInfo($row['status']);
// Time ago logic
$interval = $createdDate->diff($now);
$daysAgo = $interval->days;
$timeAgoText = $daysAgo === 0 ? 'Hoy' : ($daysAgo === 1 ? 'Ayer' : "Hace $daysAgo días");
?>
<div class="liquid-glass rounded-xl p-4 transition-all">
<div class="flex items-center justify-between mb-1.5">
<div class="flex items-center gap-2">
<span class="text-xs font-bold text-gray-500">#<?php echo $row['folio'] ?? str_pad($row['id'], 6, '0', STR_PAD_LEFT); ?></span>
<div class="flex items-center gap-1">
<?php if (!empty($row['is_anonymous']) && intval($row['is_anonymous']) == 1): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center justify-center w-5 h-5 rounded-full bg-purple-100 text-purple-700 ring-1 ring-inset ring-purple-600/20">
<i class="ph-ghost text-[10px]"></i>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100">
Reporte Anónimo
</div>
</div>
<?php endif; ?>
<?php if (isset($row['attachment_count']) && $row['attachment_count'] > 0): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-medium bg-blue-500/10 text-blue-700 dark:text-blue-400 ring-1 ring-inset ring-blue-600/20">
<i class="ph-paperclip text-[10px]"></i>
<?php echo $row['attachment_count']; ?>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100 leading-tight">
<?php echo $row['attachment_count']; ?> archivo(s) adjunto(s)
</div>
</div>
<?php endif; ?>
<?php if (isset($row['comment_count']) && $row['comment_count'] > 0): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-medium bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 ring-1 ring-inset ring-emerald-600/20">
<i class="ph-chat-circle text-[10px]"></i>
<?php echo $row['comment_count']; ?>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100 leading-tight">
<?php echo $row['comment_count']; ?> comentario(s)
</div>
</div>
<?php endif; ?>
</div>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<span class="px-1.5 py-0.5 text-[10px] font-medium rounded-full <?php echo $statusInfo['class']; ?> ring-1 ring-inset whitespace-nowrap">
<?php echo $statusInfo['text']; ?>
</span>
<?php endif; ?>
</div>
<a href="view_complaint.php?id=<?php echo $row['id']; ?>" class="text-xs font-medium text-blue-600 flex items-center gap-1 hover:text-blue-800">
Detalles <i class="ph-caret-right font-bold"></i>
</a>
</div>
<h3 class="text-sm font-medium text-gray-900 mb-2 line-clamp-2 leading-snug"><?php echo htmlspecialchars($shortDescription); ?></h3>
<div class="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-900 dark:text-gray-200">
<div class="flex items-center gap-1.5">
<i class="ph-tag text-gray-400"></i>
<span class="truncate max-w-[140px]"><?php echo $row['category_name'] ? htmlspecialchars($row['category_name']) : 'Sin categoría'; ?></span>
</div>
<div class="text-gray-300 hidden sm:block">•</div>
<div class="flex items-center gap-1.5">
<i class="ph-clock text-gray-400"></i>
<span><?php echo $timeAgoText; ?></span>
</div>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<div class="w-full flex items-start gap-1.5 pt-1 border-t border-gray-200/50 dark:border-gray-600/30 mt-0.5">
<i class="ph-buildings-light text-gray-400 mt-0.5"></i>
<div class="flex-1 truncate">
<?php if (empty($row['department_names'])): ?>
<span class="italic text-yellow-700 dark:text-yellow-400">Sin asignación</span>
<?php else:
$department_names = explode('||', $row['department_names']);
echo htmlspecialchars(implode(', ', $department_names));
endif; ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<?php if (empty($complaints)): ?>
<div class="text-center py-8 text-gray-500">
No se encontraron reportes.
</div>
<?php endif; ?>
</div>
<!-- Desktop View (Table) -->
<div class="hidden xl:block liquid-glass rounded-2xl border-none" style="overflow: visible;">
<table class="min-w-full divide-y divide-white/10">
<thead class="bg-white/10">
<tr>
<th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-24">
Folio
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[40%]">
Descripción
</th>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[35%]">
Departamentos
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-40">
Estado
</th>
<?php else: ?>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[35%]">
Usuario
</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-40">
Fecha
</th>
<?php endif; ?>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-28">
Acciones
</th>
</tr>
</thead>
<tbody class="divide-y divide-white/10">
<?php foreach ($complaints as $row): ?>
<tr class="hover:bg-white/5 transition-colors">
<?php
$createdDate = new DateTime($row['created_at']);
$now = new DateTime();
$attendedDate = !empty($row['attended_at']) ? new DateTime($row['attended_at']) : null;
?>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
<div class="flex flex-col items-center gap-1.5">
<span class="font-medium text-center">#<?php echo $row['folio'] ?? str_pad($row['id'], 6, '0', STR_PAD_LEFT); ?></span>
<div class="flex items-center justify-center gap-1">
<?php if (!empty($row['is_anonymous']) && intval($row['is_anonymous']) == 1): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center justify-center w-6 h-6 rounded-full bg-purple-100 text-purple-700 ring-1 ring-inset ring-purple-600/20">
<i class="ph-ghost text-sm"></i>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100">
Reporte Anónimo
</div>
</div>
<?php endif; ?>
<?php if (isset($row['attachment_count']) && $row['attachment_count'] > 0): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-blue-500/10 text-blue-700 dark:text-blue-400 ring-1 ring-inset ring-blue-600/20">
<i class="ph-paperclip text-xs"></i>
<?php echo $row['attachment_count']; ?>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100 leading-tight">
<?php echo $row['attachment_count']; ?> archivo(s) adjunto(s)
</div>
</div>
<?php endif; ?>
<?php if (isset($row['comment_count']) && $row['comment_count'] > 0): ?>
<div class="relative group flex items-center justify-center">
<span class="cursor-help inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 ring-1 ring-inset ring-emerald-600/20">
<i class="ph-chat-circle text-xs"></i>
<?php echo $row['comment_count']; ?>
</span>
<div class="absolute bottom-full mb-2 opacity-0 group-hover:opacity-100 transition-all duration-200 bg-white text-gray-800 text-xs font-semibold rounded-lg py-2 px-3 whitespace-nowrap pointer-events-none z-50 shadow-xl border border-gray-100 leading-tight">
<?php echo $row['comment_count']; ?> comentario(s)
</div>
</div>
<?php endif; ?>
</div>
</div>
</td>
<td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 max-w-sm">
<?php
$rawDescription = isset($row['description']) ? $row['description'] : '';
$cleanDescription = trim(strip_tags($rawDescription));
$maxLen = 140;
if (function_exists('mb_strlen')) {
$descLen = mb_strlen($cleanDescription, 'UTF-8');
$shortDescription = $descLen > $maxLen
? mb_substr($cleanDescription, 0, $maxLen, 'UTF-8') . '…'
: $cleanDescription;
} else {
$descLen = strlen($cleanDescription);
$shortDescription = $descLen > $maxLen
? substr($cleanDescription, 0, $maxLen) . '…'
: $cleanDescription;
}
?>
<div class="flex flex-col gap-1.5">
<div class="flex items-center gap-1.5 text-xs text-gray-900 dark:text-gray-200 font-medium">
<i class="ph-tag text-blue-500"></i>
<span><?php echo $row['category_name'] ? htmlspecialchars($row['category_name']) : 'Sin categoría'; ?></span>
</div>
<span class="leading-snug"><?php echo htmlspecialchars($shortDescription); ?></span>
</div>
</td>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
<?php if (empty($row['department_names'])): ?>
<div class="flex items-center gap-2 text-gray-900 dark:text-gray-200 italic">
<i class="ph-warning-circle text-yellow-500"></i>
<span>Sin asignación</span>
</div>
<?php else: ?>
<div class="flex flex-col gap-1 text-[13px] text-gray-900 dark:text-gray-200 leading-tight">
<?php
$department_names = explode('||', $row['department_names']);
foreach ($department_names as $dept_name):
?>
<div class="flex items-start gap-1.5">
<i class="ph-buildings text-gray-400 mt-0.5 shrink-0"></i>
<span><?php echo htmlspecialchars($dept_name); ?></span>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</td>
<?php else: ?>
<td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
<?php if (!empty($row['is_anonymous']) && intval($row['is_anonymous']) == 1): ?>
<span class="text-gray-500">Anónimo</span>
<?php else: ?>
<div class="max-w-[20rem]">
<div class="truncate whitespace-nowrap"><?php echo htmlspecialchars($row['user_name'] ?? ''); ?></div>
<div class="text-gray-500 truncate whitespace-nowrap"><?php echo htmlspecialchars($row['user_email'] ?? ''); ?></div>
</div>
<?php endif; ?>
</td>
<?php endif; ?>
<?php if (function_exists('isAdmin') && (isAdmin() || (isset($_SESSION['role']) && $_SESSION['role'] === 'manager'))): ?>
<td class="px-6 py-4">
<?php
// Fecha logic
$interval = $createdDate->diff($now);
$daysAgo = $interval->days;
$timeTextDate = $daysAgo === 0 ? 'Hoy' : ($daysAgo === 1 ? 'Hace 1 día' : 'Hace ' . $daysAgo . ' días');
// Estado logic
$statusInfo = getStatusDisplayInfo($row['status']);
$timeText = '';
if ($row['status'] === 'unattended_ontime') {
$businessDaysElapsed = calculateBusinessDays($createdDate, $now);
$daysRemaining = max(0.0, 5.0 - $businessDaysElapsed);
if ($daysRemaining > 0.0) {
$timeText = formatBusinessDayDiffLabel($daysRemaining, 'día restante', 'días restantes', 1);
}
} elseif ($row['status'] === 'attended_ontime' || $row['status'] === 'attended_late') {
if ($attendedDate) {
$businessDaysTaken = calculateBusinessDays($createdDate, $attendedDate);
if ($businessDaysTaken > 0.0) {
$timeText = formatBusinessDayDiffLabel($businessDaysTaken, 'día después', 'días después', 1);
} else {
$timeText = 'mismo día';
}
}
}
?>
<div class="flex flex-col gap-2">
<!-- Fecha -->
<span class="px-2 inline-flex items-center gap-x-1.5 text-xs leading-5 font-medium rounded-full bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200 ring-1 ring-inset ring-gray-600/20 w-fit whitespace-nowrap">
<i class="ph-clock text-gray-600 dark:text-gray-400"></i>
<?php echo $timeTextDate; ?>
</span>
<!-- Estado -->
<div>
<span class="px-2 inline-flex items-center gap-x-1.5 text-xs leading-5 font-semibold rounded-full <?php echo $statusInfo['class']; ?> ring-1 ring-inset w-fit whitespace-nowrap">
<i class="<?php echo $statusInfo['icon']; ?> text-<?php echo $statusInfo['color']; ?>-600"></i>
<?php echo $statusInfo['text']; ?>
</span>
<?php if ($timeText): ?>
<div class="text-[10px] text-gray-500 mt-0.5 ml-1"><?php echo $timeText; ?></div>
<?php endif; ?>
</div>
</div>
</td>
<?php else: ?>
<td class="px-6 py-4 whitespace-nowrap">
<?php
$interval = $createdDate->diff($now);
$daysAgo = $interval->days;
$timeTextDate = $daysAgo === 0 ? 'Hoy' : ($daysAgo === 1 ? 'Hace 1 día' : 'Hace ' . $daysAgo . ' días');
?>
<span class="px-2 inline-flex items-center gap-x-1.5 text-xs leading-5 font-medium rounded-full bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200 ring-1 ring-inset ring-gray-600/20">
<i class="ph-clock text-gray-600 dark:text-gray-400"></i>
<?php echo $timeTextDate; ?>
</span>
</td>
<?php endif; ?>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<a href="view_complaint.php?id=<?php echo $row['id']; ?>"
class="inline-flex items-center text-blue-600 hover:text-blue-800 font-semibold">
Ver Detalles
<i class="ph-arrow-right ml-1"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
// Build base query string preserving current filters except 'page'
$params = $_GET;
unset($params['page']);
$baseQueryString = http_build_query($params);
$baseUrl = 'dashboard.php' . ($baseQueryString ? ('?' . $baseQueryString . '&') : '?');
// Determine page number window (Google-like: show a window around current)
$window = 2;
$startPage = max(1, $page - $window);
$endPage = min($total_pages, $page + $window);
?>
<?php if ($total_pages > 1): ?>
<nav class="mt-6 flex items-center justify-center">
<ul class="inline-flex -space-x-px">
<?php if ($page > 1): ?>
<li>