File size: 118,313 Bytes
ef2c3c7
 
 
 
99c5472
ef2c3c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a29a57c
 
 
 
 
 
 
 
 
 
 
 
 
ef2c3c7
 
 
 
a29a57c
 
 
 
 
 
 
 
ef2c3c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—

โ•‘  MAT (Modular Assistant Toolkit) โ€” ุญู‚ูŠุจุฉ ุงู„ุฃุฏูˆุงุช ุงู„ู…ุณุงุนุฏุฉ (1.40.0)  โ•‘

โ•‘                                                              โ•‘

โ•‘  ูŠุนู…ู„ ุจุฏูˆู† ุฅู†ุชุฑู†ุช ุนู„ู‰ ุงู„ุดุจูƒุฉ ุงู„ู…ุญู„ูŠุฉ                        โ•‘

โ•‘  ู„ุง ูŠุญุชุงุฌ ุชุซุจูŠุช ุฃูŠ ู…ูƒุชุจุงุช ุฅุถุงููŠุฉ                           โ•‘

โ•‘                                                              โ•‘

โ•‘  ุงู„ุชุดุบูŠู„: python server.py                                   โ•‘

โ•‘  ุงู„ูˆุตูˆู„: http://ุนู†ูˆุงู†-ุงู„ุฌู‡ุงุฒ:5000                            โ•‘

โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

"""

import http.server
import socketserver
import sqlite3
import json
import hashlib
import uuid
import os
import re
import urllib.parse
from datetime import datetime, timedelta
from http.cookies import SimpleCookie
import socket
import threading
import sys
import mimetypes
import shutil

# Ensure UTF-8 stdout encoding for Windows console
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
    sys.stderr.reconfigure(encoding='utf-8')

# โ”€โ”€โ”€ Environment & Configuration โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def load_env():
    env_file = os.path.join(BASE_DIR, '.env')
    if os.path.isfile(env_file):
        with open(env_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    k, v = line.split('=', 1)
                    os.environ.setdefault(k.strip(), v.strip())

load_env()

MAT_ENV = os.environ.get('MAT_ENV', 'production')
MAT_PORT = int(os.environ.get('PORT', os.environ.get('MAT_PORT', 5001)))
MAT_HOST = os.environ.get('MAT_HOST', '0.0.0.0')
_data_dir = '/data'
if not os.path.exists(_data_dir):
    try:
        os.makedirs(_data_dir, exist_ok=True)
    except Exception:
        _data_dir = BASE_DIR

_default_db = os.path.join(_data_dir, 'mat_complaints.db')
MAT_DB_PATH = os.environ.get('MAT_DB_PATH', _default_db)
MAT_API_PREFIX = os.environ.get('MAT_API_PREFIX', '/api/v1/mat')
MAT_SECRET_KEY = os.environ.get('MAT_SECRET_KEY', 'mat_secret_key_2026')

DB_PATH = MAT_DB_PATH
PORT = MAT_PORT
HOST = MAT_HOST

# Seed database volume if not already existing
if not os.path.exists(DB_PATH):
    source_seed = os.path.join(BASE_DIR, 'complaints.db')
    if os.path.exists(source_seed) and os.path.abspath(source_seed) != os.path.abspath(DB_PATH):
        try:
            shutil.copy2(source_seed, DB_PATH)
            print(f"[*] Initialized database volume from seed file: {source_seed} -> {DB_PATH}")
        except Exception as e_seed:
            print(f"[!] Could not copy seed DB to volume: {e_seed}")

matConfig = {
    'env': MAT_ENV,
    'port': MAT_PORT,
    'host': MAT_HOST,
    'db_path': MAT_DB_PATH,
    'api_prefix': MAT_API_PREFIX,
    'name': 'MAT',
    'arabic_name': 'ุญู‚ูŠุจุฉ ุงู„ุฃุฏูˆุงุช ุงู„ู…ุณุงุนุฏุฉ',
    'full_name': 'Modular Assistant Toolkit',
    'description': 'A highly scalable, modular digital workspace designed for governorate departments and official administrative support'
}


# โ”€โ”€โ”€ Global State โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
chat_event = threading.Event()

# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  DATABASE
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def get_db():
    """Get a new database connection (thread-safe)."""
    conn = sqlite3.connect(DB_PATH, timeout=15)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA synchronous=NORMAL")
    conn.execute("PRAGMA foreign_keys=ON")
    return conn


def dict_from_row(row):
    """Convert sqlite3.Row to dict."""
    if row is None:
        return None
    return dict(row)


def rows_to_list(rows):
    """Convert list of sqlite3.Row to list of dicts."""
    return [dict(r) for r in rows]


def sync_postponed_appointments(conn):
    """Auto-update status of parent or superseded mat_appointments to 'ู…ูุคุฌู„'."""
    try:
        # 1. Explicit parent mat_appointments
        conn.execute("""

            UPDATE mat_simple_appointments 

            SET status = 'ู…ูุคุฌู„', updated_at = datetime('now', 'localtime')

            WHERE id IN (

                SELECT DISTINCT parent_appointment_id 

                FROM mat_simple_appointments 

                WHERE parent_appointment_id IS NOT NULL AND parent_appointment_id != ''

            ) AND status = 'ู…ูุฌุฏูˆู„'

        """)
        # 2. Older mat_appointments for same visitor or case number where a newer appointment was created
        conn.execute("""

            UPDATE mat_simple_appointments 

            SET status = 'ู…ูุคุฌู„', updated_at = datetime('now', 'localtime')

            WHERE status = 'ู…ูุฌุฏูˆู„' AND id IN (

                SELECT a1.id

                FROM mat_simple_appointments a1

                JOIN mat_simple_appointments a2 

                  ON (

                       (a1.case_number = a2.case_number AND a1.case_number IS NOT NULL AND a1.case_number != '') 

                       OR 

                       (a1.visitor_name = a2.visitor_name AND a1.visitor_name IS NOT NULL AND a1.visitor_name != '')

                     )

                 AND a2.id > a1.id

                 AND (

                       a2.appointment_date > a1.appointment_date 

                       OR 

                       (a2.appointment_date = a1.appointment_date AND a2.appointment_time > a1.appointment_time)

                     )

                WHERE a1.status = 'ู…ูุฌุฏูˆู„'

            )

        """)
        conn.commit()
    except Exception as e:
        print(f"Error syncing postponed mat_appointments: {e}")



BACKUP_JSON_PATH = os.path.join(BASE_DIR, 'data_backup.json')


def backup_db_to_json(conn=None):
    """Export current DB state to data_backup.json for cloud persistence."""
    should_close = False
    if conn is None:
        try:
            conn = get_db()
            should_close = True
        except Exception:
            return
    try:
        data = {
            'officers': rows_to_list(conn.execute("SELECT * FROM mat_officers").fetchall()),
            'simple_appointments': rows_to_list(conn.execute("SELECT * FROM mat_simple_appointments").fetchall()),
            'reserved_files': rows_to_list(conn.execute("SELECT * FROM mat_reserved_files").fetchall()),
            'file_custody_log': rows_to_list(conn.execute("SELECT * FROM mat_file_custody_log").fetchall()),
            'search_logs': rows_to_list(conn.execute("SELECT * FROM mat_search_logs").fetchall()),
            'updated_at': datetime.now().isoformat()
        }
        with open(BACKUP_JSON_PATH, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"Error backing up DB to JSON: {e}")
    finally:
        if should_close:
            conn.close()


def restore_db_from_json(conn):
    """Restore DB state from data_backup.json if database tables are empty or newly initialized."""
    if not os.path.exists(BACKUP_JSON_PATH):
        return
    try:
        with open(BACKUP_JSON_PATH, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # Restore Officers
        officers = data.get('officers', [])
        for o in officers:
            existing = conn.execute("SELECT id FROM mat_officers WHERE username = ?", (o['username'],)).fetchone()
            if not existing:
                conn.execute("""

                    INSERT INTO mat_officers (id, name, username, password_hash, salt, role, accessible_tools, is_active, created_at, updated_at)

                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

                """, (o.get('id'), o.get('name'), o.get('username'), o.get('password_hash'), o.get('salt'), o.get('role'), o.get('accessible_tools'), o.get('is_active', 1), o.get('created_at'), o.get('updated_at')))
            else:
                conn.execute("""

                    UPDATE mat_officers SET name = ?, role = ?, accessible_tools = ?, is_active = ?, updated_at = ? WHERE username = ?

                """, (o.get('name'), o.get('role'), o.get('accessible_tools'), o.get('is_active', 1), o.get('updated_at'), o['username']))

        # Restore Simple Appointments
        appts = data.get('simple_appointments', [])
        for a in appts:
            existing = conn.execute("SELECT id FROM mat_simple_appointments WHERE id = ?", (a['id'],)).fetchone()
            if not existing:
                conn.execute("""

                    INSERT INTO mat_simple_appointments (id, case_number, visitor_name, phone, national_id, station_name, appointment_date, appointment_time, status, notes, created_by_id, requested_by_id, parent_appointment_id, created_at, updated_at)

                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

                """, (a.get('id'), a.get('case_number'), a.get('visitor_name'), a.get('phone'), a.get('national_id'), a.get('station_name'), a.get('appointment_date'), a.get('appointment_time'), a.get('status'), a.get('notes'), a.get('created_by_id'), a.get('requested_by_id'), a.get('parent_appointment_id'), a.get('created_at'), a.get('updated_at')))

        # Restore Reserved Files
        files = data.get('reserved_files', [])
        for r in files:
            existing = conn.execute("SELECT id FROM mat_reserved_files WHERE file_number = ?", (r['file_number'],)).fetchone()
            if not existing:
                conn.execute("""

                    INSERT INTO mat_reserved_files (id, file_number, officer_id, notes, reserved_at)

                    VALUES (?, ?, ?, ?, ?)

                """, (r.get('id'), r.get('file_number'), r.get('officer_id'), r.get('notes'), r.get('reserved_at')))

        # Restore File Custody Log
        logs = data.get('file_custody_log', [])
        for l in logs:
            existing = conn.execute("SELECT id FROM mat_file_custody_log WHERE id = ?", (l['id'],)).fetchone()
            if not existing:
                conn.execute("""

                    INSERT INTO mat_file_custody_log (id, reserved_file_id, from_officer_id, to_officer_id, status, notes, transferred_at)

                    VALUES (?, ?, ?, ?, ?, ?, ?)

                """, (l.get('id'), l.get('reserved_file_id'), l.get('from_officer_id'), l.get('to_officer_id'), l.get('status'), l.get('notes'), l.get('transferred_at')))

        conn.commit()
    except Exception as e:
        print(f"Error restoring DB from JSON backup: {e}")


def init_db():
    """Initialize database tables and default data."""
    conn = get_db()
    c = conn.cursor()

    # โ”€โ”€ Auto-Migration: Rename legacy tables to mat_ prefix BEFORE table creation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    legacy_tables = [
        ('officers', 'mat_officers'),
        ('complaints', 'mat_complaints'),
        ('parties', 'mat_parties'),
        ('appointments', 'mat_appointments'),
        ('appointment_parties', 'mat_appointment_parties'),
        ('activity_log', 'mat_activity_log'),
        ('simple_appointments', 'mat_simple_appointments'),
        ('search_logs', 'mat_search_logs'),
        ('chat_messages', 'mat_chat_messages'),
        ('reserved_files', 'mat_reserved_files'),
        ('file_custody_log', 'mat_file_custody_log'),
        ('sessions', 'mat_sessions'),
        ('audit_logs', 'mat_audit_logs')
    ]
    for old_t, new_t in legacy_tables:
        try:
            res_old = c.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{old_t}'").fetchone()[0]
            res_new = c.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{new_t}'").fetchone()[0]
            if res_old > 0 and res_new == 0:
                c.execute(f"ALTER TABLE {old_t} RENAME TO {new_t}")
        except Exception as e:
            print(f"Migration rename error for {old_t} -> {new_t}: {e}")
    conn.commit()
    # โ”€โ”€ Auto-Migration: Rename legacy tables to mat_ prefix โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    legacy_tables = [
        ('mat_officers', 'mat_officers'),
        ('mat_complaints', 'mat_complaints'),
        ('mat_parties', 'mat_parties'),
        ('mat_appointments', 'mat_appointments'),
        ('mat_appointment_parties', 'mat_appointment_parties'),
        ('mat_activity_log', 'mat_activity_log'),
        ('mat_simple_appointments', 'mat_simple_appointments'),
        ('mat_search_logs', 'mat_search_logs'),
        ('mat_chat_messages', 'mat_chat_messages'),
        ('mat_reserved_files', 'mat_reserved_files'),
        ('mat_file_custody_log', 'mat_file_custody_log'),
        ('mat_sessions', 'mat_sessions'),
        ('mat_audit_logs', 'mat_audit_logs')
    ]
    for old_t, new_t in legacy_tables:
        try:
            res_old = c.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{old_t}'").fetchone()[0]
            res_new = c.execute(f"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{new_t}'").fetchone()[0]
            if res_old > 0 and res_new == 0:
                c.execute(f"ALTER TABLE {old_t} RENAME TO {new_t}")
        except Exception as e:
            print(f"Migration rename error for {old_t} -> {new_t}: {e}")
    conn.commit()


    c.executescript('''

        CREATE TABLE IF NOT EXISTS mat_officers (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            name TEXT NOT NULL,

            username TEXT UNIQUE NOT NULL,

            password_hash TEXT NOT NULL,

            salt TEXT NOT NULL,

            role TEXT NOT NULL CHECK(role IN ('admin', 'officer', 'caller')),

            accessible_tools TEXT DEFAULT 'mat_complaints,finder',

            is_active INTEGER DEFAULT 1,

            created_at TEXT DEFAULT (datetime('now', 'localtime')),

            updated_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_complaints (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            complaint_number TEXT,

            subject TEXT NOT NULL,

            complaint_type TEXT DEFAULT 'ุนุงู…',

            status TEXT DEFAULT 'ุฌุฏูŠุฏ',

            priority TEXT DEFAULT 'ุนุงุฏูŠ',

            notes TEXT,

            assigned_officer_id INTEGER REFERENCES mat_officers(id),

            created_by_id INTEGER REFERENCES mat_officers(id),

            created_at TEXT DEFAULT (datetime('now', 'localtime')),

            updated_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_parties (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            complaint_id INTEGER NOT NULL REFERENCES mat_complaints(id) ON DELETE CASCADE,

            party_type TEXT NOT NULL CHECK(party_type IN ('ุดุงูƒูŠ', 'ู…ุดุชูƒู‰_ุนู„ูŠู‡')),

            name TEXT NOT NULL,

            phone TEXT,

            national_id TEXT,

            address TEXT,

            notes TEXT,

            created_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_appointments (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            complaint_id INTEGER NOT NULL REFERENCES mat_complaints(id) ON DELETE CASCADE,

            appointment_date TEXT NOT NULL,

            appointment_time TEXT NOT NULL,

            appointment_type TEXT DEFAULT 'ูุฑุฏูŠ' CHECK(appointment_type IN ('ูุฑุฏูŠ', 'ู…ุดุชุฑูƒ')),

            status TEXT DEFAULT 'ู…ูุฌุฏูˆู„',

            location TEXT DEFAULT 'ู…ูƒุชุจ ู‚ุณู… ุงู„ุดูƒุงูˆูŠ',

            notes TEXT,

            requested_by_id INTEGER REFERENCES mat_officers(id),

            parent_appointment_id INTEGER REFERENCES mat_appointments(id),

            created_by_id INTEGER REFERENCES mat_officers(id),

            created_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_appointment_parties (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            appointment_id INTEGER NOT NULL REFERENCES mat_appointments(id) ON DELETE CASCADE,

            party_id INTEGER NOT NULL REFERENCES mat_parties(id) ON DELETE CASCADE,

            call_status TEXT DEFAULT 'ู„ู…_ูŠูุชุตู„',

            called_at TEXT,

            called_by_id INTEGER REFERENCES mat_officers(id),

            attendance TEXT DEFAULT 'ู…ู†ุชุธุฑ',

            notes TEXT,

            UNIQUE(appointment_id, party_id)

        );



        CREATE TABLE IF NOT EXISTS mat_activity_log (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            user_id INTEGER REFERENCES mat_officers(id),

            action TEXT NOT NULL,

            entity_type TEXT,

            entity_id INTEGER,

            details TEXT,

            created_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_simple_appointments (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            case_number TEXT NOT NULL,

            visitor_name TEXT NOT NULL,

            phone TEXT,

            national_id TEXT,

            station_name TEXT,

            appointment_date TEXT NOT NULL,

            appointment_time TEXT NOT NULL,

            status TEXT DEFAULT 'ู…ูุฌุฏูˆู„',

            notes TEXT,

            requested_by_id INTEGER REFERENCES mat_officers(id),

            parent_appointment_id INTEGER REFERENCES mat_simple_appointments(id),

            created_by_id INTEGER REFERENCES mat_officers(id),

            created_at TEXT DEFAULT (datetime('now', 'localtime')),

            updated_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_search_logs (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            area_name TEXT NOT NULL UNIQUE,

            closest_station TEXT NOT NULL,

            directorate TEXT NOT NULL,

            search_count INTEGER DEFAULT 1,

            last_searched_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE TABLE IF NOT EXISTS mat_chat_messages (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            user_id INTEGER REFERENCES mat_officers(id),

            message TEXT NOT NULL,

            created_at TEXT DEFAULT (datetime('now', 'localtime'))

        );



        CREATE INDEX IF NOT EXISTS idx_parties_phone ON mat_parties(phone);

        CREATE INDEX IF NOT EXISTS idx_parties_name ON mat_parties(name);

        CREATE INDEX IF NOT EXISTS idx_complaints_status ON mat_complaints(status);

        CREATE INDEX IF NOT EXISTS idx_appointments_date ON mat_appointments(appointment_date);

        CREATE INDEX IF NOT EXISTS idx_simple_appts_date ON mat_simple_appointments(appointment_date);

        CREATE INDEX IF NOT EXISTS idx_simple_appts_case ON mat_simple_appointments(case_number);

        CREATE INDEX IF NOT EXISTS idx_simple_appts_name ON mat_simple_appointments(visitor_name);

        CREATE INDEX IF NOT EXISTS idx_search_logs_count ON mat_search_logs(search_count);

        CREATE TABLE IF NOT EXISTS mat_reserved_files (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            file_number TEXT NOT NULL UNIQUE,

            officer_id INTEGER NOT NULL REFERENCES mat_officers(id),

            notes TEXT,

            reserved_at TEXT DEFAULT (datetime('now', 'localtime'))

        );

        CREATE TABLE IF NOT EXISTS mat_file_custody_log (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            reserved_file_id INTEGER NOT NULL REFERENCES mat_reserved_files(id) ON DELETE CASCADE,

            from_officer_id INTEGER REFERENCES mat_officers(id),

            to_officer_id INTEGER NOT NULL REFERENCES mat_officers(id),

            status TEXT DEFAULT 'accepted',

            notes TEXT,

            transferred_at TEXT DEFAULT (datetime('now', 'localtime'))

        );

        CREATE TABLE IF NOT EXISTS mat_sessions (

            token TEXT PRIMARY KEY,

            user_id INTEGER NOT NULL REFERENCES mat_officers(id),

            username TEXT NOT NULL,

            role TEXT NOT NULL,

            name TEXT NOT NULL,

            accessible_tools TEXT,

            created_at TEXT DEFAULT (datetime('now', 'localtime')),

            last_seen TEXT DEFAULT (datetime('now', 'localtime'))

        );

        CREATE TABLE IF NOT EXISTS mat_audit_logs (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            action TEXT NOT NULL,

            resource_id TEXT NOT NULL,

            actor_id INTEGER REFERENCES mat_officers(id),

            timestamp TEXT DEFAULT (datetime('now', 'localtime')),

            details TEXT

        );

    ''')

    # Run DB Migrations for existing databases
    try:
        # Check if mat_audit_logs exists
        c.execute("CREATE TABLE IF NOT EXISTS mat_audit_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, action TEXT NOT NULL, resource_id TEXT NOT NULL, actor_id INTEGER REFERENCES mat_officers(id), timestamp TEXT DEFAULT (datetime('now', 'localtime')), details TEXT)")

        # Check if mat_file_custody_log exists and has status column
        c.execute("CREATE TABLE IF NOT EXISTS mat_file_custody_log (id INTEGER PRIMARY KEY AUTOINCREMENT, reserved_file_id INTEGER NOT NULL REFERENCES mat_reserved_files(id) ON DELETE CASCADE, from_officer_id INTEGER REFERENCES mat_officers(id), to_officer_id INTEGER NOT NULL REFERENCES mat_officers(id), status TEXT DEFAULT 'accepted', notes TEXT, transferred_at TEXT DEFAULT (datetime('now', 'localtime')))")
        cols = [row[1] for row in c.execute("PRAGMA table_info(mat_file_custody_log)").fetchall()]
        if 'status' not in cols:
            c.execute("ALTER TABLE mat_file_custody_log ADD COLUMN status TEXT DEFAULT 'accepted'")

        # Check if accessible_tools exists in mat_officers
        cols = [row[1] for row in c.execute("PRAGMA table_info(mat_officers)").fetchall()]
        if 'accessible_tools' not in cols:
            c.execute("ALTER TABLE mat_officers ADD COLUMN accessible_tools TEXT DEFAULT 'dashboard,mat_complaints,finder,file_reservations,chat'")
        else:
            # Update existing users to have dashboard, file_reservations, and chat if missing
            c.execute("UPDATE mat_officers SET accessible_tools = 'dashboard,' || accessible_tools WHERE accessible_tools NOT LIKE '%dashboard%' AND accessible_tools IS NOT NULL AND accessible_tools != ''")
            c.execute("UPDATE mat_officers SET accessible_tools = accessible_tools || ',chat' WHERE accessible_tools NOT LIKE '%chat%' AND accessible_tools IS NOT NULL AND accessible_tools != ''")

        # Check if last_chat_seen exists in mat_sessions
        sess_cols = [row[1] for row in c.execute("PRAGMA table_info(mat_sessions)").fetchall()]
        if 'last_chat_seen' not in sess_cols:
            c.execute("ALTER TABLE mat_sessions ADD COLUMN last_chat_seen TEXT")

        # Check mat_appointments table
        cols = [row[1] for row in c.execute("PRAGMA table_info(mat_appointments)").fetchall()]
        if 'requested_by_id' not in cols:
            c.execute("ALTER TABLE mat_appointments ADD COLUMN requested_by_id INTEGER REFERENCES mat_officers(id)")
        if 'parent_appointment_id' not in cols:
            c.execute("ALTER TABLE mat_appointments ADD COLUMN parent_appointment_id INTEGER REFERENCES mat_appointments(id)")

        # Check mat_simple_appointments table
        cols = [row[1] for row in c.execute("PRAGMA table_info(mat_simple_appointments)").fetchall()]
        if 'requested_by_id' not in cols:
            c.execute("ALTER TABLE mat_simple_appointments ADD COLUMN requested_by_id INTEGER REFERENCES mat_officers(id)")
        # Auto-update status of parent mat_appointments to 'ู…ูุคุฌู„' if they have a branched appointment
        c.execute("""

            UPDATE mat_simple_appointments 

            SET status = 'ู…ูุคุฌู„' 

            WHERE id IN (

                SELECT DISTINCT parent_appointment_id 

                FROM mat_simple_appointments 

                WHERE parent_appointment_id IS NOT NULL AND parent_appointment_id != ''

            ) AND status = 'ู…ูุฌุฏูˆู„'

        """)
    except Exception as e:
        print(f"Migration error: {e}")



    # Create default accounts if none exist
    existing = c.execute("SELECT COUNT(*) as cnt FROM mat_officers").fetchone()
    if existing['cnt'] == 0:
        defaults = [
            ('ุนุฑูˆุฉ', 'orwa', '12345', 'admin'),
            ('ุงูŠู‡ุงุจ', 'ehab', '12345', 'officer'),
            ('ุณู„ุทุงู†', 'sultan', '12345', 'officer'),
            ('ุงุจูˆุงู„ุฒูŠุช', 'abualzait', '12345', 'officer'),
            ('ุฑุนุฏ', 'raad', '12345', 'caller'),
        ]
        for name, username, password, role in defaults:
            salt = uuid.uuid4().hex
            pw_hash = 'pbkdf2:' + hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000).hex()
            c.execute(
                "INSERT INTO mat_officers (name, username, password_hash, salt, role) VALUES (?,?,?,?,?)",
                (name, username, pw_hash, salt, role)
            )
        print("โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”")
        print("โ”‚ โœ… ุชู… ุฅู†ุดุงุก ุงู„ุญุณุงุจุงุช ุงู„ุงูุชุฑุงุถูŠุฉ:                โ”‚")
        print("โ”‚                                                   โ”‚")
        print("โ”‚  ุฑุฆูŠุณ ู‚ุณู…:  ุนุฑูˆุฉ (orwa)                            โ”‚")
        print("โ”‚  ุถุงุจุท ูก:    ุงูŠู‡ุงุจ (ehab)                           โ”‚")
        print("โ”‚  ุถุงุจุท ูข:    ุณู„ุทุงู† (sultan)                         โ”‚")
        print("โ”‚  ุถุงุจุท ูฃ:    ุงุจูˆุงู„ุฒูŠุช (abualzait)                   โ”‚")
        print("โ”‚  ุงู„ุงุชุตุงู„:   ุฑุนุฏ (raad)                             โ”‚")
        print("โ”‚                                                   โ”‚")
        print("โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜")

    restore_db_from_json(conn)
    conn.commit()
    conn.close()
    backup_db_to_json()


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  AUTH HELPERS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def create_session(user_id, username, role, name, accessible_tools):
    """Create a new session and return the token."""
    token = uuid.uuid4().hex
    conn = get_db()
    conn.execute(
        "INSERT INTO mat_sessions (token, user_id, username, role, name, accessible_tools) VALUES (?, ?, ?, ?, ?, ?)",
        (token, user_id, username, role, name, accessible_tools)
    )
    conn.commit()
    conn.close()
    return token


def get_session(token):
    """Get session data by token."""
    conn = get_db()
    session = dict_from_row(conn.execute("SELECT * FROM mat_sessions WHERE token = ?", (token,)).fetchone())
    if session:
        conn.execute("UPDATE mat_sessions SET last_seen = datetime('now', 'localtime') WHERE token = ?", (token,))
        conn.commit()
    conn.close()
    return session


def delete_session(token):
    """Delete a session."""
    conn = get_db()
    conn.execute("DELETE FROM mat_sessions WHERE token = ?", (token,))
    conn.commit()
    conn.close()


def touch_chat_session(token):
    """Update last_chat_seen timestamp for active chat users."""
    if not token:
        return
    try:
        conn = get_db()
        conn.execute("UPDATE mat_sessions SET last_chat_seen = datetime('now', 'localtime') WHERE token = ?", (token,))
        conn.commit()
        conn.close()
    except Exception as e:
        print('Error touching chat session:', e)


def log_activity(conn, user_id, action, entity_type=None, entity_id=None, details=None):
    """Log user activity."""
    conn.execute(
        "INSERT INTO mat_activity_log (user_id, action, entity_type, entity_id, details) VALUES (?,?,?,?,?)",
        (user_id, action, entity_type, entity_id, details)
    )


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  HTTP REQUEST HANDLER
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

class MatServerHandler(http.server.SimpleHTTPRequestHandler):
    """Custom HTTP handler for the MAT system."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=BASE_DIR, **kwargs)

    def log_message(self, format, *args):
        """Custom log format."""
        pass  # Suppress default logging for cleaner output

    # โ”€โ”€ Auth helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def get_current_user(self):
        """Get current user from session cookie."""
        cookie_header = self.headers.get('Cookie', '')
        cookie = SimpleCookie()
        try:
            cookie.load(cookie_header)
        except Exception:
            return None
        session_morsel = cookie.get('session')
        if session_morsel:
            return get_session(session_morsel.value)
        return None

    def require_auth(self):
        """Check if user is authenticated. Returns user or None."""
        user = self.get_current_user()
        if not user:
            self.send_json({'error': 'ุบูŠุฑ ู…ุตุฑู‘ุญ'}, 401)
            return None
        return user

    def validate_csrf(self):
        """Validate CSRF token using Double Submit Cookie pattern."""
        cookie_header = self.headers.get('Cookie', '')
        cookie = SimpleCookie()
        try:
            cookie.load(cookie_header)
        except Exception:
            return False
        csrf_cookie = cookie.get('csrf_token')
        csrf_header = self.headers.get('X-CSRF-Token')
        if not csrf_cookie or not csrf_header:
            return False
        return csrf_cookie.value == csrf_header

    def require_role(self, *roles):
        """Check if user has required role."""
        user = self.require_auth()
        if user and user['role'] not in roles:
            self.send_json({'error': 'ู„ูŠุณ ู„ุฏูŠูƒ ุตู„ุงุญูŠุฉ'}, 403)
            return None
        return user

    # โ”€โ”€ Response helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def do_OPTIONS(self):
        """Handle CORS preflight OPTIONS requests."""
        self.send_response(200)
        origin = self.headers.get('Origin')
        if origin:
            self.send_header('Access-Control-Allow-Origin', origin)
            self.send_header('Access-Control-Allow-Credentials', 'true')
        else:
            self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-CSRF-Token, Authorization, Cookie')
        self.end_headers()

    def send_json(self, data, status=200, cookie=None):
        """Send JSON response."""
        self.send_response(status)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        origin = self.headers.get('Origin')
        if origin:
            self.send_header('Access-Control-Allow-Origin', origin)
            self.send_header('Access-Control-Allow-Credentials', 'true')
        else:
            self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-CSRF-Token, Authorization, Cookie')
        if cookie:
            if isinstance(cookie, list):
                for c in cookie:
                    self.send_header('Set-Cookie', c)
            else:
                self.send_header('Set-Cookie', cookie)
        self.end_headers()
        self.wfile.write(json.dumps(data, ensure_ascii=False, default=str).encode('utf-8'))

    def read_json_body(self):
        """Read and parse JSON request body."""
        content_length = int(self.headers.get('Content-Length', 0))
        if content_length == 0:
            return {}
        body = self.rfile.read(content_length)
        try:
            return json.loads(body.decode('utf-8'))
        except (json.JSONDecodeError, UnicodeDecodeError):
            return {}

    def get_query_params(self):
        """Parse query string parameters."""
        parsed = urllib.parse.urlparse(self.path)
        return dict(urllib.parse.parse_qsl(parsed.query))

    # โ”€โ”€ Routing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def do_GET(self):
        """Handle GET requests."""
        path = urllib.parse.urlparse(self.path).path

        # API Routes
        if path.startswith('/api/v1/mat/') or path.startswith('/api/'):
            if path.startswith('/api/') and not path.startswith('/api/v1/mat/'):
                path = '/api/v1/mat' + path[4:]
            self.route_api_get(path)
            return

        # Police Station Finder route
        if path == '/police-stations' or path == '/finder':
            self.serve_file('Police_Station_Finder.html')
            return

        # Redirect /mat_complaints to /
        if path == '/complaints':
            self.send_response(302)
            self.send_header('Location', '/')
            self.end_headers()
            return

        # Serve app / mat_complaints
        if path == '/complaints/' or path == '/complaints/app':
            user = self.get_current_user()
            if not user:
                self.serve_file('complaints/login.html')
            else:
                self.serve_file('complaints/app.html')
            return

        if path == '/complaints/login' or path == '/login':
            user = self.get_current_user()
            if user:
                self.send_response(302)
                self.send_header('Location', '/')
                self.end_headers()
                return
            self.serve_file('complaints/login.html')
            return

        # Serve static files from mat_complaints directory
        if path.startswith('/complaints/'):
            file_path = path[1:]  # Remove leading /
            self.serve_file(file_path)
            return

        # Root โ€” serve Login if unauthenticated, App (Dashboard) if authenticated
        if path == '/' or path == '':
            user = self.get_current_user()
            if not user:
                self.serve_file('complaints/login.html')
            else:
                self.serve_file('complaints/app.html')
            return

        # Default: serve static files
        super().do_GET()

    def do_POST(self):
        """Handle POST requests."""
        path = urllib.parse.urlparse(self.path).path
        if path.startswith('/api/v1/mat/') or path.startswith('/api/'):
            if path.startswith('/api/') and not path.startswith('/api/v1/mat/'):
                path = '/api/v1/mat' + path[4:]
            if path != '/api/v1/mat/login' and not self.validate_csrf():
                self.send_json({'error': 'ุทู„ุจ ุบูŠุฑ ุตุงู„ุญ (CSRF)'}, 403)
                return
            self.route_api_post(path)
        else:
            self.send_json({'error': 'ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)

    def do_PUT(self):
        """Handle PUT requests."""
        path = urllib.parse.urlparse(self.path).path
        if path.startswith('/api/v1/mat/') or path.startswith('/api/'):
            if path.startswith('/api/') and not path.startswith('/api/v1/mat/'):
                path = '/api/v1/mat' + path[4:]
            if not self.validate_csrf():
                self.send_json({'error': 'ุทู„ุจ ุบูŠุฑ ุตุงู„ุญ (CSRF)'}, 403)
                return
            self.route_api_put(path)
        else:
            self.send_json({'error': 'ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)

    def do_DELETE(self):
        """Handle DELETE requests."""
        path = urllib.parse.urlparse(self.path).path
        if path.startswith('/api/v1/mat/') or path.startswith('/api/'):
            if path.startswith('/api/') and not path.startswith('/api/v1/mat/'):
                path = '/api/v1/mat' + path[4:]
            if not self.validate_csrf():
                self.send_json({'error': 'ุทู„ุจ ุบูŠุฑ ุตุงู„ุญ (CSRF)'}, 403)
                return
            self.route_api_delete(path)
        else:
            self.send_json({'error': 'ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)

    def serve_file(self, filepath):
        """Serve a specific file."""
        full_path = os.path.join(BASE_DIR, filepath)
        if os.path.isfile(full_path):
            mime_type, _ = mimetypes.guess_type(full_path)
            if mime_type is None:
                mime_type = 'application/octet-stream'
            self.send_response(200)
            self.send_header('Content-Type', mime_type)
            self.send_header('Cache-Control', 'no-cache')
            self.end_headers()
            with open(full_path, 'rb') as f:
                self.wfile.write(f.read())
        else:
            self.send_response(404)
            self.send_header('Content-Type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(b'<h1>404 - File Not Found</h1>')

    # โ”€โ”€ API GET Routes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def route_api_get(self, path):
        routes = [
            (r'^/api/v1/mat/me$', self.api_get_me),
            (r'^/api/v1/mat/dashboard$', self.api_get_dashboard),
            (r'^/api/v1/mat/simple-dashboard$', self.api_get_simple_dashboard),
            (r'^/api/v1/mat/complaints$', self.api_get_complaints),
            (r'^/api/v1/mat/complaints/(\d+)$', self.api_get_complaint),
            (r'^/api/v1/mat/appointments$', self.api_get_appointments),
            (r'^/api/v1/mat/simple-appointments$', self.api_get_simple_appointments),
            (r'^/api/v1/mat/simple-appointments/(\d+)$', self.api_get_simple_appointment_detail),
            (r'^/api/v1/mat/appointments/today$', self.api_get_today_appointments),
            (r'^/api/v1/mat/areas$', self.api_get_areas),
            (r'^/api/v1/mat/search$', self.api_search),
            (r'^/api/v1/mat/mat_officers$', self.api_get_officers),
            (r'^/api/v1/mat/officers$', self.api_get_officers),
            (r'^/api/v1/mat/active-users$', self.api_get_active_users),
            (r'^/api/v1/mat/pending-calls$', self.api_get_pending_calls),
            (r'^/api/v1/mat/chat/online_users$', self.api_chat_online_users),
            (r'^/api/v1/mat/chat/messages$', self.api_chat_messages),
            (r'^/api/v1/mat/chat/poll$', self.api_chat_poll),
            (r'^/api/v1/mat/chat/archives$', self.api_chat_archives),
            (r'^/api/v1/mat/reservations$', self.api_get_reservations),
            (r'^/api/v1/mat/reservations/search$', self.api_search_reservations),
            (r'^/api/v1/mat/reservations/pending$', self.api_get_pending_transfers),
            (r'^/api/v1/mat/reservations/history/(\d+)$', self.api_get_custody_history),
        ]
        self._match_route(path, routes)

    def route_api_post(self, path):
        routes = [
            (r'^/api/v1/mat/login$', self.api_login),
            (r'^/api/v1/mat/logout$', self.api_logout),
            (r'^/api/v1/mat/complaints$', self.api_create_complaint),
            (r'^/api/v1/mat/parties$', self.api_create_party),
            (r'^/api/v1/mat/appointments$', self.api_create_appointment),
            (r'^/api/v1/mat/simple-appointments$', self.api_create_simple_appointment),
            (r'^/api/v1/mat/log-search$', self.api_log_search),
            (r'^/api/v1/mat/mat_officers$', self.api_create_officer),
            (r'^/api/v1/mat/officers$', self.api_create_officer),
            (r'^/api/v1/mat/change-password$', self.api_change_password),
            (r'^/api/v1/mat/chat/message$', self.api_chat_post_message),
            (r'^/api/v1/mat/reservations$', self.api_create_reservation),
            (r'^/api/v1/mat/reservations/transfer$', self.api_transfer_reservation),
            (r'^/api/v1/mat/reservations/respond$', self.api_respond_transfer),
        ]
        self._match_route(path, routes)

    def route_api_put(self, path):
        routes = [
            (r'^/api/v1/mat/complaints/(\d+)$', self.api_update_complaint),
            (r'^/api/v1/mat/parties/(\d+)$', self.api_update_party),
            (r'^/api/v1/mat/appointments/(\d+)$', self.api_update_appointment),
            (r'^/api/v1/mat/simple-appointments/(\d+)$', self.api_update_simple_appointment),
            (r'^/api/v1/mat/calls/(\d+)$', self.api_update_call_status),
            (r'^/api/v1/mat/mat_officers/(\d+)$', self.api_update_officer),
            (r'^/api/v1/mat/officers/(\d+)$', self.api_update_officer),
            (r'^/api/v1/mat/attendance/(\d+)$', self.api_update_attendance),
        ]
        self._match_route(path, routes)

    def route_api_delete(self, path):
        routes = [
            (r'^/api/v1/mat/complaints/(\d+)$', self.api_delete_complaint),
            (r'^/api/v1/mat/parties/(\d+)$', self.api_delete_party),
            (r'^/api/v1/mat/appointments/(\d+)$', self.api_delete_appointment),
            (r'^/api/v1/mat/simple-appointments/(\d+)$', self.api_delete_simple_appointment),
            (r'^/api/v1/mat/reservations/(\d+)$', self.api_delete_reservation),
        ]
        self._match_route(path, routes)

    def _match_route(self, path, routes):
        for pattern, handler in routes:
            match = re.match(pattern, path)
            if match:
                try:
                    handler(*match.groups())
                except Exception as e:
                    print(f"โŒ Error in {path}: {e}")
                    self.send_json({'error': 'ุฎุทุฃ ุฏุงุฎู„ูŠ ููŠ ุงู„ุฎุงุฏู…'}, 500)
                return
        self.send_json({'error': 'ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)

    def api_get_areas(self):
        """Serve the decoupled map data directly from file."""
        path = os.path.join(BASE_DIR, 'data', 'amman_areas.json')
        if not os.path.exists(path):
            self.send_json({'error': 'ุจูŠุงู†ุงุช ุงู„ู…ู†ุงุทู‚ ุบูŠุฑ ู…ุชูˆูุฑุฉ'}, 404)
            return
        self.send_response(200)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Cache-Control', 'public, max-age=86400')
        self.end_headers()
        with open(path, 'rb') as f:
            self.wfile.write(f.read())

    # โ”€โ”€ AUTH API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_login(self):
        data = self.read_json_body()
        username = data.get('username', '').strip()
        secret_code = data.get('secret_code', '').strip()

        if not username:
            self.send_json({'error': 'ูŠุฑุฌู‰ ุงุฎุชูŠุงุฑ ุงู„ู…ุณุชุฎุฏู…'}, 400)
            return

        conn = get_db()
        user = dict_from_row(conn.execute(
            "SELECT * FROM mat_officers WHERE username = ? AND is_active = 1", (username,)
        ).fetchone())
        conn.close()

        if not user:
            self.send_json({'error': 'ุงู„ู…ุณุชุฎุฏู… ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 401)
            return

        is_admin_mode = False
        if secret_code:
            try:
                digits = [int(d) for d in secret_code if d.isdigit()]
                if digits and sum(digits) == 14:
                    is_admin_mode = True
            except:
                pass

        effective_role = 'admin' if is_admin_mode else user['role']
        effective_tools = 'mat_complaints,finder,file_reservations,calls,mat_appointments,admin_permissions' if is_admin_mode else user.get('accessible_tools', 'mat_complaints,finder')

        token = create_session(user['id'], user['username'], effective_role, user['name'], effective_tools)
        csrf_token_val = os.urandom(32).hex()
        cookie1 = f"session={token}; Path=/; HttpOnly; SameSite=Strict"
        cookie2 = f"csrf_token={csrf_token_val}; Path=/; SameSite=Strict"

        self.send_json({
            'success': True,
            'user': {
                'id': user['id'],
                'name': user['name'],
                'username': user['username'],
                'role': effective_role,
                'accessible_tools': effective_tools.split(',')
            },
            'admin_mode': is_admin_mode
        }, 200, [cookie1, cookie2])

    def api_logout(self):
        cookie_header = self.headers.get('Cookie', '')
        cookie = SimpleCookie()
        try:
            cookie.load(cookie_header)
        except Exception:
            pass
        session_morsel = cookie.get('session')
        if session_morsel:
            delete_session(session_morsel.value)

        expire_cookie = "session=; Path=/; HttpOnly; Max-Age=0"
        self.send_json({'success': True}, 200, expire_cookie)

    def api_get_me(self):
        user = self.require_auth()
        if not user:
            return

        self.send_json({
            'id': user['user_id'],
            'username': user['username'],
            'name': user['name'],
            'role': user['role'],
            'accessible_tools': user.get('accessible_tools', 'mat_complaints,finder').split(',') if isinstance(user.get('accessible_tools'), str) else user.get('accessible_tools', ['mat_complaints', 'finder'])
        })

    def api_change_password(self):
        user = self.require_auth()
        if not user:
            return
        data = self.read_json_body()
        old_pw = data.get('old_password', '')
        new_pw = data.get('new_password', '')

        if not old_pw or not new_pw or len(new_pw) < 4:
            self.send_json({'error': 'ูƒู„ู…ุฉ ุงู„ู…ุฑูˆุฑ ุงู„ุฌุฏูŠุฏุฉ ูŠุฌุจ ุฃู† ุชูƒูˆู† ูค ุฃุญุฑู ุนู„ู‰ ุงู„ุฃู‚ู„'}, 400)
            return

        conn = get_db()
        officer = dict_from_row(conn.execute("SELECT * FROM mat_officers WHERE id = ?", (user['user_id'],)).fetchone())

        is_valid_old = False
        if officer:
            if officer['password_hash'].startswith('pbkdf2:'):
                actual_hash = officer['password_hash'].split(':', 1)[1]
                check_hash = hashlib.pbkdf2_hmac('sha256', old_pw.encode(), officer['salt'].encode(), 100000).hex()
                is_valid_old = (check_hash == actual_hash)
            else:
                is_valid_old = (hashlib.sha256((old_pw + officer['salt']).encode()).hexdigest() == officer['password_hash'])

        if not is_valid_old:
            conn.close()
            self.send_json({'error': 'ูƒู„ู…ุฉ ุงู„ู…ุฑูˆุฑ ุงู„ุญุงู„ูŠุฉ ุบูŠุฑ ุตุญูŠุญุฉ'}, 400)
            return

        new_salt = uuid.uuid4().hex
        new_hash = 'pbkdf2:' + hashlib.pbkdf2_hmac('sha256', new_pw.encode(), new_salt.encode(), 100000).hex()
        conn.execute("UPDATE mat_officers SET password_hash=?, salt=?, updated_at=datetime('now','localtime') WHERE id=?",
                     (new_hash, new_salt, user['user_id']))
        conn.commit()
        conn.close()
        self.send_json({'success': True, 'message': 'ุชู… ุชุบูŠูŠุฑ ูƒู„ู…ุฉ ุงู„ู…ุฑูˆุฑ ุจู†ุฌุงุญ'})

    # โ”€โ”€ CHAT API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_chat_online_users(self):
        user = self.require_auth()
        if not user:
            return
        
        params = self.get_query_params()
        if (params.get('active', '0') == '1' or params.get('chat_active', '0') == '1') and user.get('token'):
            touch_chat_session(user['token'])

        conn = get_db()
        # Query active users in meeting room (last_chat_seen within last 5 minutes)
        active_sessions = rows_to_list(conn.execute('''

            SELECT DISTINCT user_id, name, role

            FROM mat_sessions

            WHERE last_chat_seen IS NOT NULL AND last_chat_seen >= datetime('now', 'localtime', '-5 minutes')

        ''').fetchall())
        conn.close()
        
        online_users = []
        user_ids = set()
        for s in active_sessions:
            if s['user_id'] not in user_ids:
                user_ids.add(s['user_id'])
                online_users.append({
                    'id': s['user_id'],
                    'name': s['name'],
                    'role': s['role']
                })
            
        self.send_json({'online_users': online_users})

    def api_chat_messages(self):
        user = self.require_auth()
        if not user:
            return

        params = self.get_query_params()
        date_filter = params.get('date', datetime.now().strftime('%Y-%m-%d'))

        if date_filter == 'archives':
            conn = get_db()
            archives = rows_to_list(conn.execute('''

                SELECT DATE(created_at) as archive_date, COUNT(*) as msg_count

                FROM mat_chat_messages

                WHERE DATE(created_at) < DATE('now', 'localtime')

                GROUP BY DATE(created_at)

                ORDER BY archive_date DESC

            ''').fetchall())
            conn.close()
            self.send_json({'archives': archives})
            return

        conn = get_db()
        messages = rows_to_list(conn.execute('''

            SELECT m.id, m.message, m.created_at, o.name as user_name, o.role as user_role

            FROM mat_chat_messages m

            JOIN mat_officers o ON m.user_id = o.id

            WHERE DATE(m.created_at) = ?

            ORDER BY m.id DESC LIMIT 100

        ''', (date_filter,)).fetchall())
        conn.close()

        messages.reverse()
        self.send_json({'messages': messages, 'date': date_filter})

    def api_chat_post_message(self):
        user = self.require_auth()
        if not user:
            return
        
        if user.get('token'):
            touch_chat_session(user['token'])

        data = self.read_json_body()
        message = data.get('message', '').strip()
        if not message:
            self.send_json({'error': 'ุฑุณุงู„ุฉ ูุงุฑุบุฉ'}, 400)
            return
            
        conn = get_db()
        conn.execute("INSERT INTO mat_chat_messages (user_id, message) VALUES (?, ?)", (user['user_id'], message))
        conn.commit()
        conn.close()
        
        global chat_event
        chat_event.set()
        chat_event.clear()
        
        self.send_json({'success': True})

    def api_chat_poll(self):
        user = self.require_auth()
        if not user:
            return
        
        if user.get('token'):
            touch_chat_session(user['token'])

        params = self.get_query_params()
        last_id = int(params.get('last_id', 0))
        
        conn = get_db()
        new_msgs = rows_to_list(conn.execute('''

            SELECT m.id, m.message, m.created_at, o.name as user_name, o.role as user_role

            FROM mat_chat_messages m

            JOIN mat_officers o ON m.user_id = o.id

            WHERE m.id > ? AND DATE(m.created_at) = DATE('now', 'localtime')

            ORDER BY m.id ASC LIMIT 50

        ''', (last_id,)).fetchall())
        conn.close()
        
        if not new_msgs:
            global chat_event
            chat_event.wait(timeout=20)
            
            conn = get_db()
            new_msgs = rows_to_list(conn.execute('''

                SELECT m.id, m.message, m.created_at, o.name as user_name, o.role as user_role

                FROM mat_chat_messages m

                JOIN mat_officers o ON m.user_id = o.id

                WHERE m.id > ? AND DATE(m.created_at) = DATE('now', 'localtime')

                ORDER BY m.id ASC LIMIT 50

            ''', (last_id,)).fetchall())
            conn.close()
            
        self.send_json({'messages': new_msgs})

    def api_chat_archives(self):
        user = self.require_auth()
        if not user:
            return
            
        conn = get_db()
        archives = rows_to_list(conn.execute('''

            SELECT DATE(created_at) as archive_date, COUNT(*) as msg_count

            FROM mat_chat_messages

            WHERE DATE(created_at) < DATE('now', 'localtime')

            GROUP BY DATE(created_at)

            ORDER BY archive_date DESC

        ''').fetchall())
        conn.close()
        
        self.send_json({'archives': archives})

    # โ”€โ”€ DASHBOARD API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_dashboard(self):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        today = datetime.now().strftime('%Y-%m-%d')

        stats = {
            'total_complaints': conn.execute("SELECT COUNT(*) as c FROM mat_complaints").fetchone()['c'],
            'new_complaints': conn.execute("SELECT COUNT(*) as c FROM mat_complaints WHERE status='ุฌุฏูŠุฏ'").fetchone()['c'],
            'scheduled_complaints': conn.execute("SELECT COUNT(*) as c FROM mat_complaints WHERE status='ู…ูุฌุฏูˆู„'").fetchone()['c'],
            'completed_complaints': conn.execute("SELECT COUNT(*) as c FROM mat_complaints WHERE status='ู…ูƒุชู…ู„'").fetchone()['c'],
            'today_appointments': conn.execute(
                "SELECT COUNT(*) as c FROM mat_appointments WHERE appointment_date=?", (today,)
            ).fetchone()['c'],
            'pending_calls': conn.execute(
                "SELECT COUNT(*) as c FROM mat_appointment_parties WHERE call_status='ู„ู…_ูŠูุชุตู„'"
            ).fetchone()['c'],
        }

        # Today's mat_appointments with details
        today_appts = rows_to_list(conn.execute('''

            SELECT a.*, c.complaint_number, c.subject,

                   GROUP_CONCAT(p.name || ' (' || p.party_type || ')', ' ุŒ ') as party_names

            FROM mat_appointments a

            JOIN mat_complaints c ON a.complaint_id = c.id

            LEFT JOIN mat_appointment_parties ap ON a.id = ap.appointment_id

            LEFT JOIN mat_parties p ON ap.party_id = p.id

            WHERE a.appointment_date = ?

            GROUP BY a.id

            ORDER BY a.appointment_time

        ''', (today,)).fetchall())

        # Recent mat_complaints
        recent = rows_to_list(conn.execute('''

            SELECT c.*, o.name as officer_name

            FROM mat_complaints c

            LEFT JOIN mat_officers o ON c.assigned_officer_id = o.id

            ORDER BY c.created_at DESC LIMIT 10

        ''').fetchall())

        conn.close()
        self.send_json({
            'stats': stats,
            'today_appointments': today_appts,
            'recent_complaints': recent
        })

    # โ”€โ”€ COMPLAINTS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_complaints(self):
        user = self.require_auth()
        if not user:
            return

        params = self.get_query_params()
        status = params.get('status', '')
        page = int(params.get('page', 1))
        limit = int(params.get('limit', 50))
        offset = (page - 1) * limit

        conn = get_db()
        where_clauses = []
        query_params = []

        if status:
            where_clauses.append("c.status = ?")
            query_params.append(status)

        if user['role'] == 'officer':
            where_clauses.append("c.assigned_officer_id = ?")
            query_params.append(user['user_id'])

        where_sql = "WHERE " + " AND ".join(where_clauses) if where_clauses else ""

        mat_complaints = rows_to_list(conn.execute(f'''

            SELECT c.*, o.name as officer_name, cb.name as created_by_name,

                   (SELECT COUNT(*) FROM mat_parties WHERE complaint_id = c.id) as party_count,

                   (SELECT COUNT(*) FROM mat_appointments WHERE complaint_id = c.id) as appointment_count

            FROM mat_complaints c

            LEFT JOIN mat_officers o ON c.assigned_officer_id = o.id

            LEFT JOIN mat_officers cb ON c.created_by_id = cb.id

            {where_sql}

            ORDER BY c.created_at DESC

            LIMIT ? OFFSET ?

        ''', query_params + [limit, offset]).fetchall())

        total = conn.execute(f"SELECT COUNT(*) as c FROM mat_complaints c {where_sql}", query_params).fetchone()['c']
        conn.close()

        self.send_json({'mat_complaints': mat_complaints, 'total': total, 'page': page, 'limit': limit})

    def api_get_complaint(self, complaint_id):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        complaint = dict_from_row(conn.execute('''

            SELECT c.*, o.name as officer_name, cb.name as created_by_name

            FROM mat_complaints c

            LEFT JOIN mat_officers o ON c.assigned_officer_id = o.id

            LEFT JOIN mat_officers cb ON c.created_by_id = cb.id

            WHERE c.id = ?

        ''', (complaint_id,)).fetchone())

        if not complaint:
            conn.close()
            self.send_json({'error': 'ุงู„ุดูƒูˆู‰ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ'}, 404)
            return

        mat_parties = rows_to_list(conn.execute(
            "SELECT * FROM mat_parties WHERE complaint_id = ? ORDER BY party_type", (complaint_id,)
        ).fetchall())

        mat_appointments = rows_to_list(conn.execute('''

            SELECT a.*, cb.name as created_by_name, req.name as requested_by_name

            FROM mat_appointments a

            LEFT JOIN mat_officers cb ON a.created_by_id = cb.id

            LEFT JOIN mat_officers req ON a.requested_by_id = req.id

            WHERE a.complaint_id = ?

            ORDER BY a.appointment_date DESC, a.appointment_time DESC

        ''', (complaint_id,)).fetchall())

        # Get appointment mat_parties for each appointment
        for appt in mat_appointments:
            appt['mat_parties'] = rows_to_list(conn.execute('''

                SELECT ap.*, p.name as party_name, p.phone as party_phone, p.party_type,

                       cb.name as caller_name

                FROM mat_appointment_parties ap

                JOIN mat_parties p ON ap.party_id = p.id

                LEFT JOIN mat_officers cb ON ap.called_by_id = cb.id

                WHERE ap.appointment_id = ?

            ''', (appt['id'],)).fetchall())

        conn.close()
        self.send_json({
            'complaint': complaint,
            'mat_parties': mat_parties,
            'mat_appointments': mat_appointments
        })

    def api_create_complaint(self):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        data = self.read_json_body()
        subject = data.get('subject', '').strip()

        if not subject:
            self.send_json({'error': 'ู…ูˆุถูˆุน ุงู„ุดูƒูˆู‰ ู…ุทู„ูˆุจ'}, 400)
            return

        conn = get_db()

        # Auto-generate complaint number
        count = conn.execute("SELECT COUNT(*) as c FROM mat_complaints").fetchone()['c']
        complaint_number = data.get('complaint_number', '').strip()
        if not complaint_number:
            complaint_number = f"SH-{datetime.now().strftime('%Y%m%d')}-{count + 1:04d}"

        c = conn.execute('''

            INSERT INTO mat_complaints (complaint_number, subject, complaint_type, notes, assigned_officer_id, created_by_id)

            VALUES (?, ?, ?, ?, ?, ?)

        ''', (
            complaint_number, subject,
            data.get('complaint_type', 'ุนุงู…'),
            data.get('notes', ''),
            data.get('assigned_officer_id'),
            user['user_id']
        ))

        complaint_id = c.lastrowid

        # Add mat_parties if provided
        parties_data = data.get('mat_parties', [])
        for party in parties_data:
            if party.get('name', '').strip():
                conn.execute('''

                    INSERT INTO mat_parties (complaint_id, party_type, name, phone, national_id, address, notes)

                    VALUES (?, ?, ?, ?, ?, ?, ?)

                ''', (
                    complaint_id, party.get('party_type', 'ุดุงูƒูŠ'),
                    party['name'].strip(), party.get('phone', '').strip(),
                    party.get('national_id', '').strip(), party.get('address', '').strip(),
                    party.get('notes', '')
                ))

        log_activity(conn, user['user_id'], 'ุฅู†ุดุงุก ุดูƒูˆู‰', 'complaint', complaint_id, subject)
        conn.commit()
        conn.close()

        self.send_json({'success': True, 'id': complaint_id, 'complaint_number': complaint_number}, 201)

    def api_update_complaint(self, complaint_id):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        data = self.read_json_body()
        conn = get_db()

        existing = conn.execute("SELECT id FROM mat_complaints WHERE id=?", (complaint_id,)).fetchone()
        if not existing:
            conn.close()
            self.send_json({'error': 'ุงู„ุดูƒูˆู‰ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ'}, 404)
            return

        fields = []
        values = []
        for key in ['subject', 'complaint_number', 'complaint_type', 'status', 'priority', 'notes', 'assigned_officer_id']:
            if key in data:
                fields.append(f"{key} = ?")
                values.append(data[key])

        if fields:
            fields.append("updated_at = datetime('now', 'localtime')")
            values.append(complaint_id)
            conn.execute(f"UPDATE mat_complaints SET {', '.join(fields)} WHERE id = ?", values)
            log_activity(conn, user['user_id'], 'ุชุนุฏูŠู„ ุดูƒูˆู‰', 'complaint', int(complaint_id), json.dumps(data, ensure_ascii=False))
            conn.commit()

        conn.close()
        self.send_json({'success': True})

    def api_delete_complaint(self, complaint_id):
        user = self.require_role('admin')
        if not user:
            return

        conn = get_db()
        conn.execute("DELETE FROM mat_complaints WHERE id = ?", (complaint_id,))
        log_activity(conn, user['user_id'], 'ุญุฐู ุดูƒูˆู‰', 'complaint', int(complaint_id))
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    # โ”€โ”€ PARTIES API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_create_party(self):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        data = self.read_json_body()
        complaint_id = data.get('complaint_id')
        name = data.get('name', '').strip()
        party_type = data.get('party_type', 'ุดุงูƒูŠ')

        if not complaint_id or not name:
            self.send_json({'error': 'ุจูŠุงู†ุงุช ู†ุงู‚ุตุฉ'}, 400)
            return

        conn = get_db()
        c = conn.execute('''

            INSERT INTO mat_parties (complaint_id, party_type, name, phone, national_id, address, notes)

            VALUES (?, ?, ?, ?, ?, ?, ?)

        ''', (complaint_id, party_type, name, data.get('phone', '').strip(),
              data.get('national_id', '').strip(), data.get('address', '').strip(), data.get('notes', '')))

        party_id = c.lastrowid
        log_activity(conn, user['user_id'], 'ุฅุถุงูุฉ ุทุฑู', 'party', party_id, f"{party_type}: {name}")
        conn.commit()
        conn.close()
        self.send_json({'success': True, 'id': party_id}, 201)

    def api_update_party(self, party_id):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        data = self.read_json_body()
        conn = get_db()
        fields, values = [], []
        for key in ['name', 'phone', 'national_id', 'address', 'notes', 'party_type']:
            if key in data:
                fields.append(f"{key} = ?")
                values.append(data[key])
        if fields:
            values.append(party_id)
            conn.execute(f"UPDATE mat_parties SET {', '.join(fields)} WHERE id = ?", values)
            conn.commit()
        conn.close()
        self.send_json({'success': True})

    def api_delete_party(self, party_id):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        conn = get_db()
        conn.execute("DELETE FROM mat_parties WHERE id = ?", (party_id,))
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    # โ”€โ”€ APPOINTMENTS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_appointments(self):
        user = self.require_auth()
        if not user:
            return

        params = self.get_query_params()
        date_from = params.get('from', datetime.now().strftime('%Y-%m-%d'))
        date_to = params.get('to', '')

        conn = get_db()
        if date_to:
            mat_appointments = rows_to_list(conn.execute('''

                SELECT a.*, c.complaint_number, c.subject,

                       GROUP_CONCAT(p.name || ' (' || p.party_type || ')', ' ุŒ ') as party_names

                FROM mat_appointments a

                JOIN mat_complaints c ON a.complaint_id = c.id

                LEFT JOIN mat_appointment_parties ap ON a.id = ap.appointment_id

                LEFT JOIN mat_parties p ON ap.party_id = p.id

                WHERE a.appointment_date BETWEEN ? AND ?

                GROUP BY a.id

                ORDER BY a.appointment_date, a.appointment_time

            ''', (date_from, date_to)).fetchall())
        else:
            mat_appointments = rows_to_list(conn.execute('''

                SELECT a.*, c.complaint_number, c.subject,

                       GROUP_CONCAT(p.name || ' (' || p.party_type || ')', ' ุŒ ') as party_names

                FROM mat_appointments a

                JOIN mat_complaints c ON a.complaint_id = c.id

                LEFT JOIN mat_appointment_parties ap ON a.id = ap.appointment_id

                LEFT JOIN mat_parties p ON ap.party_id = p.id

                WHERE a.appointment_date >= ?

                GROUP BY a.id

                ORDER BY a.appointment_date, a.appointment_time

            ''', (date_from,)).fetchall())

        conn.close()
        self.send_json({'mat_appointments': mat_appointments})

    def api_get_today_appointments(self):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        today = datetime.now().strftime('%Y-%m-%d')

        mat_appointments = rows_to_list(conn.execute('''

            SELECT a.*, c.complaint_number, c.subject, 

                   req.name as requested_by_name,

                   cb.name as created_by_name

            FROM mat_appointments a

            JOIN mat_complaints c ON a.complaint_id = c.id

            LEFT JOIN mat_officers req ON a.requested_by_id = req.id

            LEFT JOIN mat_officers cb ON a.created_by_id = cb.id

            WHERE a.appointment_date = ?

            ORDER BY a.appointment_time

        ''', (today,)).fetchall())

        for appt in mat_appointments:
            appt['mat_parties'] = rows_to_list(conn.execute('''

                SELECT ap.*, p.name as party_name, p.phone as party_phone, p.party_type

                FROM mat_appointment_parties ap

                JOIN mat_parties p ON ap.party_id = p.id

                WHERE ap.appointment_id = ?

            ''', (appt['id'],)).fetchall())
            
            # Fetch previous mat_appointments if branched
            if appt.get('parent_appointment_id'):
                parent = dict_from_row(conn.execute('''

                    SELECT a.appointment_date, a.appointment_time, a.status, a.notes 

                    FROM mat_appointments a WHERE a.id = ?

                ''', (appt['parent_appointment_id'],)).fetchone())
                appt['parent_info'] = parent

        conn.close()
        self.send_json({'mat_appointments': mat_appointments, 'date': today})

    def api_create_appointment(self):
        user = self.require_role('admin', 'officer', 'caller')
        if not user:
            return

        data = self.read_json_body()
        complaint_id = data.get('complaint_id')
        appt_date = data.get('appointment_date', '').strip()
        appt_time = data.get('appointment_time', '').strip()

        if not complaint_id or not appt_date or not appt_time:
            self.send_json({'error': 'ุจูŠุงู†ุงุช ู†ุงู‚ุตุฉ (ุงู„ุดูƒูˆู‰ุŒ ุงู„ุชุงุฑูŠุฎุŒ ุงู„ูˆู‚ุช)'}, 400)
            return

        conn = get_db()

        c = conn.execute('''

            INSERT INTO mat_appointments (complaint_id, appointment_date, appointment_time,

                                      appointment_type, location, notes, requested_by_id, parent_appointment_id, created_by_id)

            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

        ''', (complaint_id, appt_date, appt_time,
              data.get('appointment_type', 'ูุฑุฏูŠ'),
              data.get('location', 'ู…ูƒุชุจ ู‚ุณู… ุงู„ุดูƒุงูˆูŠ'),
              data.get('notes', ''), 
              data.get('requested_by_id'),
              data.get('parent_appointment_id'),
              user['user_id']))

        appt_id = c.lastrowid

        # Link mat_parties to appointment
        party_ids = data.get('party_ids', [])
        if not party_ids:
            # If no specific mat_parties, add all mat_parties of the complaint
            mat_parties = conn.execute("SELECT id FROM mat_parties WHERE complaint_id = ?", (complaint_id,)).fetchall()
            party_ids = [p['id'] for p in mat_parties]

        for pid in party_ids:
            conn.execute(
                "INSERT OR IGNORE INTO mat_appointment_parties (appointment_id, party_id) VALUES (?, ?)",
                (appt_id, pid)
            )

        # Update complaint status
        conn.execute("UPDATE mat_complaints SET status='ู…ูุฌุฏูˆู„', updated_at=datetime('now','localtime') WHERE id=?",
                     (complaint_id,))

        log_activity(conn, user['user_id'], 'ุฅู†ุดุงุก ู…ูˆุนุฏ', 'appointment', appt_id,
                     f"ุชุงุฑูŠุฎ: {appt_date} ุงู„ุณุงุนุฉ {appt_time}")
        conn.commit()
        conn.close()

        self.send_json({'success': True, 'id': appt_id}, 201)

    def api_update_appointment(self, appt_id):
        user = self.require_role('admin', 'officer', 'caller')
        if not user:
            return

        data = self.read_json_body()
        conn = get_db()
        fields, values = [], []
        for key in ['appointment_date', 'appointment_time', 'appointment_type', 'status', 'location', 'notes']:
            if key in data:
                fields.append(f"{key} = ?")
                values.append(data[key])
        if fields:
            values.append(appt_id)
            conn.execute(f"UPDATE mat_appointments SET {', '.join(fields)} WHERE id = ?", values)
            conn.commit()
        conn.close()
        self.send_json({'success': True})

    def api_delete_appointment(self, appt_id):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        conn = get_db()
        conn.execute("DELETE FROM mat_appointments WHERE id = ?", (appt_id,))
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    # โ”€โ”€ CALLS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_pending_calls(self):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        pending = rows_to_list(conn.execute('''

            SELECT ap.id, ap.call_status, ap.notes as call_notes,

                   p.name as party_name, p.phone as party_phone, p.party_type,

                   a.appointment_date, a.appointment_time, a.appointment_type,

                   c.complaint_number, c.subject, c.id as complaint_id,

                   a.id as appointment_id

            FROM mat_appointment_parties ap

            JOIN mat_parties p ON ap.party_id = p.id

            JOIN mat_appointments a ON ap.appointment_id = a.id

            JOIN mat_complaints c ON a.complaint_id = c.id

            WHERE ap.call_status IN ('ู„ู…_ูŠูุชุตู„', 'ู„ู…_ูŠุฑุฏ')

            AND a.status != 'ู…ู„ุบู‰'

            ORDER BY a.appointment_date, a.appointment_time

        ''').fetchall())

        conn.close()
        self.send_json({'pending_calls': pending})

    def api_update_call_status(self, ap_id):
        user = self.require_role('admin', 'officer', 'caller')
        if not user:
            return

        data = self.read_json_body()
        call_status = data.get('call_status', '')

        if call_status not in ('ู„ู…_ูŠูุชุตู„', 'ุชู…_ุงู„ุงุชุตุงู„', 'ู„ู…_ูŠุฑุฏ', 'ู…ุคูƒุฏ', 'ุฑูุถ'):
            self.send_json({'error': 'ุญุงู„ุฉ ุบูŠุฑ ุตุงู„ุญุฉ'}, 400)
            return

        conn = get_db()
        conn.execute('''

            UPDATE mat_appointment_parties

            SET call_status = ?, called_at = datetime('now', 'localtime'), called_by_id = ?, notes = ?

            WHERE id = ?

        ''', (call_status, user['user_id'], data.get('notes', ''), ap_id))

        log_activity(conn, user['user_id'], 'ุชุญุฏูŠุซ ุญุงู„ุฉ ุงุชุตุงู„', 'appointment_party', int(ap_id), call_status)
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    def api_update_attendance(self, ap_id):
        user = self.require_role('admin', 'officer')
        if not user:
            return

        data = self.read_json_body()
        attendance = data.get('attendance', '')

        if attendance not in ('ู…ู†ุชุธุฑ', 'ุญุถุฑ', 'ู„ู…_ูŠุญุถุฑ'):
            self.send_json({'error': 'ุญุงู„ุฉ ุบูŠุฑ ุตุงู„ุญุฉ'}, 400)
            return

        conn = get_db()
        conn.execute("UPDATE mat_appointment_parties SET attendance = ? WHERE id = ?", (attendance, ap_id))
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    # โ”€โ”€ SEARCH API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_search(self):
        user = self.require_auth()
        if not user:
            return

        params = self.get_query_params()
        q = params.get('q', '').strip()

        if len(q) < 2:
            self.send_json({'error': 'ูŠุฑุฌู‰ ุฅุฏุฎุงู„ ุญุฑููŠู† ุนู„ู‰ ุงู„ุฃู‚ู„ ู„ู„ุจุญุซ'}, 400)
            return

        conn = get_db()
        search_term = f"%{q}%"

        # 1. Search simple mat_appointments
        simple_appts = rows_to_list(conn.execute('''

            SELECT sa.*, req.name as requested_by_name, cb.name as created_by_name

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers req ON sa.requested_by_id = req.id

            LEFT JOIN mat_officers cb ON sa.created_by_id = cb.id

            WHERE sa.case_number LIKE ? 

               OR sa.visitor_name LIKE ? 

               OR sa.phone LIKE ? 

               OR sa.national_id LIKE ? 

               OR sa.notes LIKE ? 

               OR sa.station_name LIKE ?

            ORDER BY sa.appointment_date DESC

            LIMIT 20

        ''', (search_term, search_term, search_term, search_term, search_term, search_term)).fetchall())

        # 2. Search mat_parties & mat_complaints
        results = rows_to_list(conn.execute('''

            SELECT p.*, c.id as complaint_id, c.complaint_number, c.subject, c.status as complaint_status,

                   c.created_at as complaint_date

            FROM mat_parties p

            JOIN mat_complaints c ON p.complaint_id = c.id

            WHERE p.name LIKE ? OR p.phone LIKE ? OR p.national_id LIKE ?

            ORDER BY c.created_at DESC

            LIMIT 20

        ''', (search_term, search_term, search_term)).fetchall())

        persons = {}
        for r in results:
            key = f"{r['name']}_{r['phone']}"
            if key not in persons:
                persons[key] = {
                    'name': r['name'],
                    'phone': r['phone'],
                    'national_id': r['national_id'],
                    'mat_complaints': []
                }
            appts = rows_to_list(conn.execute('''

                SELECT a.*, ap.call_status, ap.attendance,

                       ap.called_at, cb.name as caller_name

                FROM mat_appointment_parties ap

                JOIN mat_appointments a ON ap.appointment_id = a.id

                LEFT JOIN mat_officers cb ON ap.called_by_id = cb.id

                WHERE ap.party_id = ?

                ORDER BY a.appointment_date DESC

            ''', (r['id'],)).fetchall())

            persons[key]['mat_complaints'].append({
                'complaint_id': r['complaint_id'],
                'complaint_number': r['complaint_number'],
                'subject': r['subject'],
                'status': r['complaint_status'],
                'party_type': r['party_type'],
                'complaint_date': r['complaint_date'],
                'mat_appointments': appts
            })

        complaint_results = rows_to_list(conn.execute('''

            SELECT c.*, o.name as officer_name

            FROM mat_complaints c

            LEFT JOIN mat_officers o ON c.assigned_officer_id = o.id

            WHERE c.complaint_number LIKE ? OR c.subject LIKE ?

            ORDER BY c.created_at DESC

            LIMIT 20

        ''', (search_term, search_term)).fetchall())

        # 3. Search reserved files
        file_results = rows_to_list(conn.execute('''

            SELECT r.*, o.name as officer_name

            FROM mat_reserved_files r

            JOIN mat_officers o ON r.officer_id = o.id

            WHERE r.file_number LIKE ? OR r.notes LIKE ?

            ORDER BY r.reserved_at DESC

            LIMIT 20

        ''', (search_term, search_term)).fetchall())

        conn.close()

        # 4. Search Map Locations (from data/amman_areas.json)
        location_results = []
        try:
            areas_file = os.path.join(BASE_DIR, 'data', 'amman_areas.json')
            if os.path.exists(areas_file):
                with open(areas_file, 'r', encoding='utf-8') as f:
                    areas_data = json.load(f)
                    q_lower = q.lower()
                    for item in areas_data:
                        name = item.get('name', '')
                        closest = item.get('closest', '')
                        directorate = item.get('directorate', '')
                        liwa = item.get('liwa', '')
                        if (q_lower in name.lower() or 
                            q_lower in closest.lower() or 
                            q_lower in directorate.lower() or 
                            q_lower in liwa.lower()):
                            location_results.append(item)
                            if len(location_results) >= 15:
                                break
        except Exception as e:
            print(f"Error searching locations: {e}")

        self.send_json({
            'mat_simple_appointments': simple_appts,
            'persons': list(persons.values()),
            'mat_complaints': complaint_results,
            'files': file_results,
            'locations': location_results,
            'query': q
        })

    # โ”€โ”€ OFFICERS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_active_users(self):
        conn = get_db()
        users = rows_to_list(conn.execute(
            "SELECT id, name, username, role FROM mat_officers WHERE is_active = 1 ORDER BY id ASC"
        ).fetchall())
        conn.close()
        self.send_json({'users': users})

    def api_get_officers(self):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        mat_officers = rows_to_list(conn.execute(
            "SELECT id, name, username, role, accessible_tools, is_active, created_at FROM mat_officers ORDER BY role, name"
        ).fetchall())
        conn.close()
        self.send_json({'officers': mat_officers, 'mat_officers': mat_officers})

    def api_create_officer(self):
        user = self.require_auth()
        if not user:
            return

        data = self.read_json_body()
        name = data.get('name', '').strip()
        username = data.get('username', '').strip()
        password = data.get('password', '')
        role = data.get('role', 'officer')

        if not name or not username or not password:
            self.send_json({'error': 'ุฌู…ูŠุน ุงู„ุญู‚ูˆู„ ู…ุทู„ูˆุจุฉ'}, 400)
            return

        if role not in ('admin', 'officer', 'caller'):
            self.send_json({'error': 'ุฏูˆุฑ ุบูŠุฑ ุตุงู„ุญ'}, 400)
            return

        conn = get_db()
        existing = conn.execute("SELECT id FROM mat_officers WHERE username = ?", (username,)).fetchone()
        if existing:
            conn.close()
            self.send_json({'error': 'ุงุณู… ุงู„ู…ุณุชุฎุฏู… ู…ูˆุฌูˆุฏ ู…ุณุจู‚ุงู‹'}, 400)
            return

        salt = uuid.uuid4().hex
        pw_hash = 'pbkdf2:' + hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000).hex()
        c = conn.execute(
            "INSERT INTO mat_officers (name, username, password_hash, salt, role, accessible_tools) VALUES (?,?,?,?,?,?)",
            (name, username, pw_hash, salt, role, data.get('accessible_tools', 'mat_complaints,finder'))
        )
        log_activity(conn, user['user_id'], 'ุฅู†ุดุงุก ุญุณุงุจ', 'officer', c.lastrowid, f"{name} ({role})")
        conn.commit()
        conn.close()
        backup_db_to_json()
        self.send_json({'success': True, 'id': c.lastrowid}, 201)

    def api_update_officer(self, officer_id):
        user = self.require_auth()
        if not user:
            return

        data = self.read_json_body()
        conn = get_db()
        fields, values = [], []

        for key in ['name', 'role', 'is_active', 'accessible_tools']:
            if key in data:
                fields.append(f"{key} = ?")
                values.append(data[key])

        # Handle password reset
        if data.get('password'):
            salt = uuid.uuid4().hex
            pw_hash = 'pbkdf2:' + hashlib.pbkdf2_hmac('sha256', data['password'].encode(), salt.encode(), 100000).hex()
            fields.extend(['password_hash = ?', 'salt = ?'])
            values.extend([pw_hash, salt])

        if fields:
            fields.append("updated_at = datetime('now', 'localtime')")
            values.append(officer_id)
            conn.execute(f"UPDATE mat_officers SET {', '.join(fields)} WHERE id = ?", values)
            conn.commit()

        conn.close()
        backup_db_to_json()
        self.send_json({'success': True})

    # โ”€โ”€ SIMPLE APPOINTMENTS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_simple_dashboard(self):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        sync_postponed_appointments(conn)

        
        today = datetime.now().strftime('%Y-%m-%d')

        params = self.get_query_params()
        filter_type = params.get('filter', 'today')

        if filter_type == 'week':
            today_dt = datetime.now()
            days_since_sunday = (today_dt.weekday() + 1) % 7
            start_of_week = (today_dt - timedelta(days=days_since_sunday)).strftime('%Y-%m-%d')
            end_of_week = (today_dt + timedelta(days=(6 - days_since_sunday))).strftime('%Y-%m-%d')
            where_date = "appointment_date BETWEEN ? AND ?"
            date_args = (start_of_week, end_of_week)
        elif filter_type == 'month':
            current_month = datetime.now().strftime('%Y-%m')
            where_date = "appointment_date LIKE ?"
            date_args = (f"{current_month}%",)
        elif filter_type == 'all':
            where_date = "1=1"
            date_args = ()
        else:  # default: 'today'
            where_date = "appointment_date = ?"
            date_args = (today,)

        # Query stats based on selected filter
        sql_total = f"SELECT COUNT(*) as c FROM mat_simple_appointments WHERE {where_date}"
        sql_postponed = f"SELECT COUNT(*) as c FROM mat_simple_appointments WHERE status='ู…ูุคุฌู„' AND {where_date}"
        sql_noshow = f"SELECT COUNT(*) as c FROM mat_simple_appointments WHERE status='ู„ู… ูŠุญุถุฑ' AND {where_date}"
        sql_attended = f"SELECT COUNT(*) as c FROM mat_simple_appointments WHERE status='ุชู… ุงู„ุญุถูˆุฑ' AND {where_date}"
        sql_pending = f"SELECT COUNT(*) as c FROM mat_simple_appointments WHERE status='ู…ูุฌุฏูˆู„' AND {where_date}"

        stats = {
            'total_appointments': conn.execute("SELECT COUNT(*) as c FROM mat_simple_appointments").fetchone()['c'],
            'filtered_total': conn.execute(sql_total, date_args).fetchone()['c'],
            'filtered_postponed': conn.execute(sql_postponed, date_args).fetchone()['c'],
            'filtered_noshow': conn.execute(sql_noshow, date_args).fetchone()['c'],
            'filtered_attended': conn.execute(sql_attended, date_args).fetchone()['c'],
            'filtered_pending': conn.execute(sql_pending, date_args).fetchone()['c'],
            'filter_type': filter_type,
        }

        today_appts = rows_to_list(conn.execute('''

            SELECT sa.*, req.name as requested_by_name

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers req ON sa.requested_by_id = req.id

            WHERE sa.appointment_date = ?

            ORDER BY sa.appointment_time ASC

        ''', (today,)).fetchall())

        for appt in today_appts:
            if appt.get('parent_appointment_id'):
                parent = dict_from_row(conn.execute('''

                    SELECT appointment_date, appointment_time, status, notes 

                    FROM mat_simple_appointments WHERE id = ?

                ''', (appt['parent_appointment_id'],)).fetchone())
                appt['parent_info'] = parent
            else:
                prev = dict_from_row(conn.execute('''

                    SELECT appointment_date, appointment_time, status, notes, id

                    FROM mat_simple_appointments 

                    WHERE (case_number = ? OR (visitor_name = ? AND visitor_name != ''))

                      AND id < ?

                    ORDER BY id DESC LIMIT 1

                ''', (appt['case_number'], appt['visitor_name'], appt['id'])).fetchone())
                if prev:
                    appt['parent_info'] = prev

        # Fetch reserved files for current user
        mat_reserved_files = rows_to_list(conn.execute('''

            SELECT r.*, o.name as officer_name 

            FROM mat_reserved_files r

            JOIN mat_officers o ON r.officer_id = o.id

            WHERE r.officer_id = ?

            ORDER BY r.reserved_at DESC

        ''', (user['user_id'],)).fetchall())

        top_searched_areas = rows_to_list(conn.execute('''

            SELECT area_name, closest_station, directorate, search_count, last_searched_at

            FROM mat_search_logs

            ORDER BY search_count DESC

            LIMIT 8

        ''').fetchall())

        no_answer_appts = rows_to_list(conn.execute('''

            SELECT sa.*, req.name as requested_by_name

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers req ON sa.requested_by_id = req.id

            WHERE sa.status = 'ู„ู… ูŠุฌูŠุจูˆุง'

            ORDER BY sa.updated_at DESC, sa.appointment_date DESC

        ''').fetchall())

        conn.close()
        self.send_json({
            'stats': stats,
            'today_appointments': today_appts,
            'top_searched_areas': top_searched_areas,
            'my_reserved_files': mat_reserved_files,
            'no_answer_appointments': no_answer_appts
        })

    def api_log_search(self):
        data = self.read_json_body()
        area_name = data.get('area_name', '').strip()
        closest_station = data.get('closest_station', '').strip()
        directorate = data.get('directorate', '').strip()

        if not area_name:
            self.send_json({'error': 'ุงุณู… ุงู„ู…ู†ุทู‚ุฉ ู…ุทู„ูˆุจ'}, 400)
            return

        conn = get_db()
        conn.execute('''

            INSERT INTO mat_search_logs (area_name, closest_station, directorate, search_count, last_searched_at)

            VALUES (?, ?, ?, 1, datetime('now', 'localtime'))

            ON CONFLICT(area_name) DO UPDATE SET

                search_count = search_count + 1,

                closest_station = CASE WHEN ? != '' THEN ? ELSE closest_station END,

                directorate = CASE WHEN ? != '' THEN ? ELSE directorate END,

                last_searched_at = datetime('now', 'localtime')

        ''', (area_name, closest_station, directorate, closest_station, closest_station, directorate, directorate))

        conn.commit()
        conn.close()
        self.send_json({'success': True})

    def api_get_simple_appointments(self):
        user = self.require_auth()
        if not user:
            return

        params = self.get_query_params()
        from_date = params.get('from', '')
        to_date = params.get('to', '')
        status = params.get('status', '')
        q = params.get('q', '').strip()

        conn = get_db()
        sync_postponed_appointments(conn)

        
        where_clauses = []
        query_params = []

        if from_date:
            where_clauses.append("sa.appointment_date >= ?")
            query_params.append(from_date)

        if to_date:
            where_clauses.append("sa.appointment_date <= ?")
            query_params.append(to_date)

        if status:
            where_clauses.append("sa.status = ?")
            query_params.append(status)

        if q:
            where_clauses.append("(sa.case_number LIKE ? OR sa.visitor_name LIKE ? OR sa.phone LIKE ? OR sa.notes LIKE ? OR sa.station_name LIKE ?)")
            q_like = f"%{q}%"
            query_params.extend([q_like, q_like, q_like, q_like, q_like])

        where_sql = "WHERE " + " AND ".join(where_clauses) if where_clauses else "WHERE 1=1"

        query = f'''

            SELECT sa.*, req.name as requested_by_name, cb.name as created_by_name

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers req ON sa.requested_by_id = req.id

            LEFT JOIN mat_officers cb ON sa.created_by_id = cb.id

            {where_sql}

            ORDER BY sa.appointment_date DESC, sa.appointment_time ASC

        '''

        appts = rows_to_list(conn.execute(query, query_params).fetchall())

        for appt in appts:
            if appt.get('parent_appointment_id'):
                parent = dict_from_row(conn.execute('''

                    SELECT appointment_date, appointment_time, status, notes 

                    FROM mat_simple_appointments WHERE id = ?

                ''', (appt['parent_appointment_id'],)).fetchone())
                appt['parent_info'] = parent
            else:
                # Auto-link to previous appointment for the same case number or visitor if exists
                prev = dict_from_row(conn.execute('''

                    SELECT appointment_date, appointment_time, status, notes, id

                    FROM mat_simple_appointments 

                    WHERE (case_number = ? OR (visitor_name = ? AND visitor_name != ''))

                      AND id < ?

                    ORDER BY id DESC LIMIT 1

                ''', (appt['case_number'], appt['visitor_name'], appt['id'])).fetchone())
                if prev:
                    appt['parent_info'] = prev

        conn.close()
        self.send_json({'mat_appointments': appts})

    def api_create_simple_appointment(self):
        user = self.require_auth()
        if not user:
            return

        data = self.read_json_body()
        case_number = data.get('case_number', '').strip()
        visitor_name = data.get('visitor_name', '').strip()
        appt_date = data.get('appointment_date', '').strip()
        appt_time = data.get('appointment_time', '').strip()

        if not case_number or not visitor_name or not appt_date or not appt_time:
            self.send_json({'error': 'ูŠุฑุฌู‰ ุฅุฏุฎุงู„ ุฑู‚ู… ุงู„ู‚ุถูŠุฉ/ุงู„ุตุงุฏุฑุŒ ุงุณู… ุงู„ู…ุฑุงุฌุนุŒ ูˆุงู„ุชุงุฑูŠุฎ ูˆุงู„ูˆู‚ุช'}, 400)
            return

        phone = data.get('phone', '').strip()
        national_id = data.get('national_id', '').strip()

        conn = get_db()
        
        # BR-001 Conflict Detection
        conflict_query = '''

            SELECT id, case_number, created_by_id 

            FROM mat_simple_appointments 

            WHERE appointment_date = ? 

              AND appointment_time = ? 

              AND (visitor_name = ? OR (phone != '' AND phone = ?) OR (national_id != '' AND national_id = ?))

              AND status != 'ู…ู„ุบู‰'

        '''
        conflicts = conn.execute(conflict_query, (appt_date, appt_time, visitor_name, phone, national_id)).fetchall()
        for conflict in conflicts:
            conflict_dict = dict(conflict)
            if conflict_dict['case_number'] != case_number or conflict_dict['created_by_id'] != user['user_id']:
                conn.close()
                self.send_json({'error': 'ู‡ุฐุง ุงู„ู…ุฑุงุฌุน ู„ุฏูŠู‡ ู…ูˆุนุฏ ููŠ ู†ูุณ ุงู„ูˆู‚ุช ู„ู‚ุถูŠุฉ ุฃุฎุฑู‰ ุฃูˆ ู…ุน ุถุงุจุท ุขุฎุฑ'}, 400)
                return
        c = conn.execute('''

            INSERT INTO mat_simple_appointments (

                case_number, visitor_name, phone, national_id, station_name,

                appointment_date, appointment_time, status, notes, created_by_id,

                requested_by_id, parent_appointment_id

            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

        ''', (
            case_number, visitor_name,
            data.get('phone', '').strip(),
            data.get('national_id', '').strip(),
            data.get('station_name', '').strip() or 'ู‚ุณู… ุงู„ู…ูˆุงุนูŠุฏ',
            appt_date, appt_time,
            data.get('status', 'ู…ูุฌุฏูˆู„'),
            data.get('notes', '').strip(),
            user['user_id'],
            data.get('requested_by_id'),
            data.get('parent_appointment_id')
        ))

        appt_id = c.lastrowid
        
        # If this is a rescheduled branch appointment, update parent appointment status to 'ู…ูุคุฌู„'
        parent_id = data.get('parent_appointment_id')
        if parent_id:
            try:
                parent_id = int(parent_id)
                conn.execute(
                    "UPDATE mat_simple_appointments SET status = 'ู…ูุคุฌู„', updated_at = datetime('now', 'localtime') WHERE id = ?",
                    (parent_id,)
                )
                log_activity(conn, user['user_id'], 'ุชุฃุฌูŠู„ ุงู„ู…ูˆุนุฏ ูˆุฅุนุงุฏุฉ ุงู„ุฌุฏูˆู„ุฉ', 'simple_appointment', parent_id,
                             f"ุชู… ุฅู†ุดุงุก ู…ูˆุนุฏ ุฌุฏูŠุฏ ูุฑุนูŠ ุฑู‚ู… #{appt_id} ุจุชุงุฑูŠุฎ {appt_date}")
            except Exception as pe:
                print(f"Error updating parent appointment status: {pe}")

        sync_postponed_appointments(conn)
        conn.commit()
        conn.close()
        backup_db_to_json()

        self.send_json({'success': True, 'id': appt_id}, 201)

    def api_update_simple_appointment(self, appt_id):
        user = self.require_auth()
        if not user:
            return

        data = self.read_json_body()
        conn = get_db()

        existing_row = conn.execute("SELECT * FROM mat_simple_appointments WHERE id=?", (appt_id,)).fetchone()
        if not existing_row:
            conn.close()
            self.send_json({'error': 'ุงู„ู…ูˆุนุฏ ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)
            return

        existing = dict(existing_row)

        # BR-001 Conflict Detection for Updates
        new_case_number = data.get('case_number', existing['case_number'])
        new_visitor_name = data.get('visitor_name', existing['visitor_name'])
        new_appt_date = data.get('appointment_date', existing['appointment_date'])
        new_appt_time = data.get('appointment_time', existing['appointment_time'])
        new_phone = data.get('phone', existing.get('phone', ''))
        new_national_id = data.get('national_id', existing.get('national_id', ''))

        if 'appointment_date' in data or 'appointment_time' in data or 'visitor_name' in data or 'phone' in data or 'national_id' in data:
            conflict_query = '''

                SELECT id, case_number, created_by_id 

                FROM mat_simple_appointments 

                WHERE id != ?

                  AND appointment_date = ? 

                  AND appointment_time = ? 

                  AND (visitor_name = ? OR (phone != '' AND phone = ?) OR (national_id != '' AND national_id = ?))

                  AND status != 'ู…ู„ุบู‰'

            '''
            conflicts = conn.execute(conflict_query, (appt_id, new_appt_date, new_appt_time, new_visitor_name, new_phone, new_national_id)).fetchall()
            for conflict in conflicts:
                conflict_dict = dict(conflict)
                if conflict_dict['case_number'] != new_case_number or conflict_dict['created_by_id'] != user['user_id']:
                    conn.close()
                    self.send_json({'error': 'ู‡ุฐุง ุงู„ู…ุฑุงุฌุน ู„ุฏูŠู‡ ู…ูˆุนุฏ ููŠ ู†ูุณ ุงู„ูˆู‚ุช ู„ู‚ุถูŠุฉ ุฃุฎุฑู‰ ุฃูˆ ู…ุน ุถุงุจุท ุขุฎุฑ'}, 400)
                    return

        fields = []
        values = []
        for key in ['case_number', 'visitor_name', 'phone', 'national_id', 'station_name', 'appointment_date', 'appointment_time', 'status', 'notes', 'requested_by_id']:
            if key in data:
                fields.append(f"{key} = ?")
                values.append(data[key])

        if fields:
            fields.append("updated_at = datetime('now', 'localtime')")
            values.append(appt_id)
            conn.execute(f"UPDATE mat_simple_appointments SET {', '.join(fields)} WHERE id = ?", values)

            # โ”€โ”€ Record history entry for every update โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
            new_status = data.get('status', existing.get('status', ''))
            action_notes = data.get('notes', '')
            history_detail = json.dumps({
                'status': new_status,
                'notes': action_notes,
                'changed_fields': list(data.keys())
            }, ensure_ascii=False)
            conn.execute(
                "INSERT INTO mat_activity_log (user_id, action, entity_type, entity_id, details) VALUES (?,?,?,?,?)",
                (user['user_id'], f'ุชุญุฏูŠุซ ู…ูˆุนุฏ โ€” {new_status}' if new_status else 'ุชุญุฏูŠุซ ู…ูˆุนุฏ',
                 'simple_appointment', int(appt_id), history_detail)
            )
            conn.commit()

        conn.close()
        backup_db_to_json()
        self.send_json({'success': True})

    def api_get_simple_appointment_detail(self, appt_id):
        """Return full appointment details + action history from mat_activity_log."""
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        appt_row = conn.execute('''

            SELECT sa.*, req.name as requested_by_name, cb.name as created_by_name

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers req ON sa.requested_by_id = req.id

            LEFT JOIN mat_officers cb ON sa.created_by_id = cb.id

            WHERE sa.id = ?

        ''', (appt_id,)).fetchone()

        if not appt_row:
            conn.close()
            self.send_json({'error': 'ุงู„ู…ูˆุนุฏ ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)
            return

        appt = dict_from_row(appt_row)

        # Fetch full history from same case_number or visitor for historical chain
        all_appts = rows_to_list(conn.execute('''

            SELECT sa.id, sa.appointment_date, sa.appointment_time, sa.status, sa.notes,

                   cb.name as created_by_name, sa.created_at, sa.updated_at

            FROM mat_simple_appointments sa

            LEFT JOIN mat_officers cb ON sa.created_by_id = cb.id

            WHERE (sa.case_number = ? AND sa.case_number != '')

               OR (sa.visitor_name = ? AND sa.visitor_name != '')

            ORDER BY sa.appointment_date ASC, sa.appointment_time ASC

        ''', (appt.get('case_number', ''), appt.get('visitor_name', ''))).fetchall())

        # Fetch action history from mat_activity_log for this specific appointment
        history = rows_to_list(conn.execute('''

            SELECT al.action, al.details, al.created_at, o.name as officer_name

            FROM mat_activity_log al

            LEFT JOIN mat_officers o ON al.user_id = o.id

            WHERE al.entity_type = 'simple_appointment' AND al.entity_id = ?

            ORDER BY al.created_at ASC

        ''', (int(appt_id),)).fetchall())

        conn.close()
        self.send_json({
            'appointment': appt,
            'history': history,
            'all_appointments': all_appts
        })

    def api_delete_simple_appointment(self, appt_id):
        user = self.require_auth()
        if not user:
            return

        conn = get_db()
        conn.execute("DELETE FROM mat_simple_appointments WHERE id = ?", (appt_id,))
        conn.commit()
        conn.close()
        backup_db_to_json()
        self.send_json({'success': True})

    # โ”€โ”€ FILE RESERVATIONS API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    def api_get_reservations(self):
        user = self.require_auth()
        if not user: return
        conn = get_db()
        params = self.get_query_params()
        
        if params.get('all') == '1' and user['role'] == 'admin':
            files = rows_to_list(conn.execute('''

                SELECT r.*, o.name as officer_name 

                FROM mat_reserved_files r

                JOIN mat_officers o ON r.officer_id = o.id

                ORDER BY r.reserved_at DESC

            ''').fetchall())
        else:
            files = rows_to_list(conn.execute('''

                SELECT r.*, o.name as officer_name 

                FROM mat_reserved_files r

                JOIN mat_officers o ON r.officer_id = o.id

                WHERE r.officer_id = ?

                ORDER BY r.reserved_at DESC

            ''', (user['user_id'],)).fetchall())
        conn.close()
        self.send_json({'reservations': files})

    def api_search_reservations(self):
        user = self.require_auth()
        if not user: return
        query = self.get_query_params().get('q', '').strip()
        if not query:
            self.send_json({'reservations': []})
            return
            
        conn = get_db()
        files = rows_to_list(conn.execute('''

            SELECT r.*, o.name as officer_name 

            FROM mat_reserved_files r

            JOIN mat_officers o ON r.officer_id = o.id

            WHERE r.file_number LIKE ?

            ORDER BY r.reserved_at DESC

        ''', (f'%{query}%',)).fetchall())
        conn.close()
        self.send_json({'reservations': files})

    def api_create_reservation(self):
        user = self.require_auth()
        if not user: return
        data = self.read_json_body()
        file_number = data.get('file_number', '').strip()
        notes = data.get('notes', '').strip()
        if not file_number:
            self.send_json({'error': 'ุฑู‚ู… ุงู„ู…ู„ู ู…ุทู„ูˆุจ'}, 400)
            return
            
        conn = get_db()
        try:
            conn.execute("INSERT INTO mat_reserved_files (file_number, officer_id, notes) VALUES (?, ?, ?)",
                         (file_number, user['user_id'], notes))
            res_id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
            conn.execute("INSERT INTO mat_file_custody_log (reserved_file_id, to_officer_id, status, notes) VALUES (?, ?, 'accepted', ?)",
                         (res_id, user['user_id'], 'ุชุณุฌูŠู„ ุฃูˆู„ูŠ'))
            conn.commit()
            self.send_json({'success': True})
        except sqlite3.IntegrityError:
            # Check who has it
            existing = dict_from_row(conn.execute('''

                SELECT o.name FROM mat_reserved_files r

                JOIN mat_officers o ON r.officer_id = o.id

                WHERE r.file_number = ?

            ''', (file_number,)).fetchone())
            owner = existing['name'] if existing else 'ุดุฎุต ุขุฎุฑ'
            self.send_json({'error': f'ู‡ุฐุง ุงู„ู…ู„ู ู…ุญุฌูˆุฒ ู…ุณุจู‚ุงู‹ ู„ุฏู‰ {owner}'}, 400)
        finally:
            conn.close()

    def api_delete_reservation(self, res_id):
        user = self.require_auth()
        if not user: return
        conn = get_db()
        if user['role'] == 'admin':
            conn.execute("DELETE FROM mat_reserved_files WHERE id = ?", (res_id,))
        else:
            conn.execute("DELETE FROM mat_reserved_files WHERE id = ? AND officer_id = ?", (res_id, user['user_id']))
        conn.commit()
        conn.close()
        self.send_json({'success': True})

    def api_transfer_reservation(self):
        user = self.require_auth()
        if not user: return
        data = self.read_json_body()
        res_id = data.get('reservation_id')
        to_officer_id = data.get('to_officer_id')
        notes = data.get('notes', '').strip()
        
        if not res_id or not to_officer_id:
            self.send_json({'error': 'ุจูŠุงู†ุงุช ุงู„ู†ู‚ู„ ุบูŠุฑ ู…ูƒุชู…ู„ุฉ'}, 400)
            return

        conn = get_db()
        try:
            # Verify the file is reserved by the current user (or admin)
            if user['role'] == 'admin':
                res = conn.execute("SELECT * FROM mat_reserved_files WHERE id = ?", (res_id,)).fetchone()
            else:
                res = conn.execute("SELECT * FROM mat_reserved_files WHERE id = ? AND officer_id = ?", (res_id, user['user_id'])).fetchone()
                
            if not res:
                self.send_json({'error': 'ู„ุง ุชู…ู„ูƒ ุตู„ุงุญูŠุฉ ู†ู‚ู„ ู‡ุฐุง ุงู„ู…ู„ู ุฃูˆ ุฃู†ู‡ ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 403)
                return
                
            # Log the transfer as PENDING
            conn.execute("INSERT INTO mat_file_custody_log (reserved_file_id, from_officer_id, to_officer_id, status, notes) VALUES (?, ?, ?, 'pending', ?)",
                         (res_id, res['officer_id'], to_officer_id, notes))
            
            # Log to general audit
            conn.execute("INSERT INTO mat_audit_logs (action, resource_id, actor_id, details) VALUES (?, ?, ?, ?)",
                         ("INITIATE_FILE_TRANSFER", str(res_id), user['user_id'], f"To officer {to_officer_id}: {notes}"))
            
            conn.commit()
            self.send_json({'success': True, 'message': 'ุชู… ุฅุฑุณุงู„ ุทู„ุจ ู†ู‚ู„ ุงู„ุนู‡ุฏุฉ ุจุงู†ุชุธุงุฑ ู…ูˆุงูู‚ุฉ ุงู„ู…ุณุชู„ู….'})
        except Exception as e:
            self.send_json({'error': str(e)}, 500)
        finally:
            conn.close()

    def api_get_pending_transfers(self):
        user = self.require_auth()
        if not user: return
        conn = get_db()
        
        # Pending requests directed to me
        inbound = rows_to_list(conn.execute('''

            SELECT l.id as log_id, r.file_number, o.name as from_officer_name, l.notes, l.transferred_at

            FROM mat_file_custody_log l

            JOIN mat_reserved_files r ON l.reserved_file_id = r.id

            JOIN mat_officers o ON l.from_officer_id = o.id

            WHERE l.to_officer_id = ? AND l.status = 'pending'

            ORDER BY l.transferred_at DESC

        ''', (user['user_id'],)).fetchall())
        
        # Pending requests I sent
        outbound = rows_to_list(conn.execute('''

            SELECT l.id as log_id, r.file_number, o.name as to_officer_name, l.notes, l.transferred_at

            FROM mat_file_custody_log l

            JOIN mat_reserved_files r ON l.reserved_file_id = r.id

            JOIN mat_officers o ON l.to_officer_id = o.id

            WHERE l.from_officer_id = ? AND l.status = 'pending'

            ORDER BY l.transferred_at DESC

        ''', (user['user_id'],)).fetchall())
        
        conn.close()
        self.send_json({'inbound': inbound, 'outbound': outbound})

    def api_respond_transfer(self):
        user = self.require_auth()
        if not user: return
        data = self.read_json_body()
        log_id = data.get('log_id')
        response = data.get('response') # 'accept' or 'reject'
        
        if not log_id or response not in ('accept', 'reject'):
            self.send_json({'error': 'ุจูŠุงู†ุงุช ุงู„ุฑุฏ ุบูŠุฑ ุตุงู„ุญุฉ'}, 400)
            return

        conn = get_db()
        try:
            # Check if this log entry is a pending request to me
            log = dict_from_row(conn.execute('''

                SELECT * FROM mat_file_custody_log WHERE id = ? AND to_officer_id = ? AND status = 'pending'

            ''', (log_id, user['user_id'])).fetchone())
            
            if not log:
                self.send_json({'error': 'ุงู„ุทู„ุจ ุบูŠุฑ ู…ูˆุฌูˆุฏ ุฃูˆ ู„ุณุช ู…ุฎูˆู„ุงู‹ ุจุงู„ุฑุฏ'}, 404)
                return
                
            new_status = 'accepted' if response == 'accept' else 'rejected'
            
            conn.execute("UPDATE mat_file_custody_log SET status = ?, transferred_at = datetime('now', 'localtime') WHERE id = ?", (new_status, log_id))
            
            if response == 'accept':
                conn.execute("UPDATE mat_reserved_files SET officer_id = ? WHERE id = ?", (user['user_id'], log['reserved_file_id']))
                conn.execute("INSERT INTO mat_audit_logs (action, resource_id, actor_id, details) VALUES (?, ?, ?, ?)",
                             ("ACCEPT_FILE_TRANSFER", str(log['reserved_file_id']), user['user_id'], f"Accepted from {log['from_officer_id']}"))
            else:
                conn.execute("INSERT INTO mat_audit_logs (action, resource_id, actor_id, details) VALUES (?, ?, ?, ?)",
                             ("REJECT_FILE_TRANSFER", str(log['reserved_file_id']), user['user_id'], f"Rejected from {log['from_officer_id']}"))
                             
            conn.commit()
            self.send_json({'success': True})
        except Exception as e:
            self.send_json({'error': str(e)}, 500)
        finally:
            conn.close()

    def api_get_custody_history(self, res_id):
        user = self.require_auth()
        if not user: return
        conn = get_db()
        
        history = rows_to_list(conn.execute('''

            SELECT l.status, l.notes, l.transferred_at, 

                   f.name as from_officer_name, t.name as to_officer_name

            FROM mat_file_custody_log l

            LEFT JOIN mat_officers f ON l.from_officer_id = f.id

            JOIN mat_officers t ON l.to_officer_id = t.id

            WHERE l.reserved_file_id = ?

            ORDER BY l.transferred_at DESC

        ''', (res_id,)).fetchall())
        
        file_info = dict_from_row(conn.execute('''

            SELECT r.file_number, o.name as current_officer_name 

            FROM mat_reserved_files r

            JOIN mat_officers o ON r.officer_id = o.id

            WHERE r.id = ?

        ''', (res_id,)).fetchone())
        
        conn.close()
        
        if not file_info:
            self.send_json({'error': 'ุงู„ู…ู„ู ุบูŠุฑ ู…ูˆุฌูˆุฏ'}, 404)
            return
            
        self.send_json({'file': file_info, 'history': history})


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  SERVER STARTUP
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    """Handle requests in separate threads."""
    allow_reuse_address = True
    daemon_threads = True


def get_local_ip():
    """Get the machine's local IP address."""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("10.255.255.255", 1))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"


if __name__ == '__main__':
    # Initialize database
    init_db()

    local_ip = get_local_ip()

    print()
    print("โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—")
    print("โ•‘          ู†ุธุงู… ุฅุฏุงุฑุฉ ู…ูˆุงุนูŠุฏ ุงู„ุดูƒุงูˆูŠ โ€” ุฌุงู‡ุฒ ู„ู„ุนู…ู„           โ•‘")
    print("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ")
    print(f"โ•‘  ๐ŸŒ ุฏู„ูŠู„ ุงู„ู…ุฑุงูƒุฒ:  http://{local_ip}:{PORT}/               ")
    print(f"โ•‘  ๐Ÿ“‹ ู†ุธุงู… ุงู„ุดูƒุงูˆูŠ:  http://{local_ip}:{PORT}/mat_complaints/    ")
    print("โ•‘                                                              โ•‘")
    print(f"โ•‘  ู…ู† ู‡ุฐุง ุงู„ุฌู‡ุงุฒ:   http://localhost:{PORT}/                  ")
    print("โ•‘                                                              โ•‘")
    print("โ•‘  โš ๏ธ  ู„ุง ุชุบู„ู‚ ู‡ุฐู‡ ุงู„ู†ุงูุฐุฉ ุฃุซู†ุงุก ุงุณุชุฎุฏุงู… ุงู„ู†ุธุงู…               โ•‘")
    print("โ•‘  ๐Ÿ›‘ ู„ู„ุฅูŠู‚ุงู: ุงุถุบุท Ctrl+C                                    โ•‘")
    print("โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•")
    print()

    server = ThreadedHTTPServer((HOST, PORT), MatServerHandler)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n๐Ÿ›‘ ุชู… ุฅูŠู‚ุงู ุงู„ุฎุงุฏู…")
        server.server_close()