-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.php
More file actions
1235 lines (1124 loc) · 61.1 KB
/
admin.php
File metadata and controls
1235 lines (1124 loc) · 61.1 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
session_start();
// Verify admin session
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
header("Location: admin_login.php");
exit();
}
require_once 'config/database.php';
$database = new Database();
$db = $database->getConnection();
// Debug query to check spots 1 and 7 specifically
$debug_query = "SELECT o.*, a.spot_number
FROM occupied_spots o
JOIN available_spots a ON o.spot_id = a.id
WHERE a.spot_number IN ('P1', 'P7')
AND o.status != 'completed'
AND (
(o.reservation_date = CURDATE() AND CURTIME() BETWEEN o.start_time AND o.end_time)
OR (o.status = 'reserved' AND (
o.reservation_date > CURDATE()
OR (o.reservation_date = CURDATE() AND o.start_time > CURTIME())
))
)";
$debug_stmt = $db->prepare($debug_query);
$debug_stmt->execute();
$debug_results = $debug_stmt->fetchAll(PDO::FETCH_ASSOC);
error_log("Debug - Spots 1 and 7 occupancy check:");
error_log("Current time: " . date('Y-m-d H:i:s'));
foreach ($debug_results as $result) {
error_log("Spot: " . $result['spot_number'] .
", Status: " . $result['status'] .
", Date: " . $result['reservation_date'] .
", Time: " . $result['start_time'] . " - " . $result['end_time']);
}
// Get all parking spots with their current status
$spots_query = "SELECT a.*,
CASE
WHEN EXISTS (
SELECT 1 FROM occupied_spots o
WHERE o.spot_id = a.id
AND o.status != 'completed'
AND (
(o.reservation_date = CURDATE() AND CURTIME() BETWEEN o.start_time AND o.end_time)
OR (o.reservation_date < CURDATE() AND o.end_date >= CURDATE() AND CURTIME() <= o.end_time)
OR (o.reservation_date = CURDATE() AND o.start_time > o.end_time AND CURTIME() >= o.start_time)
OR (o.reservation_date = CURDATE() AND o.start_time > o.end_time AND CURTIME() <= o.end_time)
)
) THEN 'occupied'
WHEN EXISTS (
SELECT 1 FROM occupied_spots o
WHERE o.spot_id = a.id
AND o.status = 'reserved'
AND (
o.reservation_date > CURDATE()
OR (o.reservation_date = CURDATE() AND o.start_time > CURTIME())
OR (o.reservation_date < CURDATE() AND o.end_date >= CURDATE())
)
) THEN 'reserved'
ELSE 'available'
END as current_status,
CAST(SUBSTRING(spot_number, 2) AS UNSIGNED) as spot_number_numeric
FROM available_spots a
ORDER BY spot_number_numeric ASC";
$spots_stmt = $db->prepare($spots_query);
$spots_stmt->execute();
$spots = $spots_stmt->fetchAll(PDO::FETCH_ASSOC);
// Debug the final status of spots 1 and 7
foreach ($spots as $spot) {
if ($spot['spot_number'] === 'P1' || $spot['spot_number'] === 'P7') {
error_log("Final status for " . $spot['spot_number'] . ": " . $spot['current_status']);
}
}
// Get today's reservations
$today_query = "SELECT o.*, a.spot_number, u.username, u.fullname,
CASE
WHEN (o.reservation_date = CURDATE() AND CURTIME() BETWEEN o.start_time AND o.end_time) OR
(o.reservation_date < CURDATE() AND o.end_date >= CURDATE() AND CURTIME() <= o.end_time) OR
(o.reservation_date = CURDATE() AND o.start_time > o.end_time AND CURTIME() >= o.start_time) OR
(o.reservation_date = CURDATE() AND o.start_time > o.end_time AND CURTIME() <= o.end_time)
THEN 'ongoing'
ELSE 'reserved'
END as current_status
FROM occupied_spots o
JOIN available_spots a ON o.spot_id = a.id
JOIN users u ON o.user_id = u.id
WHERE DATE(o.reservation_date) = CURDATE()
AND o.status != 'completed'
ORDER BY o.start_time";
$today_stmt = $db->prepare($today_query);
$today_stmt->execute();
$today_reservations = $today_stmt->fetchAll(PDO::FETCH_ASSOC);
// Get financial reports
$financial_query = "
SELECT
DATE_FORMAT(reservation_date, '%Y-%m') as month,
COUNT(*) as total_reservations,
SUM(cost) as total_revenue,
AVG(cost) as average_revenue,
COUNT(DISTINCT user_id) as unique_users
FROM occupied_spots
WHERE status != 'cancelled'
AND reservation_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
GROUP BY DATE_FORMAT(reservation_date, '%Y-%m')
ORDER BY month DESC";
$financial_stmt = $db->prepare($financial_query);
$financial_stmt->execute();
$financial_data = $financial_stmt->fetchAll(PDO::FETCH_ASSOC);
// Get user statistics
$user_stats_query = "
SELECT
COUNT(DISTINCT user_id) as total_users,
COUNT(DISTINCT CASE WHEN reservation_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN user_id END) as active_users_30d,
COUNT(DISTINCT CASE WHEN reservation_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN user_id END) as active_users_7d
FROM occupied_spots
WHERE status != 'cancelled'";
$user_stats_stmt = $db->prepare($user_stats_query);
$user_stats_stmt->execute();
$user_stats = $user_stats_stmt->fetch(PDO::FETCH_ASSOC);
// Get peak hours analysis
$peak_hours_query = "
SELECT
HOUR(start_time) as hour,
COUNT(*) as reservation_count
FROM occupied_spots
WHERE reservation_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
AND status != 'cancelled'
GROUP BY HOUR(start_time)
ORDER BY hour";
$peak_hours_stmt = $db->prepare($peak_hours_query);
$peak_hours_stmt->execute();
$peak_hours_data = $peak_hours_stmt->fetchAll(PDO::FETCH_ASSOC);
// Get spot utilization
$spot_utilization_query = "
SELECT
a.spot_number,
COALESCE(COUNT(o.id), 0) as total_reservations,
COALESCE(SUM(CASE WHEN o.status = 'ongoing' THEN 1 ELSE 0 END), 0) as ongoing_reservations,
COALESCE(SUM(o.cost), 0) as total_revenue
FROM available_spots a
LEFT JOIN occupied_spots o ON a.id = o.spot_id
AND o.reservation_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
AND o.status != 'cancelled'
GROUP BY a.id, a.spot_number
ORDER BY total_reservations DESC";
$spot_utilization_stmt = $db->prepare($spot_utilization_query);
$spot_utilization_stmt->execute();
$spot_utilization_data = $spot_utilization_stmt->fetchAll(PDO::FETCH_ASSOC);
// Get total number of spots
$total_spots_query = "SELECT COUNT(*) as total_spots FROM available_spots";
$total_spots_stmt = $db->prepare($total_spots_query);
$total_spots_stmt->execute();
$total_spots = $total_spots_stmt->fetch(PDO::FETCH_ASSOC)['total_spots'];
// Get current ongoing reservations count
$current_ongoing_query = "
SELECT COUNT(*) as current_ongoing
FROM occupied_spots o
JOIN available_spots a ON o.spot_id = a.id
WHERE o.status = 'ongoing'";
$current_ongoing_stmt = $db->prepare($current_ongoing_query);
$current_ongoing_stmt->execute();
$current_ongoing = $current_ongoing_stmt->fetch(PDO::FETCH_ASSOC)['current_ongoing'];
$admin_username = $_SESSION['admin_username'];
// Calculate financial summary for JavaScript functions
$total_revenue = 0;
$total_reservations = 0;
foreach ($financial_data as $data) {
$total_revenue += $data['total_revenue'];
$total_reservations += $data['total_reservations'];
}
$avg_revenue = $total_reservations > 0 ? $total_revenue / $total_reservations : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Smart Parking System</title>
<link rel="stylesheet" href="css/stylesAdmin.css">
<!-- Favicon -->
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script>
// Navigation function - must be available before HTML loads
function showSection(sectionId) {
// Hide all content sections
const sections = document.querySelectorAll('.content-section');
sections.forEach(section => {
section.classList.remove('active');
});
// Remove active class from all nav boxes
const navBoxes = document.querySelectorAll('.nav-box');
navBoxes.forEach(box => {
box.classList.remove('active');
});
// Show the selected section
document.getElementById(sectionId).classList.add('active');
// Add active class to the clicked nav box
event.currentTarget.classList.add('active');
}
</script>
</head>
<body>
<div class="admin-container">
<div class="admin-header">
<h1>Admin Dashboard</h1>
<div class="user-info">
<span>Welcome, <?php echo htmlspecialchars($admin_username); ?></span>
<a href="logout.php" class="logout-btn">
<i class="fas fa-sign-out-alt"></i> Logout
</a>
</div>
</div>
<!-- Navigation Boxes -->
<div class="admin-navigation">
<div class="nav-box active" onclick="showSection('parking-management')">
<i class="fas fa-car"></i>
<h3>Parking Management</h3>
<p>Manage parking spots and reservations</p>
</div>
<div class="nav-box" onclick="showSection('system-report')">
<i class="fas fa-chart-line"></i>
<h3>System Report</h3>
<p>View analytics and system reports</p>
</div>
<div class="nav-box" onclick="showSection('download-report')">
<i class="fas fa-download"></i>
<h3>Download Report</h3>
<p>Generate and download PDF reports</p>
</div>
</div>
<div class="admin-content">
<div class="welcome-message">
Welcome to the Smart Parking System Admin Dashboard
</div>
<!-- Parking Management Section -->
<div id="parking-management" class="content-section active">
<div class="management-section">
<div class="section-header">
<h2><i class="fas fa-car"></i> Parking Management</h2>
</div>
<div class="spots-grid">
<?php foreach ($spots as $spot): ?>
<div class="spot-card" data-spot="<?php echo htmlspecialchars($spot['spot_number']); ?>" onclick="viewSpotReservations('<?php echo htmlspecialchars($spot['spot_number']); ?>')">
<h3>
<i class="fas fa-parking"></i>
<?php echo htmlspecialchars($spot['spot_number']); ?>
</h3>
<span class="spot-status status-<?php echo strtolower($spot['current_status']); ?>">
<?php echo ucfirst($spot['current_status']); ?>
</span>
</div>
<?php endforeach; ?>
</div>
<div class="section-header">
<h2><i class="fas fa-calendar-alt"></i> Today's Reservations</h2>
</div>
<?php if (empty($today_reservations)): ?>
<div class="no-reservations">
No reservations for today
</div>
<?php else: ?>
<table class="reservations-table">
<thead>
<tr>
<th>Spot</th>
<th>User</th>
<th>Time</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($today_reservations as $reservation): ?>
<tr>
<td><?php echo htmlspecialchars($reservation['spot_number']); ?></td>
<td>
<?php echo htmlspecialchars($reservation['username']); ?>
<?php if (!empty($reservation['fullname'])): ?>
<br><small>(<?php echo htmlspecialchars($reservation['fullname']); ?>)</small>
<?php endif; ?>
</td>
<td>
<?php
echo date('h:i A', strtotime($reservation['start_time'])) . ' - ' .
date('h:i A', strtotime($reservation['end_time']));
?>
</td>
<td>
<span id="currentStatus" class="reservation-status status-<?php echo strtolower($reservation['current_status']); ?>">
<?php echo ucfirst($reservation['current_status']); ?>
</span>
</td>
<td>
<button class="view-btn" onclick="viewReservation(<?php echo htmlspecialchars(json_encode($reservation)); ?>)">
<i class="fas fa-eye"></i> View
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
<!-- System Report Section -->
<div id="system-report" class="content-section">
<div class="reports-section">
<div class="section-header">
<h2><i class="fas fa-chart-line"></i> System Reports & Analytics</h2>
</div>
<!-- Financial Overview -->
<div class="revenue-trend">
<h3><i class="fas fa-money-bill-wave"></i> Financial Overview</h3>
<div class="revenue-grid">
<div class="revenue-item">
<div class="revenue-value">₱<?php echo number_format($total_revenue, 2); ?></div>
<div class="revenue-label">Total Revenue (6 Months)</div>
</div>
<div class="revenue-item">
<div class="revenue-value"><?php echo number_format($total_reservations); ?></div>
<div class="revenue-label">Total Reservations</div>
</div>
<div class="revenue-item">
<div class="revenue-value">₱<?php echo number_format($avg_revenue, 2); ?></div>
<div class="revenue-label">Average Revenue per Reservation</div>
</div>
</div>
</div>
<!-- User Statistics -->
<div class="reports-grid">
<div class="report-card">
<h3><i class="fas fa-users"></i> User Statistics</h3>
<div class="metric-grid">
<div class="metric-item">
<div class="metric-value"><?php echo number_format($user_stats['total_users']); ?></div>
<div class="metric-label">Total Users</div>
</div>
<div class="metric-item">
<div class="metric-value"><?php echo number_format($user_stats['active_users_30d']); ?></div>
<div class="metric-label">Active Users (30 Days)</div>
</div>
<div class="metric-item">
<div class="metric-value"><?php echo number_format($user_stats['active_users_7d']); ?></div>
<div class="metric-label">Active Users (7 Days)</div>
</div>
<div class="metric-item">
<div class="metric-value">
<?php
echo $user_stats['total_users'] > 0
? round(($user_stats['active_users_30d'] / $user_stats['total_users']) * 100)
: 0;
?>%
</div>
<div class="metric-label">User Retention Rate</div>
</div>
</div>
</div>
<!-- Peak Hours Analysis -->
<div class="report-card">
<h3><i class="fas fa-clock"></i> Peak Hours Analysis</h3>
<div class="chart-container">
<canvas id="peakHoursChart"></canvas>
</div>
</div>
</div>
<!-- Spot Performance -->
<div class="spot-performance">
<h3><i class="fas fa-chart-bar"></i> Spot Performance (Last 30 Days)</h3>
<table>
<thead>
<tr>
<th>Spot</th>
<th>Total Reservations</th>
<th>Current Occupancy</th>
<th>Revenue</th>
<th>Utilization</th>
</tr>
</thead>
<tbody>
<?php
$max_reservations = 0;
foreach ($spot_utilization_data as $spot) {
$max_reservations = max($max_reservations, $spot['total_reservations']);
}
foreach ($spot_utilization_data as $spot):
$utilization_percentage = ($spot['total_reservations'] / $max_reservations) * 100;
?>
<tr>
<td><?php echo htmlspecialchars($spot['spot_number']); ?></td>
<td><?php echo number_format($spot['total_reservations']); ?></td>
<td><?php echo number_format($spot['ongoing_reservations']); ?></td>
<td>₱<?php echo number_format($spot['total_revenue'], 2); ?></td>
<td>
<div class="performance-bar">
<div class="performance-bar-fill" style="width: <?php echo $utilization_percentage; ?>%"></div>
</div>
<?php echo round($utilization_percentage); ?>%
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Download Report Section -->
<div id="download-report" class="content-section">
<div class="reports-section">
<div class="section-header">
<h2><i class="fas fa-download"></i> Download Reports</h2>
</div>
<div class="download-options">
<div class="download-card">
<h3><i class="fas fa-file-pdf"></i> System Report</h3>
<p>Generate a comprehensive PDF report containing all system analytics, financial data, performance metrics, and detailed insights about the parking system operations.</p>
<button class="download-btn" onclick="generateSystemReport()">
<i class="fas fa-download"></i> Download System Report
</button>
</div>
</div>
<div class="report-preview">
<h3><i class="fas fa-eye"></i> Report Preview</h3>
<div id="reportPreview" class="preview-content">
<p>Click the download button above to generate and preview the comprehensive system report.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Add Modal -->
<div id="reservationModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2><i class="fas fa-info-circle"></i> Reservation Details</h2>
<button class="close-modal" onclick="closeModal()">×</button>
</div>
<div class="reservation-details">
<div class="detail-group">
<h3><i class="fas fa-parking"></i> Parking Information</h3>
<div class="detail-item">
<span class="detail-label">Spot Number:</span>
<span class="detail-value" id="modalSpotNumber"></span>
</div>
<div class="detail-item">
<span class="detail-label">Status:</span>
<span class="detail-value" id="modalStatus"></span>
</div>
</div>
<div class="detail-group">
<h3><i class="fas fa-user"></i> User Information</h3>
<div class="detail-item">
<span class="detail-label">Username:</span>
<span class="detail-value" id="modalUsername"></span>
</div>
<div class="detail-item">
<span class="detail-label">Full Name:</span>
<span class="detail-value" id="modalFullname"></span>
</div>
</div>
<div class="detail-group">
<h3><i class="fas fa-clock"></i> Time Information</h3>
<div class="detail-item">
<span class="detail-label">Date:</span>
<span class="detail-value" id="modalDate"></span>
</div>
<div class="detail-item">
<span class="detail-label">Start Time:</span>
<span class="detail-value" id="modalStartTime"></span>
</div>
<div class="detail-item">
<span class="detail-label">End Time:</span>
<span class="detail-value" id="modalEndTime"></span>
</div>
<div class="detail-item">
<span class="detail-label">Duration:</span>
<span class="detail-value" id="modalDuration"></span>
</div>
</div>
<div class="detail-group">
<h3><i class="fas fa-money-bill-wave"></i> Payment Information</h3>
<div class="detail-item">
<span class="detail-label">Cost:</span>
<span class="detail-value" id="modalCost"></span>
</div>
<div class="detail-item">
<span class="detail-label">Payment Status:</span>
<span class="detail-value" id="modalPaymentStatus"></span>
</div>
</div>
</div>
<div class="modal-footer">
<?php if ($reservation['status'] === 'ongoing'): ?>
<button class="modal-btn danger" onclick="endReservation(currentReservationId)">
<i class="fas fa-stop-circle"></i> End Reservation
</button>
<?php endif; ?>
<button class="modal-btn primary" onclick="closeModal()">
<i class="fas fa-times"></i> Close
</button>
</div>
</div>
</div>
<!-- Add Spot Reservations Modal -->
<div id="spotReservationsModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2><i class="fas fa-parking"></i> <span id="spotModalTitle">Spot Reservations</span></h2>
<button class="close-modal" onclick="closeSpotModal()">×</button>
</div>
<div class="reservation-details">
<div id="spotReservationsList" class="spot-reservations">
<!-- Reservations will be loaded here -->
</div>
</div>
<div class="modal-footer">
<button class="modal-btn primary" onclick="closeSpotModal()">
<i class="fas fa-times"></i> Close
</button>
</div>
</div>
</div>
<!-- Add Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let currentReservationId = null;
function viewReservation(reservation) {
currentReservationId = reservation.id;
// Format the date
const reservationDate = new Date(reservation.reservation_date);
const formattedDate = reservationDate.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
// Calculate duration
const startTime = new Date(`2000-01-01T${reservation.start_time}`);
const endTime = new Date(`2000-01-01T${reservation.end_time}`);
let duration = (endTime - startTime) / (1000 * 60 * 60); // in hours
if (duration < 0) duration += 24; // Handle overnight reservations
const durationText = `${duration.toFixed(1)} hours`;
// Update modal content
document.getElementById('modalSpotNumber').textContent = reservation.spot_number;
document.getElementById('modalStatus').innerHTML = `<span class="reservation-status status-${reservation.current_status.toLowerCase()}">${reservation.current_status.charAt(0).toUpperCase() + reservation.current_status.slice(1)}</span>`;
document.getElementById('modalUsername').textContent = reservation.username;
document.getElementById('modalFullname').textContent = reservation.fullname || 'N/A';
document.getElementById('modalDate').textContent = formattedDate;
document.getElementById('modalStartTime').textContent = new Date(`2000-01-01T${reservation.start_time}`).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
document.getElementById('modalEndTime').textContent = new Date(`2000-01-01T${reservation.end_time}`).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
document.getElementById('modalDuration').textContent = durationText;
document.getElementById('modalCost').innerHTML = `₱${parseFloat(reservation.cost).toFixed(2)}`;
document.getElementById('modalPaymentStatus').textContent = reservation.payment_status || 'Pending';
// Show modal
document.getElementById('reservationModal').style.display = 'block';
}
function closeModal() {
document.getElementById('reservationModal').style.display = 'none';
currentReservationId = null;
}
// Close modal when clicking outside
window.onclick = function(event) {
const modal = document.getElementById('reservationModal');
if (event.target === modal) {
closeModal();
}
}
function endReservation(reservationId) {
if (confirm('Are you sure you want to end this reservation?')) {
fetch('update_reservation.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `reservation_id=${reservationId}&action=end`
})
.then(response => response.json())
.then(data => {
if (data.success) {
location.reload();
} else {
alert('Error: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while updating the reservation.');
});
}
}
function viewSpotReservations(spotNumber) {
console.log('Fetching reservations for spot:', spotNumber);
// Show loading state
document.getElementById('spotModalTitle').textContent = `Spot ${spotNumber} Reservations`;
document.getElementById('spotReservationsList').innerHTML = '<div class="no-reservations">Loading reservations...</div>';
document.getElementById('spotReservationsModal').style.display = 'block';
// Fetch reservations for this spot
fetch('get_spot_reservations.php?spot=' + encodeURIComponent(spotNumber), {
method: 'GET',
credentials: 'same-origin', // Include cookies
headers: {
'Accept': 'application/json'
}
})
.then(async response => {
console.log('Response status:', response.status);
const data = await response.json();
if (!response.ok) {
// Handle different error status codes
switch (response.status) {
case 401:
throw new Error('Please log in as admin to view reservations');
case 400:
throw new Error(data.error || 'Invalid request');
case 500:
throw new Error(data.error || 'Server error occurred');
default:
throw new Error(data.error || 'Failed to load reservations');
}
}
return data;
})
.then(data => {
console.log('Received data:', data);
const container = document.getElementById('spotReservationsList');
if (!Array.isArray(data) || data.length === 0) {
container.innerHTML = '<div class="no-reservations">No reservations found for this spot</div>';
return;
}
container.innerHTML = data.map(reservation => {
try {
const date = new Date(reservation.reservation_date);
const formattedDate = date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
const startTime = new Date(`2000-01-01T${reservation.start_time}`).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
const endTime = new Date(`2000-01-01T${reservation.end_time}`).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
return `
<div class="reservation-card">
<div class="reservation-card-header">
<span class="reservation-card-time">${startTime} - ${endTime}</span>
<span class="reservation-status status-${reservation.status.toLowerCase()}">${reservation.status}</span>
</div>
<div class="reservation-card-user">
<i class="fas fa-user"></i>
${reservation.fullname || reservation.username || 'Unknown User'}
</div>
<div class="reservation-card-details">
<div class="reservation-card-detail">
<i class="fas fa-calendar"></i>
${formattedDate}
</div>
<div class="reservation-card-detail">
<i class="fas fa-money-bill-wave"></i>
₱${reservation.cost}
</div>
<div class="reservation-card-detail">
<i class="fas fa-clock"></i>
${calculateDuration(reservation.start_time, reservation.end_time)}
</div>
</div>
</div>
`;
} catch (error) {
console.error('Error processing reservation:', error, reservation);
return '';
}
}).filter(Boolean).join('');
})
.catch(error => {
console.error('Fetch error:', error);
let errorMessage = error.message;
// Try to parse the error details from the response
if (error.response) {
error.response.json().then(data => {
if (data.details) {
errorMessage = `${data.error}: ${data.details}`;
}
}).catch(() => {
// If parsing fails, use the original error message
});
}
document.getElementById('spotReservationsList').innerHTML =
`<div class="no-reservations">
<i class="fas fa-exclamation-circle"></i>
<div class="error-message">${errorMessage}</div>
<div class="error-help">Please check the database connection and try again.</div>
</div>`;
});
}
function calculateDuration(startTime, endTime) {
const start = new Date(`2000-01-01T${startTime}`);
const end = new Date(`2000-01-01T${endTime}`);
let duration = (end - start) / (1000 * 60 * 60); // in hours
if (duration < 0) duration += 24; // Handle overnight reservations
return `${duration.toFixed(1)} hours`;
}
function closeSpotModal() {
document.getElementById('spotReservationsModal').style.display = 'none';
}
// Initialize Peak Hours Chart
const peakHoursCtx = document.getElementById('peakHoursChart').getContext('2d');
const peakHoursData = <?php echo json_encode($peak_hours_data); ?>;
new Chart(peakHoursCtx, {
type: 'bar',
data: {
labels: peakHoursData.map(item => {
const hour = parseInt(item.hour);
return hour === 0 ? '12 AM' :
hour === 12 ? '12 PM' :
hour > 12 ? (hour - 12) + ' PM' :
hour + ' AM';
}),
datasets: [{
label: 'Number of Reservations',
data: peakHoursData.map(item => item.reservation_count),
backgroundColor: 'rgba(52, 152, 219, 0.5)',
borderColor: 'rgba(52, 152, 219, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
},
plugins: {
legend: {
display: false
},
title: {
display: true,
text: 'Reservation Distribution by Hour'
}
}
}
});
// Download Report Functions
function generateSystemReport() {
showLoadingState('Generating Comprehensive System Report...');
// Get PHP variables for JavaScript
const totalRevenue = <?php echo $total_revenue; ?>;
const totalReservations = <?php echo $total_reservations; ?>;
const avgRevenue = <?php echo $avg_revenue; ?>;
const userStats = <?php echo json_encode($user_stats); ?>;
const spotUtilizationData = <?php echo json_encode($spot_utilization_data); ?>;
const peakHoursData = <?php echo json_encode($peak_hours_data); ?>;
const totalSpots = <?php echo $total_spots; ?>;
const currentOngoing = <?php echo $current_ongoing; ?>;
// Create a new window for the report
const reportWindow = window.open('', '_blank');
reportWindow.document.write(`
<!DOCTYPE html>
<html>
<head>
<title>Comprehensive System Report - Smart Parking System</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.header { text-align: center; margin-bottom: 30px; }
.section { margin-bottom: 25px; }
.section h2 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 5px; }
.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 15px 0; }
.metric-item { background: #f8f9fa; padding: 15px; border-radius: 5px; text-align: center; }
.metric-value { font-size: 1.5em; font-weight: bold; color: #2c3e50; }
.metric-label { color: #6c757d; font-size: 0.9em; }
table { width: 100%; border-collapse: collapse; margin: 15px 0; }
th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
th { background: #f8f9fa; font-weight: bold; }
.footer { margin-top: 30px; text-align: center; color: #6c757d; font-size: 0.9em; }
.utilization-bar { background: #e9ecef; height: 20px; border-radius: 10px; overflow: hidden; }
.utilization-fill { background: #3498db; height: 100%; transition: width 0.3s ease; }
</style>
</head>
<body>
<div class="header">
<h1>Smart Parking System - Comprehensive System Report</h1>
<p>Generated on: ${new Date().toLocaleDateString()} at ${new Date().toLocaleTimeString()}</p>
</div>
<div class="section">
<h2>Financial Overview (Last 6 Months)</h2>
<div class="metric-grid">
<div class="metric-item">
<div class="metric-value">₱${totalRevenue.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
<div class="metric-label">Total Revenue</div>
</div>
<div class="metric-item">
<div class="metric-value">${totalReservations.toLocaleString()}</div>
<div class="metric-label">Total Reservations</div>
</div>
<div class="metric-item">
<div class="metric-value">₱${avgRevenue.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</div>
<div class="metric-label">Average Revenue per Reservation</div>
</div>
<div class="metric-item">
<div class="metric-value">${userStats.total_users > 0 ? Math.round((userStats.active_users_30d / userStats.total_users) * 100) : 0}%</div>
<div class="metric-label">User Retention Rate</div>
</div>
</div>
</div>
<div class="section">
<h2>User Statistics & Activity</h2>
<div class="metric-grid">
<div class="metric-item">
<div class="metric-value">${userStats.total_users.toLocaleString()}</div>
<div class="metric-label">Total Users</div>
</div>
<div class="metric-item">
<div class="metric-value">${userStats.active_users_30d.toLocaleString()}</div>
<div class="metric-label">Active Users (30 Days)</div>
</div>
<div class="metric-item">
<div class="metric-value">${userStats.active_users_7d.toLocaleString()}</div>
<div class="metric-label">Active Users (7 Days)</div>
</div>
<div class="metric-item">
<div class="metric-value">${peakHoursData.length > 0 ? Math.max(...peakHoursData.map(item => item.reservation_count)) : 0}</div>
<div class="metric-label">Peak Hour Reservations</div>
</div>
</div>
</div>
<div class="section">
<h2>Peak Hours Analysis (Last 30 Days)</h2>
<table>
<thead>
<tr>
<th>Hour</th>
<th>Reservations</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
${peakHoursData.map(item => {
const hour = parseInt(item.hour);
const hourLabel = hour === 0 ? '12 AM' :
hour === 12 ? '12 PM' :
hour > 12 ? (hour - 12) + ' PM' :
hour + ' AM';
const totalReservations = peakHoursData.reduce((sum, h) => sum + h.reservation_count, 0);
const percentage = totalReservations > 0 ? ((item.reservation_count / totalReservations) * 100).toFixed(1) : 0;
return `
<tr>
<td>${hourLabel}</td>
<td>${item.reservation_count}</td>
<td>${percentage}%</td>
</tr>
`;
}).join('')}
</tbody>
</table>
</div>
<div class="section">
<h2>Spot Performance & Utilization (Last 30 Days)</h2>
<table>
<thead>
<tr>
<th>Spot</th>
<th>Total Reservations</th>
<th>Current Occupancy</th>
<th>Revenue Generated</th>
<th>Utilization Rate</th>
</tr>
</thead>
<tbody>
${spotUtilizationData.map(spot => {
const maxReservations = Math.max(...spotUtilizationData.map(s => s.total_reservations));
const utilizationRate = maxReservations > 0 ? (spot.total_reservations / maxReservations) * 100 : 0;
return `
<tr>
<td>${spot.spot_number}</td>
<td>${spot.total_reservations.toLocaleString()}</td>
<td>${spot.ongoing_reservations.toLocaleString()}</td>
<td>₱${parseFloat(spot.total_revenue).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}</td>
<td>
<div class="utilization-bar">
<div class="utilization-fill" style="width: ${utilizationRate.toFixed(1)}%"></div>
</div>
${utilizationRate.toFixed(1)}%
</td>
</tr>
`;
}).join('')}
</tbody>
</table>
</div>
<div class="section">
<h2>System Performance Summary</h2>
<div class="metric-grid">
<div class="metric-item">
<div class="metric-value">${totalSpots}</div>
<div class="metric-label">Total Parking Spots</div>
</div>
<div class="metric-item">
<div class="metric-value">${currentOngoing}</div>
<div class="metric-label">Currently Occupied</div>
</div>
<div class="metric-item">
<div class="metric-value">${totalSpots > 0 ? ((currentOngoing / totalSpots) * 100).toFixed(1) : 0}%</div>