-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdatabase.php
More file actions
1072 lines (996 loc) · 36.7 KB
/
database.php
File metadata and controls
1072 lines (996 loc) · 36.7 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
require_once __DIR__ . '/config.php';
function db(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
return $pdo;
}
function find_user_by_username_or_email(string $identifier): ?array
{
$stmt = db()->prepare('SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1');
$stmt->execute([$identifier, $identifier]);
$user = $stmt->fetch();
return $user ?: null;
}
function create_user(string $username, string $email, string $password, string $role = ROLE_STAFF, ?int $linkedDoctorId = null): int
{
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = db()->prepare('INSERT INTO users (username,email,password_hash,role,linked_doctor_id) VALUES (?,?,?,?,?)');
$stmt->execute([$username, $email, $hash, $role, $linkedDoctorId]);
return (int) db()->lastInsertId();
}
function simple_stats(): array
{
$pdo = db();
$counts = [];
foreach (
[
'patients',
'doctors',
'appointments',
'treatments',
'rooms',
'admissions'
] as $table
) {
$counts[$table] = (int) $pdo->query("SELECT COUNT(*) FROM $table")->fetchColumn();
}
return $counts;
}
// Dashboard helpers
function dashboard_appointments_today(?int $doctorId = null, int $limit = 10): array
{
$sql = 'SELECT a.*, p.first_name AS patient_first, p.last_name AS patient_last, d.first_name AS doctor_first, d.last_name AS doctor_last
FROM appointments a
JOIN patients p ON p.id = a.patient_id
JOIN doctors d ON d.id = a.doctor_id
WHERE DATE(a.appointment_date) = CURDATE()';
$params = [];
if ($doctorId !== null) {
$sql .= ' AND a.doctor_id = ?';
$params[] = $doctorId;
}
$limit = (int)$limit;
$sql .= ' ORDER BY a.appointment_date ASC LIMIT ' . $limit;
$stmt = db()->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
function dashboard_appointments_today_status_counts(?int $doctorId = null): array
{
$sql = 'SELECT a.status, COUNT(*) AS c
FROM appointments a
WHERE DATE(a.appointment_date) = CURDATE()';
$params = [];
if ($doctorId !== null) {
$sql .= ' AND a.doctor_id = ?';
$params[] = $doctorId;
}
$sql .= ' GROUP BY a.status';
$stmt = db()->prepare($sql);
$stmt->execute($params);
$out = ['scheduled' => 0, 'completed' => 0, 'cancelled' => 0];
foreach ($stmt->fetchAll() as $row) {
$out[$row['status']] = (int)$row['c'];
}
return $out;
}
function dashboard_appointments_upcoming_count(?int $doctorId = null, int $days = 7): int
{
$from = date('Y-m-d 00:00:00');
$to = (new DateTime("+{$days} days"))->format('Y-m-d 23:59:59');
$sql = 'SELECT COUNT(*) FROM appointments a WHERE a.appointment_date > ? AND a.appointment_date <= ?';
$params = [$from, $to];
if ($doctorId !== null) {
$sql .= ' AND a.doctor_id = ?';
$params[] = $doctorId;
}
$stmt = db()->prepare($sql);
$stmt->execute($params);
return (int)$stmt->fetchColumn();
}
function rooms_occupancy_counts(): array
{
$stmt = db()->query('SELECT status, COUNT(*) AS c FROM rooms GROUP BY status');
$out = ['available' => 0, 'occupied' => 0, 'maintenance' => 0];
foreach ($stmt->fetchAll() as $row) {
$out[$row['status']] = (int)$row['c'];
}
return $out;
}
function admissions_open_list(int $limit = 10): array
{
$limit = (int)$limit;
$sql = 'SELECT a.*, p.first_name AS pf, p.last_name AS pl, r.room_number
FROM admissions a
JOIN patients p ON p.id = a.patient_id
JOIN rooms r ON r.id = a.room_id
WHERE a.discharged_on IS NULL
ORDER BY a.admitted_on DESC
LIMIT ' . $limit;
return db()->query($sql)->fetchAll();
}
function doctor_recent_treatments(int $doctorId, int $limit = 10): array
{
$limit = (int)$limit;
$sql = 'SELECT t.*, p.first_name AS pf, p.last_name AS pl
FROM treatments t
JOIN patients p ON p.id = t.patient_id
WHERE t.doctor_id = ?
ORDER BY t.treatment_date DESC, t.id DESC
LIMIT ' . $limit;
$stmt = db()->prepare($sql);
$stmt->execute([$doctorId]);
return $stmt->fetchAll();
}
function list_recent_appointments(int $limit = 10, ?int $doctorId = null): array
{
$sql = 'SELECT a.*, p.first_name AS patient_first, p.last_name AS patient_last, d.first_name AS doctor_first, d.last_name AS doctor_last
FROM appointments a
JOIN patients p ON p.id = a.patient_id
JOIN doctors d ON d.id = a.doctor_id';
$params = [];
if ($doctorId !== null) {
$sql .= ' WHERE a.doctor_id = ?';
$params[] = $doctorId;
}
$limit = (int)$limit;
$sql .= ' ORDER BY a.appointment_date DESC LIMIT ' . $limit;
$stmt = db()->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
/* =============== Patients =============== */
function patients_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO patients (first_name,last_name,gender,birthdate,phone,email,address) VALUES (?,?,?,?,?,?,?)');
$stmt->execute([
trim($data['first_name'] ?? ''),
trim($data['last_name'] ?? ''),
($data['gender'] ?? null) ?: null,
($data['birthdate'] ?? null) ?: null,
($data['phone'] ?? null) ?: null,
($data['email'] ?? null) ?: null,
($data['address'] ?? null) ?: null,
]);
return (int) db()->lastInsertId();
}
function patients_delete(int $id): void
{
db()->prepare('DELETE FROM patients WHERE id = ?')->execute([$id]);
}
function patients_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = '';
$params = [];
if ($q !== '') {
$where = ' AND (first_name LIKE ? OR last_name LIKE ? OR phone LIKE ? OR email LIKE ?)';
$like = "%$q%";
$params = [$like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT * FROM patients WHERE 1=1' . $where . ' ORDER BY id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM patients WHERE 1=1' . ($q !== '' ? ' AND (first_name LIKE ? OR last_name LIKE ? OR phone LIKE ? OR email LIKE ?)' : ''));
if ($q !== '') {
$cnt->execute([$like, $like, $like, $like]);
} else {
$cnt->execute();
}
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function patients_options(): array
{
return db()->query('SELECT id, first_name, last_name FROM patients ORDER BY first_name, last_name')->fetchAll();
}
function patients_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM patients WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function patients_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE patients SET first_name = ?, last_name = ?, gender = ?, birthdate = ?, phone = ?, email = ?, address = ? WHERE id = ?');
$stmt->execute([
trim($data['first_name'] ?? ''),
trim($data['last_name'] ?? ''),
($data['gender'] ?? null) ?: null,
($data['birthdate'] ?? null) ?: null,
($data['phone'] ?? null) ?: null,
($data['email'] ?? null) ?: null,
($data['address'] ?? null) ?: null,
$id,
]);
}
/* =============== Doctors =============== */
function doctors_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO doctors (first_name,last_name,email,phone,specialization,department_id) VALUES (?,?,?,?,?,?)');
$stmt->execute([
trim($data['first_name'] ?? ''),
trim($data['last_name'] ?? ''),
trim($data['email'] ?? ''),
($data['phone'] ?? null) ?: null,
($data['specialization'] ?? null) ?: null,
($data['department_id'] ?? null) ?: null,
]);
return (int) db()->lastInsertId();
}
function doctors_delete(int $id): void
{
db()->prepare('DELETE FROM doctors WHERE id = ?')->execute([$id]);
}
function doctors_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = ' WHERE 1=1';
$params = [];
if ($q !== '') {
$where .= ' AND (d.first_name LIKE ? OR d.last_name LIKE ? OR d.email LIKE ? OR d.specialization LIKE ?)';
$like = "%$q%";
$params = [$like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT d.*, dept.name AS dept_name FROM doctors d LEFT JOIN departments dept ON dept.id = d.department_id' . $where . ' ORDER BY d.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM doctors d LEFT JOIN departments dept ON dept.id = d.department_id' . ($q !== '' ? ' AND (d.first_name LIKE ? OR d.last_name LIKE ? OR d.email LIKE ? OR d.specialization LIKE ?)' : ''));
if ($q !== '') {
$cnt->execute([$like, $like, $like, $like]);
} else {
$cnt->execute();
}
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function doctors_options(): array
{
return db()->query('SELECT id, first_name, last_name FROM doctors ORDER BY first_name, last_name')->fetchAll();
}
function doctors_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM doctors WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function doctors_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE doctors SET first_name = ?, last_name = ?, email = ?, phone = ?, specialization = ?, department_id = ? WHERE id = ?');
$stmt->execute([
trim($data['first_name'] ?? ''),
trim($data['last_name'] ?? ''),
trim($data['email'] ?? ''),
($data['phone'] ?? null) ?: null,
($data['specialization'] ?? null) ?: null,
($data['department_id'] ?? null) !== null && $data['department_id'] !== '' ? (int)$data['department_id'] : null,
$id,
]);
}
/* =============== Departments =============== */
function departments_create(string $name, string $description = ''): int
{
$stmt = db()->prepare('INSERT INTO departments (name, description) VALUES (?, ?)');
$stmt->execute([$name, $description]);
return (int) db()->lastInsertId();
}
function departments_delete(int $id): void
{
db()->prepare('DELETE FROM departments WHERE id = ?')->execute([$id]);
}
function departments_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = '';
$params = [];
if ($q !== '') {
$where = ' WHERE name LIKE ? OR description LIKE ?';
$like = "%$q%";
$params = [$like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$querySql = 'SELECT * FROM departments' . $where . ' ORDER BY name LIMIT ' . $limit . ' OFFSET ' . $offset;
$stmt = $pdo->prepare($querySql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
$countSql = 'SELECT COUNT(*) FROM departments' . ($q !== '' ? ' WHERE name LIKE ? OR description LIKE ?' : '');
$countStmt = $pdo->prepare($countSql);
if ($q !== '') {
$countStmt->execute([$like, $like]);
} else {
$countStmt->execute();
}
$total = (int)$countStmt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function departments_options(): array
{
return db()->query('SELECT id, name FROM departments ORDER BY name')->fetchAll();
}
function departments_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM departments WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function departments_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE departments SET name = ?, description = ? WHERE id = ?');
$stmt->execute([
trim($data['name'] ?? ''),
trim($data['description'] ?? ''),
$id,
]);
}
/* =============== Appointments =============== */
function appointments_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO appointments (patient_id, doctor_id, appointment_date, status, notes) VALUES (?,?,?,?,?)');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
(int)($data['doctor_id'] ?? 0),
($data['appointment_date'] ?? ''),
($data['status'] ?? 'scheduled'),
($data['notes'] ?? null),
]);
return (int) db()->lastInsertId();
}
function appointments_delete(int $id): void
{
db()->prepare('DELETE FROM appointments WHERE id = ?')->execute([$id]);
}
function appointments_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE 1=1';
$params = [];
if ($q !== '') {
$where .= ' AND (p.first_name LIKE ? OR p.last_name LIKE ? OR d.first_name LIKE ? OR d.last_name LIKE ? OR a.status LIKE ?)';
$like = "%$q%";
$params = [$like, $like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$sql = 'SELECT a.*, p.first_name AS pf, p.last_name AS pl, d.first_name AS df, d.last_name AS dl FROM appointments a JOIN patients p ON p.id=a.patient_id JOIN doctors d ON d.id=a.doctor_id ' . $where . ' ORDER BY a.appointment_date DESC LIMIT ' . $limit . ' OFFSET ' . $offset;
$list = $pdo->prepare($sql);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM appointments a JOIN patients p ON p.id=a.patient_id JOIN doctors d ON d.id=a.doctor_id ' . ($q !== '' ? 'WHERE (p.first_name LIKE ? OR p.last_name LIKE ? OR d.first_name LIKE ? OR d.last_name LIKE ? OR a.status LIKE ?)' : ''));
if ($q !== '') {
$cnt->execute([$like, $like, $like, $like, $like]);
} else {
$cnt->execute();
}
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function appointments_list_for_doctor(int $doctorId, string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE a.doctor_id = ?';
$params = [$doctorId];
if ($q !== '') {
$where .= ' AND (p.first_name LIKE ? OR p.last_name LIKE ? OR a.status LIKE ?)';
$like = "%$q%";
$params = [$doctorId, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$sql = 'SELECT a.*, p.first_name AS pf, p.last_name AS pl, d.first_name AS df, d.last_name AS dl FROM appointments a JOIN patients p ON p.id=a.patient_id JOIN doctors d ON d.id=a.doctor_id ' . $where . ' ORDER BY a.appointment_date DESC LIMIT ' . $limit . ' OFFSET ' . $offset;
$list = $pdo->prepare($sql);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM appointments a JOIN patients p ON p.id=a.patient_id JOIN doctors d ON d.id=a.doctor_id ' . $where);
$cnt->execute($params);
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function appointments_options_recent(int $limit = 200): array
{
return db()->query('SELECT id, appointment_date FROM appointments ORDER BY appointment_date DESC LIMIT ' . (int)$limit)->fetchAll();
}
function appointments_minimal_recent(int $limit = 500): array
{
$limit = (int)$limit;
$sql = 'SELECT id, appointment_date, patient_id, doctor_id FROM appointments ORDER BY appointment_date DESC LIMIT ' . $limit;
return db()->query($sql)->fetchAll();
}
function appointments_options_recent_for_doctor(int $doctorId, int $limit = 200): array
{
$limit = (int)$limit;
$stmt = db()->prepare('SELECT id, appointment_date FROM appointments WHERE doctor_id = ? ORDER BY appointment_date DESC LIMIT ' . $limit);
$stmt->execute([$doctorId]);
return $stmt->fetchAll();
}
function appointments_options_for_patient(int $patientId, int $limit = 200): array
{
$limit = (int)$limit;
$stmt = db()->prepare('SELECT id, appointment_date FROM appointments WHERE patient_id = ? ORDER BY appointment_date DESC LIMIT ' . $limit);
$stmt->execute([$patientId]);
return $stmt->fetchAll();
}
function appointments_options_for_patient_and_doctor(int $patientId, int $doctorId, int $limit = 200): array
{
$limit = (int)$limit;
$stmt = db()->prepare('SELECT id, appointment_date FROM appointments WHERE patient_id = ? AND doctor_id = ? ORDER BY appointment_date DESC LIMIT ' . $limit);
$stmt->execute([$patientId, $doctorId]);
return $stmt->fetchAll();
}
function appointments_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM appointments WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function appointments_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE appointments SET patient_id = ?, doctor_id = ?, appointment_date = ?, status = ?, notes = ? WHERE id = ?');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
(int)($data['doctor_id'] ?? 0),
($data['appointment_date'] ?? ''),
($data['status'] ?? 'scheduled'),
($data['notes'] ?? null),
$id,
]);
}
/* =============== Treatments =============== */
function treatments_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO treatments (patient_id, doctor_id, appointment_id, diagnosis, treatment_date) VALUES (?,?,?,?,?)');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
($data['doctor_id'] ?? null) !== null && $data['doctor_id'] !== '' ? (int)$data['doctor_id'] : null,
($data['appointment_id'] ?? null) !== null && $data['appointment_id'] !== '' ? (int)$data['appointment_id'] : null,
($data['diagnosis'] ?? null),
($data['treatment_date'] ?? date('Y-m-d')),
]);
return (int) db()->lastInsertId();
}
function treatments_delete(int $id): void
{
db()->prepare('DELETE FROM treatments WHERE id = ?')->execute([$id]);
}
function treatments_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE 1=1';
$params = [];
if ($q !== '') {
$where .= ' AND (p.first_name LIKE ? OR p.last_name LIKE ? OR d.first_name LIKE ? OR d.last_name LIKE ? OR t.diagnosis LIKE ?)';
$like = "%$q%";
$params = [$like, $like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT t.*, p.first_name AS pf, p.last_name AS pl, d.first_name AS df, d.last_name AS dl FROM treatments t JOIN patients p ON p.id=t.patient_id LEFT JOIN doctors d ON d.id=t.doctor_id ' . $where . ' ORDER BY t.treatment_date DESC, t.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM treatments t JOIN patients p ON p.id=t.patient_id LEFT JOIN doctors d ON d.id=t.doctor_id ' . ($q !== '' ? ' WHERE (p.first_name LIKE ? OR p.last_name LIKE ? OR d.first_name LIKE ? OR d.last_name LIKE ? OR t.diagnosis LIKE ?)' : ''));
if ($q !== '') {
$cnt->execute([$like, $like, $like, $like, $like]);
} else {
$cnt->execute();
}
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function treatments_list_for_doctor(int $doctorId, string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE t.doctor_id = ?';
$params = [$doctorId];
if ($q !== '') {
$where .= ' AND (p.first_name LIKE ? OR p.last_name LIKE ? OR t.diagnosis LIKE ?)';
$like = "%$q%";
$params = [$doctorId, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT t.*, p.first_name AS pf, p.last_name AS pl, d.first_name AS df, d.last_name AS dl FROM treatments t JOIN patients p ON p.id=t.patient_id LEFT JOIN doctors d ON d.id=t.doctor_id ' . $where . ' ORDER BY t.treatment_date DESC, t.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM treatments t JOIN patients p ON p.id=t.patient_id LEFT JOIN doctors d ON d.id=t.doctor_id ' . $where);
$cnt->execute($params);
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function treatments_options_recent_with_patient(int $limit = 200): array
{
return db()->query('SELECT t.id, t.treatment_date, p.first_name, p.last_name FROM treatments t JOIN patients p ON p.id=t.patient_id ORDER BY t.id DESC LIMIT ' . (int)$limit)->fetchAll();
}
function treatments_options_recent_with_patient_for_doctor(int $doctorId, int $limit = 200): array
{
$limit = (int)$limit;
$stmt = db()->prepare('SELECT t.id, t.treatment_date, p.first_name, p.last_name FROM treatments t JOIN patients p ON p.id=t.patient_id WHERE t.doctor_id = ? ORDER BY t.id DESC LIMIT ' . $limit);
$stmt->execute([$doctorId]);
return $stmt->fetchAll();
}
function treatments_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM treatments WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function treatments_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE treatments SET patient_id = ?, doctor_id = ?, appointment_id = ?, diagnosis = ?, treatment_date = ? WHERE id = ?');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
($data['doctor_id'] ?? null) !== null && $data['doctor_id'] !== '' ? (int)$data['doctor_id'] : null,
($data['appointment_id'] ?? null) !== null && $data['appointment_id'] !== '' ? (int)$data['appointment_id'] : null,
($data['diagnosis'] ?? null),
($data['treatment_date'] ?? date('Y-m-d')),
$id,
]);
}
/* =============== Prescriptions =============== */
function prescriptions_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO prescriptions (treatment_id, medication_id, dosage, frequency, duration_days) VALUES (?,?,?,?,?)');
$stmt->execute([
(int)($data['treatment_id'] ?? 0),
(int)($data['medication_id'] ?? 0),
trim($data['dosage'] ?? ''),
trim($data['frequency'] ?? ''),
(int)($data['duration_days'] ?? 0),
]);
return (int) db()->lastInsertId();
}
function prescriptions_delete(int $id): void
{
db()->prepare('DELETE FROM prescriptions WHERE id = ?')->execute([$id]);
}
function prescriptions_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE 1=1';
$params = [];
if ($q !== '') {
$where .= ' AND (m.name LIKE ? OR p.first_name LIKE ? OR p.last_name LIKE ? OR pr.dosage LIKE ? OR pr.frequency LIKE ?)';
$like = "%$q%";
$params = [$like, $like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT pr.*, m.name AS med_name, t.treatment_date, p.first_name, p.last_name FROM prescriptions pr JOIN medications m ON m.id=pr.medication_id JOIN treatments t ON t.id=pr.treatment_id JOIN patients p ON p.id=t.patient_id ' . $where . ' ORDER BY pr.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM prescriptions pr JOIN medications m ON m.id=pr.medication_id JOIN treatments t ON t.id=pr.treatment_id JOIN patients p ON p.id=t.patient_id ' . ($q !== '' ? ' WHERE (m.name LIKE ? OR p.first_name LIKE ? OR p.last_name LIKE ? OR pr.dosage LIKE ? OR pr.frequency LIKE ?)' : ''));
if ($q !== '') {
$cnt->execute([$like, $like, $like, $like, $like]);
} else {
$cnt->execute();
}
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function prescriptions_list_for_doctor(int $doctorId, string $q, int $limit, int $offset): array
{
$pdo = db();
$where = 'WHERE t.doctor_id = ?';
$params = [$doctorId];
if ($q !== '') {
$where .= ' AND (m.name LIKE ? OR p.first_name LIKE ? OR p.last_name LIKE ? OR pr.dosage LIKE ? OR pr.frequency LIKE ?)';
$like = "%$q%";
$params = [$doctorId, $like, $like, $like, $like, $like];
}
$limit = (int)$limit;
$offset = (int)$offset;
$list = $pdo->prepare('SELECT pr.*, m.name AS med_name, t.treatment_date, p.first_name, p.last_name FROM prescriptions pr JOIN medications m ON m.id=pr.medication_id JOIN treatments t ON t.id=pr.treatment_id JOIN patients p ON p.id=t.patient_id ' . $where . ' ORDER BY pr.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute($params);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM prescriptions pr JOIN medications m ON m.id=pr.medication_id JOIN treatments t ON t.id=pr.treatment_id JOIN patients p ON p.id=t.patient_id ' . $where);
$cnt->execute($params);
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function prescriptions_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM prescriptions WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function prescriptions_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE prescriptions SET treatment_id = ?, medication_id = ?, dosage = ?, frequency = ?, duration_days = ? WHERE id = ?');
$stmt->execute([
(int)($data['treatment_id'] ?? 0),
(int)($data['medication_id'] ?? 0),
trim($data['dosage'] ?? ''),
trim($data['frequency'] ?? ''),
(int)($data['duration_days'] ?? 0),
$id,
]);
}
/* =============== Medications =============== */
function medications_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO medications (name, description) VALUES (?, ?)');
$stmt->execute([trim($data['name'] ?? ''), trim($data['description'] ?? '')]);
return (int) db()->lastInsertId();
}
function medications_delete(int $id): void
{
db()->prepare('DELETE FROM medications WHERE id = ?')->execute([$id]);
}
function medications_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$limit = (int)$limit;
$offset = (int)$offset;
if ($q === '') {
$list = $pdo->prepare('SELECT * FROM medications ORDER BY name LIMIT ' . $limit . ' OFFSET ' . $offset);
$list->execute();
$rows = $list->fetchAll();
$cnt = $pdo->query('SELECT COUNT(*) FROM medications');
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
$where = 'WHERE (name LIKE ? OR description LIKE ?)';
$list = $pdo->prepare('SELECT * FROM medications ' . $where . ' ORDER BY name LIMIT ' . $limit . ' OFFSET ' . $offset);
$like = "%$q%";
$list->execute([$like, $like]);
$rows = $list->fetchAll();
$cnt = $pdo->prepare('SELECT COUNT(*) FROM medications ' . $where);
$cnt->execute([$like, $like]);
$total = (int)$cnt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function medications_options(): array
{
return db()->query('SELECT id, name FROM medications ORDER BY name')->fetchAll();
}
function medications_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM medications WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function medications_update(int $id, array $data): void
{
$stmt = db()->prepare('UPDATE medications SET name = ?, description = ? WHERE id = ?');
$stmt->execute([
trim($data['name'] ?? ''),
trim($data['description'] ?? ''),
$id,
]);
}
/* =============== Rooms & Admissions =============== */
function rooms_create(array $data): int
{
$stmt = db()->prepare('INSERT INTO rooms (room_number, type, status) VALUES (?,?,?)');
$stmt->execute([trim($data['room_number'] ?? ''), ($data['type'] ?? null) ?: null, ($data['status'] ?? 'available')]);
return (int) db()->lastInsertId();
}
function rooms_delete(int $id): void
{
db()->prepare('DELETE FROM rooms WHERE id = ?')->execute([$id]);
}
function rooms_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$limit = (int)$limit;
$offset = (int)$offset;
if ($q === '') {
$roomsStmt = $pdo->prepare('SELECT * FROM rooms ORDER BY room_number LIMIT ' . $limit . ' OFFSET ' . $offset);
$roomsStmt->execute();
$rows = $roomsStmt->fetchAll();
$total = (int)$pdo->query('SELECT COUNT(*) FROM rooms')->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
$like = "%$q%";
$roomsStmt = $pdo->prepare('SELECT * FROM rooms WHERE (room_number LIKE ? OR type LIKE ? OR status LIKE ?) ORDER BY room_number LIMIT ' . $limit . ' OFFSET ' . $offset);
$roomsStmt->execute([$like, $like, $like]);
$rows = $roomsStmt->fetchAll();
$roomsCntStmt = $pdo->prepare('SELECT COUNT(*) FROM rooms WHERE (room_number LIKE ? OR type LIKE ? OR status LIKE ?)');
$roomsCntStmt->execute([$like, $like, $like]);
$total = (int)$roomsCntStmt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function rooms_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM rooms WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function rooms_update(int $id, array $data): void
{
$pdo = db();
$pdo->beginTransaction();
try {
$roomStmt = $pdo->prepare('SELECT status FROM rooms WHERE id = ? FOR UPDATE');
$roomStmt->execute([$id]);
$cur = $roomStmt->fetch();
if (!$cur) {
throw new RuntimeException('Room not found');
}
$newStatus = ($data['status'] ?? 'available');
$cntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntStmt->execute([$id]);
$open = (int)$cntStmt->fetchColumn();
if ($open > 0 && $newStatus !== 'occupied') {
throw new RuntimeException('Cannot change status: room has open admissions');
}
if ($open === 0 && $newStatus === 'occupied') {
throw new RuntimeException('Cannot set occupied: no open admissions');
}
$stmt = $pdo->prepare('UPDATE rooms SET room_number = ?, type = ?, status = ? WHERE id = ?');
$stmt->execute([
trim($data['room_number'] ?? ''),
($data['type'] ?? null) ?: null,
$newStatus,
$id,
]);
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}
}
function rooms_options_available(): array
{
return db()->query("SELECT id, room_number FROM rooms WHERE status = 'available' ORDER BY room_number")->fetchAll();
}
function admissions_create(array $data): int
{
$pdo = db();
$pdo->beginTransaction();
try {
$roomId = (int)($data['room_id'] ?? 0);
$lock = $pdo->prepare('SELECT status FROM rooms WHERE id = ? FOR UPDATE');
$lock->execute([$roomId]);
$roomRow = $lock->fetch();
if (!$roomRow) {
throw new RuntimeException('Room not found');
}
if ($roomRow['status'] !== 'available') {
throw new RuntimeException('Room is not available');
}
$cntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntStmt->execute([$roomId]);
if ((int)$cntStmt->fetchColumn() > 0) {
throw new RuntimeException('Room already has an open admission');
}
$stmt = $pdo->prepare('INSERT INTO admissions (patient_id, room_id, admitted_on, discharged_on, notes) VALUES (?,?,?,NULL,?)');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
$roomId,
($data['admitted_on'] ?? ''),
($data['notes'] ?? null),
]);
$newId = (int) $pdo->lastInsertId();
$upd = $pdo->prepare("UPDATE rooms SET status = 'occupied' WHERE id = ?");
$upd->execute([$roomId]);
$pdo->commit();
return $newId;
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}
}
function admissions_discharge(int $id): void
{
$pdo = db();
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare('SELECT room_id FROM admissions WHERE id = ? FOR UPDATE');
$stmt->execute([$id]);
$row = $stmt->fetch();
if ($row) {
$roomId = (int)$row['room_id'];
$pdo->prepare('UPDATE admissions SET discharged_on = NOW() WHERE id = ? AND discharged_on IS NULL')->execute([$id]);
$cntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntStmt->execute([$roomId]);
$open = (int)$cntStmt->fetchColumn();
if ($open === 0) {
$pdo->prepare("UPDATE rooms SET status = 'available' WHERE id = ?")->execute([$roomId]);
}
}
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}
}
function admissions_delete(int $id): void
{
$pdo = db();
$pdo->beginTransaction();
try {
$stmt = $pdo->prepare('SELECT room_id, discharged_on FROM admissions WHERE id = ? FOR UPDATE');
$stmt->execute([$id]);
$row = $stmt->fetch();
$pdo->prepare('DELETE FROM admissions WHERE id = ?')->execute([$id]);
if ($row) {
$roomId = (int)$row['room_id'];
$wasOpen = $row['discharged_on'] === null;
if ($wasOpen) {
$cntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntStmt->execute([$roomId]);
$open = (int)$cntStmt->fetchColumn();
if ($open === 0) {
$pdo->prepare("UPDATE rooms SET status = 'available' WHERE id = ?")->execute([$roomId]);
}
}
}
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}
}
function admissions_list(string $q, int $limit, int $offset): array
{
$pdo = db();
$limit = (int)$limit;
$offset = (int)$offset;
if ($q === '') {
$admStmt = $pdo->prepare('SELECT a.*, p.first_name AS pf, p.last_name AS pl, r.room_number FROM admissions a JOIN patients p ON p.id=a.patient_id JOIN rooms r ON r.id=a.room_id ORDER BY a.admitted_on DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$admStmt->execute();
$rows = $admStmt->fetchAll();
$admCntStmt = $pdo->query('SELECT COUNT(*) FROM admissions a JOIN patients p ON p.id=a.patient_id JOIN rooms r ON r.id=a.room_id');
$total = (int)$admCntStmt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
$like = "%$q%";
$admStmt = $pdo->prepare('SELECT a.*, p.first_name AS pf, p.last_name AS pl, r.room_number FROM admissions a JOIN patients p ON p.id=a.patient_id JOIN rooms r ON r.id=a.room_id WHERE (p.first_name LIKE ? OR p.last_name LIKE ? OR r.room_number LIKE ?) ORDER BY a.admitted_on DESC LIMIT ' . $limit . ' OFFSET ' . $offset);
$admStmt->execute([$like, $like, $like]);
$rows = $admStmt->fetchAll();
$admCntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions a JOIN patients p ON p.id=a.patient_id JOIN rooms r ON r.id=a.room_id WHERE (p.first_name LIKE ? OR p.last_name LIKE ? OR r.room_number LIKE ?)');
$admCntStmt->execute([$like, $like, $like]);
$total = (int)$admCntStmt->fetchColumn();
return ['rows' => $rows, 'total' => $total];
}
function admissions_get(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM admissions WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ?: null;
}
function admissions_update(int $id, array $data): void
{
$pdo = db();
$pdo->beginTransaction();
try {
$curStmt = $pdo->prepare('SELECT room_id, discharged_on FROM admissions WHERE id = ? FOR UPDATE');
$curStmt->execute([$id]);
$cur = $curStmt->fetch();
$oldRoomId = $cur ? (int)$cur['room_id'] : 0;
$isOpen = $cur ? ($cur['discharged_on'] === null) : false;
$newRoomId = (int)($data['room_id'] ?? 0);
if ($isOpen && $newRoomId && $newRoomId !== $oldRoomId) {
$lockNew = $pdo->prepare('SELECT status FROM rooms WHERE id = ? FOR UPDATE');
$lockNew->execute([$newRoomId]);
$newRoomRow = $lockNew->fetch();
if (!$newRoomRow) {
throw new RuntimeException('New room not found');
}
if ($newRoomRow['status'] !== 'available') {
throw new RuntimeException('New room is not available');
}
$cntNew = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntNew->execute([$newRoomId]);
if ((int)$cntNew->fetchColumn() > 0) {
throw new RuntimeException('New room already has an open admission');
}
}
$stmt = $pdo->prepare('UPDATE admissions SET patient_id = ?, room_id = ?, admitted_on = ?, notes = ? WHERE id = ?');
$stmt->execute([
(int)($data['patient_id'] ?? 0),
$newRoomId,
($data['admitted_on'] ?? ''),
($data['notes'] ?? null),
$id,
]);
if ($isOpen) {
if ($newRoomId && $newRoomId !== $oldRoomId) {
$pdo->prepare("UPDATE rooms SET status = 'occupied' WHERE id = ?")->execute([$newRoomId]);
if ($oldRoomId) {
$cntStmt = $pdo->prepare('SELECT COUNT(*) FROM admissions WHERE room_id = ? AND discharged_on IS NULL');
$cntStmt->execute([$oldRoomId]);
$open = (int)$cntStmt->fetchColumn();
if ($open === 0) {
$pdo->prepare("UPDATE rooms SET status = 'available' WHERE id = ?")->execute([$oldRoomId]);
}