File size: 73,727 Bytes
ea9a026
 
 
ba7fcc6
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
1e65df5
ea9a026
 
 
ba7fcc6
1e65df5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
ea9a026
0330133
 
ea9a026
0330133
 
 
 
ea9a026
0330133
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
df049d2
0330133
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
ba7fcc6
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
 
 
ba7fcc6
 
0330133
 
 
ba7fcc6
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
ba7fcc6
0330133
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
0330133
 
 
 
ba7fcc6
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
ba7fcc6
0330133
 
 
ea9a026
 
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
2698900
0330133
 
 
 
 
 
 
 
2698900
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
 
2698900
 
0330133
 
 
 
2698900
1e65df5
2698900
 
1e65df5
 
 
 
 
 
 
 
 
 
 
 
2698900
 
 
 
0330133
 
 
1e65df5
 
0330133
 
 
1e65df5
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
2698900
 
1e65df5
2698900
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
2698900
0330133
 
 
 
ea9a026
0330133
 
 
 
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df049d2
 
 
 
0330133
 
df049d2
 
0330133
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
2698900
 
 
 
0330133
 
 
 
 
 
 
 
2698900
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
 
2698900
0330133
 
 
 
2698900
1e65df5
2698900
 
1e65df5
 
 
 
 
 
 
 
 
 
 
 
2698900
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
2698900
0330133
 
 
 
ea9a026
0330133
ea9a026
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0330133
 
 
 
 
 
 
2698900
 
0330133
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
ea9a026
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
df049d2
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
df049d2
0330133
 
 
 
 
 
 
 
ea9a026
0330133
 
 
ea9a026
0330133
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
ea9a026
 
0330133
 
 
 
ea9a026
0330133
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
c6a4aaf
0330133
 
 
 
 
c6a4aaf
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
2698900
0330133
 
 
 
 
 
 
 
 
2698900
1e65df5
0330133
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2698900
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
2698900
1e65df5
 
 
 
 
 
 
 
 
ea9a026
1e65df5
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
 
 
 
ea9a026
0330133
 
 
 
 
ea9a026
c6a4aaf
 
0330133
 
2698900
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
c6a4aaf
0330133
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
c6a4aaf
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
2698900
0330133
 
2698900
 
 
0330133
 
 
 
c6a4aaf
0330133
 
 
 
c6a4aaf
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2698900
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
 
df049d2
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
df049d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
 
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df049d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2698900
df049d2
2698900
 
 
 
 
 
1e65df5
2698900
 
df049d2
 
 
2698900
1e65df5
 
 
 
 
 
 
 
2698900
 
 
1e65df5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2698900
 
 
 
 
 
1e65df5
2698900
 
1e65df5
2698900
 
 
 
 
 
 
 
 
 
1e65df5
2698900
 
df049d2
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
2698900
 
 
1e65df5
 
 
 
 
 
2698900
 
 
 
 
 
 
 
1e65df5
2698900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e65df5
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
import Invoice from "../models/InvoiceModel.js";
import Customer from "../models/CustomerModel.js";
import Product from "../models/ProductModel.js";
import CatalogItem from "../models/CatalogItemModel.js";
import Counter from "../models/CounterModel.js";
import Income from "../models/IncomeModel.js";
import Tenant from "../models/TenantModel.js";
import WhatsAppService from "../utils/whatsappService.js";
import User from "../models/UserModel.js";
import Driver from "../models/DriverModel.js";
import Table from "../models/TableModel.js"; // โœ… was missing โ€” needed for table validation
import mongoose from "mongoose";
import {
  resolveBranchForWrite,
  resolveScopedBranch,
} from "../utils/branchContext.js";
import { normalizeCustomerName, normalizeCustomerPhone } from "../utils/customerNormalization.js";

const WALK_IN_CUSTOMER_NAME = "Walking-in Customer";

const INVOICE_ITEM_TYPES = ["product", "service", "catalog"];
const ALLOWED_TRANSFER_TYPES = ["instapay", "vodafone_cash", "bank_transfer", "wallet"];
const roundMoney = (value) => Math.round(Number(value || 0));

const escapeRegExp = (value = "") => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

const bindSettlementCustomer = async ({

  tenantId,

  branchId,

  userId,

  customerName,

  customerPhone,

  fallbackCustomerId = null,

  session = null,

}) => {
  const displayName = String(customerName || "").trim();
  const normalizedName = normalizeCustomerName(customerName);
  const normalizedPhone = normalizeCustomerPhone(customerPhone);
  let resolvedCustomer = null;

  if (normalizedPhone) {
    resolvedCustomer = await Customer.findOneAndUpdate(
      { tenant: tenantId, phone: normalizedPhone },
      {
        $set: {
          ...(displayName ? { name: displayName } : {}),
          phone: normalizedPhone,
          isWalkIn: false,
        },
        $setOnInsert: {
          tenant: tenantId,
          branch: branchId || undefined,
          createdBy: userId || null,
        },
      },
      { upsert: true, new: true, session }
    );
  } else if (normalizedName) {
    const nameRegex = new RegExp(`^${escapeRegExp(displayName)}$`, "i");
    resolvedCustomer = await Customer.findOne({
      tenant: tenantId,
      isWalkIn: false,
      $or: [
        { normalizedName },
        { name: nameRegex },
      ],
    }).session(session);
  }

  if (!resolvedCustomer && fallbackCustomerId) {
    resolvedCustomer = await Customer.findById(fallbackCustomerId).session(session);
    if (resolvedCustomer && normalizedPhone && resolvedCustomer.phone !== normalizedPhone) {
      resolvedCustomer.phone = normalizedPhone;
    }
    if (resolvedCustomer && displayName) {
      resolvedCustomer.name = displayName;
      resolvedCustomer.isWalkIn = false;
    }
    if (resolvedCustomer && (normalizedPhone || normalizedName)) {
      await resolvedCustomer.save({ session });
    }
  }

  return resolvedCustomer;
};

const buildOrderMessage = ({

  status,

  orderNumber,

  restaurantName,

  itemsList,

  driverName,

  driverPhone,

  orderType,

}) => {
  switch (status) {
    case "pending":
      return `๐Ÿงพ ุชู… ุงุณุชู„ุงู… ุทู„ุจูƒ ุฑู‚ู… #${orderNumber} ููŠ ${restaurantName}\n\nุฌุงุฑูŠ ุงู„ู…ุฑุงุฌุนุฉ ุงู„ุขู†.`;

    case "preparing":
      return `๐Ÿ‘จโ€๐Ÿณ ุทู„ุจูƒ ุฑู‚ู… #${orderNumber} ู‚ูŠุฏ ุงู„ุชุญุถูŠุฑ ุงู„ุขู† ููŠ ${restaurantName}\n\n${itemsList}`;

    case "ready_for_delivery":
      return `๐Ÿฝ๏ธ ุทู„ุจูƒ ุฑู‚ู… #${orderNumber} ุฌุงู‡ุฒ ุงู„ุขู† ู„ู„ุงุณุชู„ุงู… ู…ู† ${restaurantName}`;

    case "shipped":
      return orderType === "delivery"
        ? `๐Ÿšš ุทู„ุจูƒ ุฑู‚ู… #${orderNumber} ููŠ ุงู„ุทุฑูŠู‚ ุฅู„ูŠูƒ\n\nุงู„ุณุงุฆู‚: ${driverName}\nุฑู‚ู… ุงู„ู‡ุงุชู: ${driverPhone}`
        : `๐Ÿšถ ุทู„ุจูƒ ุฑู‚ู… #${orderNumber} ุฌุงู‡ุฒ ู„ู„ุงุณุชู„ุงู…`;

    default:
      return `๐Ÿ“ฆ ุชุญุฏูŠุซ ุนู„ู‰ ุทู„ุจูƒ ุฑู‚ู… #${orderNumber}`;
  }
};

async function generateInvoiceNumber(tenantId, branchId) {
  const counter = await Counter.findOneAndUpdate(
    { tenant: tenantId, branch: branchId },
    { $inc: { invoiceNumber: 1 } },
    {
      new: true,
      upsert: true,
      setDefaultsOnInsert: true,
    },
  );

  const padded = String(counter.invoiceNumber).padStart(8, "0");
  return `INV-${padded}`;
}

const getOrCreateWalkInCustomer = async (tenantId, branchId, userId) => {
  let customer = await Customer.findOne({
    tenant: tenantId,
    branch: branchId,
    isWalkIn: true,
  });

  if (!customer) {
    customer = await Customer.create({
      tenant: tenantId,
      branch: branchId,
      name: WALK_IN_CUSTOMER_NAME,
      isWalkIn: true,
      notes: "System generated customer for walk-in cash sales.",
      createdBy: userId || null,
    });
  }

  return customer;
};

const ensureStockAvailability = async (items, tenantId, branchId) => {
  for (const item of items) {
    if (item.type !== "product" || !item.productId) {
      continue;
    }

    const product = await Product.findOne({
      _id: item.productId,
      tenant: tenantId,
      branch: branchId,
    });
    if (!product) {
      const error = new Error(`ุงู„ู…ู†ุชุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ: ${item.name}`);
      error.statusCode = 404;
      throw error;
    }

    if (product.stock < Number(item.quantity)) {
      const error = new Error(
        `ุงู„ู…ุฎุฒูˆู† ุบูŠุฑ ูƒุงูู ู„ู„ุตู†ู ${item.name}. ุงู„ู…ุชุงุญ: ${product.stock}`,
      );
      error.statusCode = 400;
      throw error;
    }
  }
};

const validateCatalogItems = async (items, tenantId, branchId) => {
  for (const item of items) {
    if (item.type !== "catalog" || !item.catalogItemId) {
      continue;
    }

    const catalogItem = await CatalogItem.findOne({
      _id: item.catalogItemId,
      tenant: tenantId,
      branch: branchId,
      isActive: true,
    }).populate("category", "name");

    if (!catalogItem) {
      const error = new Error(`ุนู†ุตุฑ ุงู„ูƒุชุงู„ูˆุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ: ${item.name}`);
      error.statusCode = 404;
      throw error;
    }
  }
};

const applyInvoiceItemsAndStock = async (

  invoice,

  items,

  tenantId,

  branchId,

) => {
  for (const item of items) {
    const quantity = Number(item.quantity || 0);
    const normalizedType = INVOICE_ITEM_TYPES.includes(item.type)
      ? item.type
      : item.productId
        ? "product"
        : "service";
    let resolvedName = item.name;
    let resolvedPrice = Number(item.price || 0);

    if (normalizedType === "catalog" && item.catalogItemId) {
      const catalogItem = await CatalogItem.findOne({
        _id: item.catalogItemId,
        tenant: tenantId,
        branch: branchId,
      });

      if (!catalogItem) {
        const error = new Error(`ุนู†ุตุฑ ุงู„ูƒุชุงู„ูˆุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ: ${item.name}`);
        error.statusCode = 404;
        throw error;
      }

      resolvedName = catalogItem.name;
      resolvedPrice = Number(catalogItem.price || 0);
    }

    invoice.items.push({
      name: resolvedName,
      quantity,
      price: resolvedPrice,
      total: quantity * resolvedPrice,
      type: normalizedType,
      ...(item.productId ? { productId: item.productId } : {}),
      ...(item.serviceId ? { serviceId: item.serviceId } : {}),
      ...(item.catalogItemId ? { catalogItemId: item.catalogItemId } : {}),
    });

    if (normalizedType === "product" && item.productId) {
      await Product.findOneAndUpdate(
        { _id: item.productId, tenant: tenantId, branch: branchId },
        { $inc: { stock: -quantity } },
      );
    }
  }
};

const createIncomeForPayment = async ({

  tenantId,

  branchId,

  invoice,

  customer,

  amount,

  userId,

  date,

  notes,

  paymentMethod = "cash",

  transferType = null,

}) => {
  if (!amount || amount <= 0) {
    return;
  }

  // If the invoice has services, calculate the ratio and split the income record
  const revenueBuckets = [
    {
      amount: Number(invoice.serviceRevenue || 0),
      category: "service_income",
      title: `Service Income - ${invoice.invoiceNumber}`,
      notesFallback: `Service portion for invoice ${invoice.invoiceNumber}`,
    },
    {
      amount: Number(invoice.catalogRevenue || 0),
      category: "catalog_sale",
      title: `Catalog Sale - ${invoice.invoiceNumber}`,
      notesFallback: `Catalog portion for invoice ${invoice.invoiceNumber}`,
    },
    {
      amount: Number(invoice.productRevenue || 0),
      category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
      title: `Invoice payment - ${invoice.invoiceNumber}`,
      notesFallback: `Product portion for invoice ${invoice.invoiceNumber}`,
    },
  ].filter((bucket) => bucket.amount > 0);

  const totalItemRevenue = revenueBuckets.reduce(
    (sum, bucket) => sum + bucket.amount,
    0,
  );

  if (!totalItemRevenue) {
    return;
  }

  let remainingAmount = Number(amount);
  const incomesToCreate = revenueBuckets
    .map((bucket, index) => {
      const isLastBucket = index === revenueBuckets.length - 1;
      const allocatedAmount = isLastBucket
        ? Number(remainingAmount.toFixed(2))
        : Number(
          ((Number(amount) * bucket.amount) / totalItemRevenue).toFixed(2),
        );

      remainingAmount = Number((remainingAmount - allocatedAmount).toFixed(2));

      return {
        tenant: tenantId,
        branch: branchId,
        title: bucket.title,
        category: bucket.category,
        amount: allocatedAmount,
        paymentMethod,
        notes: notes || bucket.notesFallback,
        sourceType: "invoice_payment",
        relatedInvoice: invoice._id,
        relatedCustomer: customer?._id || null,
        date: date || new Date(),
        createdBy: userId || null,
      };
    })
    .filter((entry) => entry.amount > 0);

  if (incomesToCreate.length) {
    await Income.insertMany(incomesToCreate);
  }
};

// โœ… GET current tax rate
export const getTaxRate = async (req, res) => {
  try {
    const tenant = await Tenant.findById(req.user.tenant._id);
    const taxRate = tenant?.settings?.taxRate || 14; // Default: 14%
    const taxEnabled = tenant?.settings?.taxEnabled ?? true;

    res.json({
      taxRate,
      taxEnabled,
      currency: tenant?.settings?.currency || "EGP"
    });
  } catch (err) {
    res.status(500).json({ message: "Failed to get tax rate" });
  }
};

// โœ… UPDATE tax rate
export const updateTaxRate = async (req, res) => {
  try {
    const { taxRate, taxEnabled } = req.body;

    // โœ… VALIDATION
    if (taxRate !== undefined && (taxRate < 0 || taxRate > 50)) {
      return res.status(400).json({
        message: "Tax rate must be between 0 and 100"
      });
    }

    // Update tenant settings
    const tenant = await Tenant.findByIdAndUpdate(
      req.user.tenant._id,
      {
        $set: {
          "settings.taxRate": taxRate ?? 14,
          "settings.taxEnabled": taxEnabled ?? true
        }
      },
      { new: true }
    );

    res.json({
      message: "Tax rate updated successfully",
      taxRate: tenant.settings.taxRate,
      taxEnabled: tenant.settings.taxEnabled
    });
  } catch (err) {
    res.status(500).json({ message: "Failed to update tax rate" });
  }
};


export const addItemToInvoice = async (req, res) => {
  let createdCustomer = null;
  try {
    const { customerId } = req.params;
    const {
      items,
      customerName,
      customerPhone,
      notes = "",
      discount = 0,
      tax = 0,
      restaurantData,
      serviceCharge = 0,
      deliveryCharge = 0,
    } = req.body;
    const tenantId = req.user.tenant?._id;
    // โœ… FETCH TENANT FIRST to get tax settings
    const tenant = await Tenant.findById(tenantId);
    const taxRate = tenant?.settings?.taxRate || 14;
    const taxEnabled = tenant?.settings?.taxEnabled ?? true;
    const branch = await resolveBranchForWrite(req);
    const branchId = branch._id;

    if (!tenantId) {
      return res
        .status(403)
        .json({ message: "ู„ุง ูŠูˆุฌุฏ ู…ุณุชุฃุฌุฑ ู…ุฑุชุจุท ุจู‡ุฐุง ุงู„ุญุณุงุจ" });
    }
    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({ message: "ูŠุฌุจ ุฅุถุงูุฉ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„" });
    }

    let finalCustomerId = customerId;
    if (customerId === "new") {
      const normalizedCustomerPhone = normalizeCustomerPhone(customerPhone);
      const normalizedCustomerName = normalizeCustomerName(customerName);
      // โœ… PREVENT DUPLICATES: Check if phone exists first or use upsert
      const customerUpdate = {
        name: customerName.trim(),
        tenant: tenantId,
        branch: branchId,
        createdBy: req.user._id,
      };
      if (normalizedCustomerPhone) customerUpdate.phone = normalizedCustomerPhone;

      createdCustomer = await Customer.findOneAndUpdate(
        {
          tenant: tenantId,
          ...(normalizedCustomerPhone
            ? { phone: normalizedCustomerPhone }
            : {
              branch: branchId,
              isWalkIn: false,
              $or: [
                { normalizedName: normalizedCustomerName },
                { name: customerName.trim() },
              ],
            }),
        },
        { $setOnInsert: customerUpdate },
        { upsert: true, new: true, runValidators: true }
      );
      finalCustomerId = createdCustomer._id;
    }

    // Existing customers may belong to another branch when management users
    // work in all-branches mode, so resolve by tenant-wide identity.
    const customer = await Customer.findOne({
      _id: finalCustomerId,
      tenant: tenantId,
      isDeleted: false,
    });
    if (!customer) {
      if (createdCustomer)
        await Customer.deleteOne({ _id: createdCustomer._id });
      return res.status(404).json({ message: "ุงู„ุนู…ูŠู„ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
    }
    if (customer.isWalkIn) {
      if (createdCustomer)
        await Customer.deleteOne({ _id: createdCustomer._id });
      return res.status(400).json({
        message: "ุงุณุชุฎุฏู… ู…ุณุงุฑ ุจูŠุน ุงู„ุฒุงุฆุฑ ุงู„ู†ู‚ุฏูŠ ู„ููˆุงุชูŠุฑ ุงู„ุนู…ู„ุงุก ุงู„ุฒุงุฆุฑูŠู†",
      });
    }

    // โœ… NEW: Update existing customer phone if it's missing but provided in request
    if (customer && !customer.phone && customerPhone?.trim()) {
      customer.phone = normalizeCustomerPhone(customerPhone);
      await customer.save();
    }

    try {
      // โœ… Validate table availability BEFORE creating invoice
      if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
        const existingTable = await Table.findById(restaurantData.table);
        if (!existingTable) {
          return res.status(404).json({ message: "ุงู„ุทุงูˆู„ุฉ ุงู„ู…ุญุฏุฏุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
        }
        if (existingTable.status === "occupied") {
          return res.status(400).json({
            message: "ู‡ุฐู‡ ุงู„ุทุงูˆู„ุฉ ู…ุดุบูˆู„ุฉ ุญุงู„ูŠุงู‹ โ€” ูŠุฑุฌู‰ ุฅุชู…ุงู… ุงู„ุญุณุงุจ ุฃูˆู„ุงู‹ ุฃูˆ ุงุฎุชูŠุงุฑ ุทุงูˆู„ุฉ ุฃุฎุฑู‰",
          });
        }
      }

      const invoice = new Invoice({
        tenant: tenantId,
        branch: branchId,
        customer: finalCustomerId,
        issuedBy: req.user._id,
        notes: notes.trim(),
        discount: Math.max(Number(discount) || 0, 0),
        taxAmount: 0, // Will be calculated below
        serviceCharge: Math.max(Number(serviceCharge) || 0, 0),
        deliveryCharge: Math.max(Number(deliveryCharge) || 0, 0),
        restaurantData: restaurantData || null,
      });

      await validateCatalogItems(items, tenantId, branchId);
      await ensureStockAvailability(items, tenantId, branchId);
      await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);

      // โœ… Calculate tax AFTER items are added
      if (
        taxEnabled &&
        invoice.restaurantData?.orderType === "dine-in"
      ) {
        const subtotal = invoice.items.reduce(
          (sum, item) => sum + (item.price * item.quantity),
          0
        );
        invoice.taxAmount = Math.round((subtotal * taxRate) / 100 * 100) / 100;
      } else {
        invoice.taxAmount = 0;
      }

      // Robust duplicate key retry logic for missing/corrupted counters
      let saved = false;
      for (let i = 0; i < 3; i++) {
        try {
          invoice.invoiceNumber = await generateInvoiceNumber(
            tenantId,
            branchId,
          );
          invoice.calculateTotals();
          await invoice.save();
          saved = true;
          break;
        } catch (saveErr) {
          if (saveErr.code === 11000 && i < 2) continue;
          throw saveErr;
        }
      }

      if (!saved) throw new Error("ุชุนุฐุฑ ุญูุธ ุงู„ูุงุชูˆุฑุฉ ู„ุฎุทุฃ ุชุฒุงู…ู†ุŒ ุญุงูˆู„ ู…ุฌุฏุฏุงู‹");

      // โœ… Lock table after successful invoice creation
      if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
        await Table.findByIdAndUpdate(restaurantData.table, {
          status: "occupied",
          currentOrderId: invoice._id,
        });
      }
      res.status(200).json(invoice);
    } catch (err) {
      if (createdCustomer)
        await Customer.deleteOne({ _id: createdCustomer._id });
      throw err; // cascade to main catch block
    }
  } catch (err) {
    if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
    res.status(err.statusCode || 500).json({ message: err.message });
  }
};

export const updateRestaurantStatus = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const { status } = req.body;

    const allowedStatuses = [
      "pending",
      "preparing",
      "ready_for_delivery",
      "shipped",
    ];

    if (!allowedStatuses.includes(status)) {
      return res.status(400).json({ message: "ุญุงู„ุฉ ุบูŠุฑ ุตุงู„ุญุฉ" });
    }

    const invoice = await Invoice.findById(invoiceId);
    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    const currentStatus = invoice.restaurantStatus || "pending";
    const currentIndex = allowedStatuses.indexOf(currentStatus);
    const targetIndex = allowedStatuses.indexOf(status);

    if (currentIndex !== -1 && targetIndex < currentIndex) {
      return res.status(400).json({ message: "ู„ุง ูŠู…ูƒู† ุงู„ุฑุฌูˆุน ู„ุญุงู„ุฉ ุณุงุจู‚ุฉ" });
    }

    // DELIVERY VALIDATION BEFORE SHIPPING
    if (
      invoice.restaurantData?.orderType === "delivery" &&
      status === "shipped"
    ) {
      const driver = invoice.restaurantData?.driver;

      if (!driver?.driverId && !driver?.driverUserId) {
        return res.status(400).json({
          message: "ูŠุฌุจ ุชุนูŠูŠู† ุณุงุฆู‚ ู‚ุจู„ ุดุญู† ุทู„ุจ ุงู„ุชูˆุตูŠู„",
        });
      }
    }

    invoice.restaurantStatus = status;
    await invoice.save();

    if (
      status === "shipped" &&
      invoice.restaurantData?.orderType === "delivery" &&
      invoice.restaurantData?.driver?.driverId
    ) {
      const assignedDriver = await Driver.findOne({
        _id: invoice.restaurantData.driver.driverId,
        tenant: invoice.tenant,
        isActive: true,
      });

      if (assignedDriver) {
        assignedDriver.currentOrderIds = (assignedDriver.currentOrderIds || []).filter(
          (orderId) => orderId.toString() !== invoice._id.toString(),
        );
        assignedDriver.currentOrders = assignedDriver.currentOrderIds.length;
        assignedDriver.status = assignedDriver.currentOrders > 0 ? "busy" : "available";
        await assignedDriver.save();
      }
    }

    // RELEASE TABLE ONLY FOR NON-DINE-IN ORDERS.
    // A dine-in table must ONLY be released computationally when remainingAmount reaches 0 during Payment!
    const isDineIn = invoice.restaurantData?.orderType === "dine-in";
    if (
      invoice.restaurantData?.table && !isDineIn &&
      (status === "shipped" || status === "ready_for_delivery")
    ) {
      await Table.findByIdAndUpdate(invoice.restaurantData.table, {
        status: "available",
        currentOrderId: null,
      });
    }

    // WHATSAPP NOTIFICATION
    // Delivery orders: only send "preparing" and "shipped" โ€” skip "ready_for_delivery"
    //   because that message implies the customer should come pick up, which is wrong for delivery.
    // Takeaway orders: send "preparing", "ready_for_delivery", "shipped"
    // Dine-in orders: send "preparing" and "ready_for_delivery" (dine-in-ready template)
    const orderType = invoice.restaurantData?.orderType;
    const isEligible =
      (orderType === "delivery" && (status === "preparing" || status === "shipped")) ||
      (orderType === "takeaway" && (status === "preparing" || status === "ready_for_delivery" || status === "shipped")) ||
      (isDineIn && (status === "preparing" || status === "ready_for_delivery"));
    let phoneNumber = null
    if (isEligible) {
      try {
        phoneNumber = invoice.restaurantData?.guestInfo?.phone;
        if (!phoneNumber && invoice.customer) {
          const customer = await Customer.findById(invoice.customer);
          phoneNumber = customer?.phone || null;
        }

        if (phoneNumber) {
          const tenant = await Tenant.findById(invoice.tenant).select("name");

          const restaurantName = tenant?.name || "";

          const itemsList = (invoice.items || [])
            .map((i) => `- ${i.name} ร— ${i.quantity}`)
            .join("\n");

          const driver = invoice.restaurantData?.driver || {};
          const driverName = driver.driverName || "";
          const driverPhone = driver.driverPhone || "";

          // โœ… Use dine-in-ready for dine-in ready_for_delivery status
          const notificationType =
            isDineIn && status === "ready_for_delivery"
              ? "dine-in-ready"
              : status;

          const totalFormatted = `${invoice.totalAmount?.toFixed(2) || ""} ${invoice.tenant?.currency || ""}`;

          await WhatsAppService.queueNotification({
            tenant: invoice.tenant,
            order: invoice._id,
            customer: invoice.customer || null,
            phoneNumber,
            notificationType,
            orderNumber: invoice.invoiceNumber,
            restaurantName,
            total: totalFormatted,
            itemsList,
            driverName,
            driverPhone,
            language: "ar",
          });
        }
      } catch (err) {
        console.error("[WhatsApp] Notification failed:", {
          error: err.message,
          invoiceId,
          status,

          phoneNumber,
          notificationType: status,
        });
        // Don't fail the status update - just log the error
        // This ensures order status changes work even if WhatsApp fails
      }
    }

    return res.status(200).json({
      message: "ุชู… ุชุญุฏูŠุซ ุญุงู„ุฉ ุงู„ุทู„ุจ ุจู†ุฌุงุญ",
      invoice,
    });
  } catch (error) {
    return res.status(500).json({ message: error.message });
  }
};

export const assignRestaurantDriver = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const { driverUserId, driverId } = req.body;

    if (!driverUserId && !driverId) {
      return res.status(400).json({ message: "ู…ุนุฑู ุงู„ุณุงุฆู‚ ู…ุทู„ูˆุจ" });
    }

    const invoice = await Invoice.findById(invoiceId);
    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    if (invoice.restaurantData?.orderType !== "delivery") {
      return res
        .status(400)
        .json({ message: "ุชุนูŠูŠู† ุงู„ุณุงุฆู‚ ู…ุชุงุญ ูู‚ุท ู„ุทู„ุจุงุช ุงู„ุชูˆุตูŠู„" });
    }

    let resolvedDriver = null;
    let resolvedDriverMode = "user";

    // โœ… FIX 1: Check driver availability before assignment
    if (driverId) {
      resolvedDriver = await Driver.findOne({
        _id: driverId,
        tenant: invoice.tenant,
        isActive: true,
      });
      if (!resolvedDriver)
        return res.status(404).json({ message: "ุงู„ุณุงุฆู‚ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });

      // โœ… Check if driver is off-duty
      if (resolvedDriver.status === "off-duty") {
        return res.status(400).json({
          message: "ุงู„ุณุงุฆู‚ ุฎุงุฑุฌ ุงู„ุฎุฏู…ุฉ ุญุงู„ูŠุงู‹ - ุงู„ุญุงู„ุฉ: ุฎุงุฑุฌ ุงู„ุฎุฏู…ุฉ"
        });
      }

      // โœ… Check if driver is at max orders capacity
      if (
        !resolvedDriver.currentOrderIds.some(
          (orderId) => orderId.toString() === invoice._id.toString(),
        ) &&
        resolvedDriver.currentOrders >= resolvedDriver.maxOrders
      ) {
        return res.status(400).json({
          message: `ุงู„ุณุงุฆู‚ ูˆุตู„ ู„ู„ุญุฏ ุงู„ุฃู‚ุตู‰ ู…ู† ุงู„ุทู„ุจุงุช (${resolvedDriver.maxOrders} ุทู„ุจ)`
        });
      }

      // โœ… Only allow assignment if driver is available or busy (working)
      // Optionally warn if driver is already busy
      if (resolvedDriver.status === "busy") {
        // Still allow assignment but log warning
        console.warn(`โš ๏ธ Driver ${driverId} is busy but assigning additional order`);
      }

      resolvedDriverMode = "registry";
    } else {
      const userDriver = await User.findOne({
        _id: driverUserId,
        tenant: invoice.tenant,
        status: "active",
      });
      if (!userDriver)
        return res.status(404).json({ message: "ุงู„ุณุงุฆู‚ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
      resolvedDriver = {
        _id: null,
        name: userDriver.fullName || userDriver.username || "",
        phone: userDriver.phone || "",
      };
    }

    const previousDriverId = invoice.restaurantData?.driver?.driverId;
    if (
      previousDriverId &&
      (!driverId || previousDriverId.toString() !== driverId.toString())
    ) {
      const previousDriver = await Driver.findOne({
        _id: previousDriverId,
        tenant: invoice.tenant,
        isActive: true,
      });

      if (previousDriver) {
        previousDriver.currentOrderIds = (previousDriver.currentOrderIds || []).filter(
          (orderId) => orderId.toString() !== invoice._id.toString(),
        );
        previousDriver.currentOrders = previousDriver.currentOrderIds.length;
        previousDriver.status = previousDriver.currentOrders > 0 ? "busy" : "available";
        await previousDriver.save();
      }
    }

    if (resolvedDriverMode === "registry") {
      const alreadyAssigned = (resolvedDriver.currentOrderIds || []).some(
        (orderId) => orderId.toString() === invoice._id.toString(),
      );
      if (!alreadyAssigned) {
        resolvedDriver.currentOrderIds = [...(resolvedDriver.currentOrderIds || []), invoice._id];
      }
      resolvedDriver.currentOrders = resolvedDriver.currentOrderIds.length;
      // โœ… Set status to busy when orders are assigned
      resolvedDriver.status = resolvedDriver.currentOrders > 0 ? "busy" : "available";
      await resolvedDriver.save();
    }

    invoice.restaurantData = invoice.restaurantData || {};
    invoice.restaurantData.driver = {
      driverId: driverId ? resolvedDriver._id : null,
      driverUserId: driverId ? null : driverUserId,
      driverName: resolvedDriver.name || "",
      driverPhone: resolvedDriver.phone || "",
      assignedAt: new Date(),
      // โœ… Track driver status at assignment time
      driverStatus: resolvedDriver.status || "available",
    };

    await invoice.save();

    res.status(200).json({
      message: "ุชู… ุชุนูŠูŠู† ุงู„ุณุงุฆู‚ ุจู†ุฌุงุญ",
      invoice,
      driverInfo: {
        name: resolvedDriver.name,
        phone: resolvedDriver.phone,
        status: resolvedDriver.status,
        currentOrders: resolvedDriver.currentOrders,
        maxOrders: resolvedDriver.maxOrders,
      }
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export const autoAssignRestaurantDriver = async (req, res) => {
  try {
    const { invoiceId } = req.params;

    const invoice = await Invoice.findById(invoiceId);
    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    if (invoice.restaurantData?.orderType !== "delivery") {
      return res
        .status(400)
        .json({ message: "ุงู„ุชุนูŠูŠู† ุงู„ุชู„ู‚ุงุฆูŠ ู…ุชุงุญ ูู‚ุท ู„ุทู„ุจุงุช ุงู„ุชูˆุตูŠู„" });
    }

    // Prefer Driver registry first (POS drivers), fallback to cashier-as-driver if none exist.
    const driver =
      (await Driver.findOne({
        tenant: invoice.tenant,
        isActive: true,
        status: "available",
        $expr: { $lt: ["$currentOrders", "$maxOrders"] },
        ...(invoice.branch ? { branch: invoice.branch } : {}),
      }).sort({ createdAt: 1 })) ||
      (await User.findOne({
        tenant: invoice.tenant,
        status: "active",
        role: "cashier",
        ...(invoice.branch ? { assignedBranch: invoice.branch } : {}),
      }).sort({ createdAt: 1 }));

    if (!driver) {
      return res
        .status(404)
        .json({ message: "ู„ุง ูŠูˆุฌุฏ ุณุงุฆู‚ ู…ุชุงุญ ู„ู„ุชุนูŠูŠู† ุงู„ุชู„ู‚ุงุฆูŠ" });
    }

    invoice.restaurantData = invoice.restaurantData || {};

    if (driver instanceof Driver) {
      const alreadyAssigned = (driver.currentOrderIds || []).some(
        (orderId) => orderId.toString() === invoice._id.toString(),
      );
      if (!alreadyAssigned) {
        driver.currentOrderIds = [...(driver.currentOrderIds || []), invoice._id];
      }
      driver.currentOrders = driver.currentOrderIds.length;
      driver.status = driver.currentOrders > 0 ? "busy" : "available";
      await driver.save();

      invoice.restaurantData.driver = {
        driverId: driver._id,
        driverUserId: null,
        driverName: driver.name || "",
        driverPhone: driver.phone || "",
        assignedAt: new Date(),
      };
    } else {
      invoice.restaurantData.driver = {
        driverId: null,
        driverUserId: driver._id,
        driverName: driver.fullName || driver.username || "",
        driverPhone: driver.phone || "",
        assignedAt: new Date(),
      };
    }

    await invoice.save();

    res
      .status(200)
      .json({ message: "ุชู… ุงู„ุชุนูŠูŠู† ุงู„ุชู„ู‚ุงุฆูŠ ู„ู„ุณุงุฆู‚ ุจู†ุฌุงุญ", invoice });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export const createWalkInCashSale = async (req, res) => {
  let createdCustomer = null;
  try {
    const tenantId = req.user.tenant?._id;
    // โœ… FETCH TENANT FIRST to get tax settings
    const tenant = await Tenant.findById(tenantId);
    const taxRate = tenant?.settings?.taxRate || 14;
    const taxEnabled = tenant?.settings?.taxEnabled ?? true;
    const branch = await resolveBranchForWrite(req);
    const branchId = branch._id;
    const {
      items,
      paidAmount,
      notes = "",
      customerId,
      customerName,
      customerPhone,
      discount = 0,
      tax = 0,
      restaurantData,
      serviceCharge = 0,
      deliveryCharge = 0,
    } = req.body;

    if (!tenantId) {
      return res
        .status(403)
        .json({ message: "ู„ุง ูŠูˆุฌุฏ ู…ุณุชุฃุฌุฑ ู…ุฑุชุจุท ุจู‡ุฐุง ุงู„ุญุณุงุจ" });
    }
    if (!Array.isArray(items) || items.length === 0) {
      return res.status(400).json({ message: "ูŠุฌุจ ุฅุถุงูุฉ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„" });
    }

    let finalCustomerId = customerId;
    if (!finalCustomerId && customerName) {
      const normalizedCustomerPhone = normalizeCustomerPhone(customerPhone);
      const normalizedCustomerName = normalizeCustomerName(customerName);
      const customerUpdate = {
        name: customerName.trim(),
        tenant: tenantId,
        branch: branchId,
        createdBy: req.user._id,
      };
      if (normalizedCustomerPhone) customerUpdate.phone = normalizedCustomerPhone;

      createdCustomer = await Customer.findOneAndUpdate(
        {
          tenant: tenantId,
          ...(normalizedCustomerPhone
            ? { phone: normalizedCustomerPhone }
            : {
              branch: branchId,
              isWalkIn: false,
              $or: [
                { normalizedName: normalizedCustomerName },
                { name: customerName.trim() },
              ],
            }),
        },
        { $setOnInsert: customerUpdate },
        { upsert: true, new: true, runValidators: true }
      );
      finalCustomerId = createdCustomer._id;
    }

    try {
      await validateCatalogItems(items, tenantId, branchId);
      await ensureStockAvailability(items, tenantId, branchId);

      let customer;
      if (finalCustomerId) {
        customer = await Customer.findOne({
          _id: finalCustomerId,
          tenant: tenantId,
          branch: branchId,
        });
        if (!customer) throw new Error("ุงู„ุนู…ูŠู„ ุงู„ู…ุญุฏุฏ ุบูŠุฑ ู…ูˆุฌูˆุฏ");
      } else {
        customer = await getOrCreateWalkInCustomer(
          tenantId,
          branchId,
          req.user._id,
        );
      }

      const invoice = new Invoice({
        tenant: tenantId,
        branch: branchId,
        customer: customer._id,
        issuedBy: req.user._id,
        notes: notes.trim(),
        discount: Math.max(Number(discount) || 0, 0),
        taxAmount: 0, // Will be calculated below
        serviceCharge: Math.max(Number(serviceCharge) || 0, 0),
        deliveryCharge: Math.max(Number(deliveryCharge) || 0, 0),
        restaurantData: restaurantData || null,
      });

      await applyInvoiceItemsAndStock(invoice, items, tenantId, branchId);

      // โœ… Calculate tax AFTER items are added
      if (
        taxEnabled &&
        invoice.restaurantData?.orderType === "dine-in"
      ) {
        const subtotal = invoice.items.reduce(
          (sum, item) => sum + (item.price * item.quantity),
          0
        );
        invoice.taxAmount = Math.round((subtotal * taxRate) / 100 * 100) / 100;
      } else {
        invoice.taxAmount = 0;
      }

      // Calculate totals
      invoice.calculateTotals();

      let saved = false;
      for (let i = 0; i < 3; i++) {
        try {
          invoice.invoiceNumber = await generateInvoiceNumber(
            tenantId,
            branchId,
          );
          invoice.calculateTotals();
          await invoice.save();
          saved = true;
          break;
        } catch (saveErr) {
          if (saveErr.code === 11000 && i < 2) continue;
          throw saveErr;
        }
      }
      if (!saved) throw new Error("ุชุนุฐุฑ ุญูุธ ุงู„ูุงุชูˆุฑุฉ ู„ุฎุทุฃ ุชุฒุงู…ู† ุจุงู„ุฑู‚ู…");

      // Sales-tenant walk-in must remain cash-in-full only
      const isRestaurantOrder = !!restaurantData?.orderType;
      const paymentType = req.body.paymentType || "full";
      const paymentAmount = Number(paidAmount || 0);

      if (!isRestaurantOrder && (customer?.isWalkIn || !customerName)) {
        // Traditional walk-in (no specific customer profile provided): must pay full amount in cash
        if (
          !paymentAmount ||
          Math.abs(paymentAmount - invoice.totalAmount) > 0.01
        ) {
          throw new Error(
            "ูุงุชูˆุฑุฉ ุงู„ุฒุงุฆุฑ ูŠุฌุจ ุฃู† ุชูƒูˆู† ู†ู‚ุฏูŠุฉ ุจุงู„ูƒุงู…ู„ุŒ ูˆูŠุฌุจ ุฃู† ูŠุณุงูˆูŠ ุงู„ู…ุจู„ุบ ุงู„ู…ุฏููˆุน ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ",
          );
        }
      }

      // Record payment if amount > 0
      if (paymentAmount > 0) {
        const amountToRecord = Math.min(paymentAmount, invoice.totalAmount);
        invoice.payments.push({
          amount: amountToRecord,
          method: paymentType === "transfer" ? "transfer" : "cash",
          receivedBy: req.user._id,
          confirmed: true,
        });
      }
      // unpaid (ุขุฌู„) = no payment recorded, invoice stays "open"

      await invoice.save();

      // Record income only for cash/confirmed payments
      if (paymentAmount > 0) {
        await createIncomeForPayment({
          tenantId,
          branchId,
          invoice,
          customer,
          amount: Math.min(paymentAmount, invoice.totalAmount),
          userId: req.user._id,
          notes: isRestaurantOrder ? "Restaurant sale" : "Walk-in cash sale",
          paymentMethod: paymentType === "transfer" ? "transfer" : "cash",
        });
      }

      // โœ… Lock table if dine-in
      if (restaurantData?.orderType === "dine-in" && restaurantData?.table) {
        const tableCheck = await Table.findById(restaurantData.table);
        if (tableCheck && tableCheck.status !== "occupied") {
          await Table.findByIdAndUpdate(restaurantData.table, {
            status: "occupied",
            currentOrderId: invoice._id,
          });
        }
      }

      const populatedInvoice = await Invoice.findById(invoice._id).populate(
        "customer",
        "name isWalkIn phone",
      );

      // โœ… Return changeDue so frontend can display it
      const responseData = populatedInvoice.toObject();
      responseData.changeDue = Math.max(
        paymentAmount - Number(invoice.totalAmount),
        0
      );
      res.status(201).json(responseData);
    } catch (err) {
      if (createdCustomer)
        await Customer.deleteOne({ _id: createdCustomer._id });
      throw err;
    }
  } catch (err) {
    if (createdCustomer) await Customer.deleteOne({ _id: createdCustomer._id });
    res.status(err.statusCode || 500).json({ message: err.message });
  }
};

export const getInvoices = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 5;
    const skip = (page - 1) * limit;
    const search = req.query.search || "";
    const { tenantId, branchFilter } = await resolveScopedBranch(req);

    const query = { tenant: tenantId, ...branchFilter };
    if (search) {
      query.invoiceNumber = { $regex: search, $options: "i" };
    }
    if (req.query.method) {
      query["payments.method"] = req.query.method;
    }

    // Restaurant/Cafe filtering for restaurant management screens
    // - isRestaurant=true => only invoices with restaurantData.orderType set
    // - orderType=delivery|takeaway|dine-in => filter by restaurantData.orderType
    // - restaurantStatus=pending|preparing|ready_for_delivery|shipped => filter by Invoice.restaurantStatus
    const isRestaurant =
      String(req.query.isRestaurant || "").toLowerCase() === "true";
    if (isRestaurant) {
      query["restaurantData.orderType"] = { $ne: null };
    }

    if (req.query.orderType) {
      query["restaurantData.orderType"] = req.query.orderType;
    }

    if (req.query.restaurantStatus) {
      query.restaurantStatus = req.query.restaurantStatus;
    }
    if (req.query.excludeStatus) {
      const excluded = req.query.excludeStatus.split(",").map((s) => s.trim());
      query.restaurantStatus = { $nin: excluded };
    }

    const total = await Invoice.countDocuments(query);
    const invoices = await Invoice.find(query)
      .populate("customer")
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    res.status(200).json({
      data: invoices,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

export const getInvoicesByCustomer = async (req, res) => {
  try {
    const invoices = await Invoice.find({
      customer: req.params.customerId,
      tenant: req.user.tenant._id,
      ...(await resolveScopedBranch(req)).branchFilter,
    });

    res.json(invoices);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

export const getInvoiceById = async (req, res) => {
  try {
    const { id } = req.params;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: id,
      tenant: req.user.tenant._id,
      ...branchFilter,
    })
      .populate("customer", "name isWalkIn phone")
      .populate({
        path: "items.productId",
        select: "name price",
      })
      .populate({
        path: "items.catalogItemId",
        select: "name price",
      });

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    res.status(200).json(invoice);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export const updateInvoiceItem = async (req, res) => {
  try {
    const { invoiceId, itemId } = req.params;
    const { name, quantity, price } = req.body;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: req.user.tenant._id,
      ...branchFilter,
    }).populate("customer", "isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    const item = invoice.items.id(itemId);
    if (!item) {
      return res.status(404).json({ message: "ุจู†ุฏ ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
    }

    const newQuantity = Number(quantity);
    const newPrice = Number(price);

    if (!Number.isFinite(newQuantity) || newQuantity <= 0) {
      return res.status(400).json({ message: "ุงู„ูƒู…ูŠุฉ ุบูŠุฑ ุตุงู„ุญุฉ" });
    }

    if (!Number.isFinite(newPrice) || newPrice < 0) {
      return res.status(400).json({ message: "ุงู„ุณุนุฑ ุบูŠุฑ ุตุงู„ุญ" });
    }

    // =========================
    // HANDLE CATALOG ITEM
    // =========================
    if (item.type === "catalog" && item.catalogItemId) {
      const catalogItem = await CatalogItem.findOne({
        _id: item.catalogItemId,
        tenant: req.user.tenant._id,
        ...branchFilter,
      });

      if (!catalogItem) {
        return res.status(404).json({ message: "ุนู†ุตุฑ ุงู„ูƒุชุงู„ูˆุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
      }

      item.name = catalogItem.name;
      item.quantity = newQuantity;
      item.price = Number(catalogItem.price || 0);
      item.total = item.quantity * item.price;

      await invoice.save();

      return res.status(200).json({
        message: "ุชู… ุชุญุฏูŠุซ ุจู†ุฏ ุงู„ูƒุชุงู„ูˆุฌ ุจู†ุฌุงุญ",
        invoice,
      });
    }

    // =========================
    // HANDLE PRODUCT ITEM
    // =========================
    if (item.productId) {
      const oldQuantity = Number(item.quantity);
      const diff = newQuantity - oldQuantity;

      const product = await Product.findOne({
        _id: item.productId,
        tenant: req.user.tenant._id,
        ...branchFilter,
      });

      if (!product) {
        return res.status(404).json({ message: "ุงู„ู…ู†ุชุฌ ุงู„ู…ุฑุชุจุท ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
      }

      // If increasing quantity โ†’ check stock
      if (diff > 0 && product.stock < diff) {
        return res.status(400).json({
          message: "ุงู„ู…ุฎุฒูˆู† ุบูŠุฑ ูƒุงููŠ ู„ู„ุชุนุฏูŠู„",
        });
      }

      // FIXED STOCK UPDATE (IMPORTANT)
      if (diff !== 0) {
        await Product.findOneAndUpdate(
          {
            _id: item.productId,
            tenant: req.user.tenant._id,
            ...branchFilter,
          },
          { $inc: { stock: -diff } },
        );
      }
    }

    // =========================
    // APPLY CHANGES
    // =========================
    item.name = name;
    item.quantity = newQuantity;
    item.price = newPrice;
    item.total = newQuantity * newPrice;

    await invoice.save();

    return res.status(200).json({
      message: "ุชู… ุชุญุฏูŠุซ ุจู†ุฏ ุงู„ูุงุชูˆุฑุฉ ุจู†ุฌุงุญ",
      invoice,
    });
  } catch (error) {
    return res.status(500).json({ message: error.message });
  }
};

export const deleteInvoiceItem = async (req, res) => {
  try {
    const { invoiceId, itemId } = req.params;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: req.user.tenant._id,
      ...branchFilter,
    }).populate("customer", "isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    const item = invoice.items.id(itemId);
    if (!item) {
      return res.status(404).json({ message: "ุงู„ู…ู†ุชุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
    }

    // restore stock only for product items
    if (item.productId) {
      await Product.findOneAndUpdate(
        { _id: item.productId, tenant: req.user.tenant._id, ...branchFilter },
        { $inc: { stock: Number(item.quantity) } },
      );
    }

    // REMOVE TABLE LOGIC HERE (BUG FIX)

    item.deleteOne();
    await invoice.save();

    res.json(invoice);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

export const payInvoice = async (req, res) => {
  const session = await mongoose.startSession();
  session.startTransaction();

  try {
    const { invoiceId } = req.body;

    const {
      paymentMethod = "cash",
      transferType,
      customerName,
      customerPhone,
      releaseTable = false,
    } = req.body;

    let amount = Number(req.body.amount || 0);
    amount = roundMoney(amount);
    const { branchId, branchFilter } = await resolveScopedBranch(req);

    // โ”€ PAYMENT TYPE CHECKS โ”€
    const isCash = paymentMethod === "cash";
    const isPartial = paymentMethod === "partial";
    const isDebt = paymentMethod === "unpaid";
    const isTransfer = paymentMethod === "transfer";

    // โ”€ 1. BASIC VALIDATION โ”€
    if (!isDebt && amount <= 0) {
      return res.status(400).json({ message: "ูŠุฌุจ ุฅุฏุฎุงู„ ู…ุจู„ุบ ุตุญูŠุญ" });
    }

    if (isTransfer && !ALLOWED_TRANSFER_TYPES.includes(transferType)) {
      return res.status(400).json({ message: "ู†ูˆุน ุงู„ุชุญูˆูŠู„ ุบูŠุฑ ุตุญูŠุญ" });
    }

    // โ”€ 2. FIND INVOICE โ”€
    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: req.user.tenant._id,
      ...branchFilter,
    })
      .populate("customer", "name isWalkIn phone")
      .session(session);

    if (!invoice) {
      return res.status(404).json({ message: "ู„ุง ุชูˆุฌุฏ ูุงุชูˆุฑุฉ ู†ุดุทุฉ" });
    }

    // โ”€ 3. BUSINESS RULES โ”€
    const isRestaurantOrder = !!invoice.restaurantData?.orderType;
    if (isRestaurantOrder && isCash && amount < invoice.remainingAmount) {
      return res.status(400).json({ message: "ุงู„ุฏูุน ุงู„ู†ู‚ุฏูŠ ูŠุฌุจ ุฃู† ูŠูƒูˆู† ูƒุงู…ู„ุงู‹" });
    }

    if (isDebt && amount > 0) {
      return res.status(400).json({ message: "ุงู„ุขุฌู„ ู„ุง ูŠุณู…ุญ ุจุฃูŠ ู…ุจู„ุบ ู…ุฏููˆุน" });
    }

    if (isPartial && amount >= invoice.remainingAmount) {
      return res.status(400).json({ message: "ุงู„ู…ุจู„ุบ ุงู„ุฌุฒุฆูŠ ูŠุฌุจ ุฃู† ูŠูƒูˆู† ุฃู‚ู„ ู…ู† ุงู„ุฅุฌู…ุงู„ูŠ" });
    }

    // โ”€ 4. CUSTOMER BINDING VALIDATION โ”€
    const isWalkIn = invoice.customer?.isWalkIn === true;

    if (isWalkIn && !isCash) {
      // Non-cash payments on walk-in REQUIRE customer data
      if (!customerName?.trim() || !customerPhone?.trim()) {
        return res.status(400).json({
          message: "ูŠุฌุจ ุฅุฏุฎุงู„ ุจูŠุงู†ุงุช ุงู„ุนู…ูŠู„ ู„ู„ุฏูุน ุงู„ุขุฌู„ ุฃูˆ ุงู„ุชุญูˆูŠู„"
        });
      }
    }

    // โ”€ 5. CUSTOMER BINDING (UPSERT/LINK) โ”€
    const settlementCustomer = await bindSettlementCustomer({
      tenantId: req.user.tenant._id,
      branchId,
      userId: req.user._id,
      customerName,
      customerPhone,
      fallbackCustomerId: invoice.customer?._id || invoice.customer || null,
      session,
    });

    if (settlementCustomer && (!invoice.customer ||
      (invoice.customer._id?.toString?.() || invoice.customer.toString()) !== settlementCustomer._id.toString())) {
      invoice.customer = settlementCustomer._id;
    }

    // โ”€ 6. REGISTER PAYMENT โ”€
    if (amount > 0) {
      invoice.payments.push({
        amount,
        method: paymentMethod,
        transferType: isTransfer ? transferType : null,
        receivedBy: req.user._id,
        settledBy: req.user._id,          // โœ“ NEW
        settledAt: new Date(),            // โœ“ NEW
        confirmed: isCash,
        branchId: branchId,               // โœ“ NEW
      });
    }

    // โ”€ 7. SAVE INVOICE โ”€
    await invoice.save({ session });

    // โ”€ 8. INCOME LOGIC โ”€
    if (isCash && amount > 0) {
      await createIncomeForPayment({
        tenantId: req.user.tenant._id,
        branchId: branchId,
        invoice,
        customer: invoice.customer,
        amount,
        userId: req.user._id,
        paymentMethod,
        transferType,
      });
    }

    // โ”€ 9. TABLE RELEASE (TRANSACTIONAL) โ”€
    if ((invoice.remainingAmount <= 0 || releaseTable) &&
      invoice.restaurantData?.orderType === "dine-in") {
      await Table.findByIdAndUpdate(
        invoice.restaurantData.table,
        {
          status: "available",
          currentOrderId: null,
          freedAt: new Date(),
          freedBy: req.user._id,
        },
        { session }
      );
    }

    // โ”€ 10. COMMIT โ”€
    await session.commitTransaction();
    res.json(invoice);

  } catch (err) {
    await session.abortTransaction();
    res.status(500).json({ message: err.message });
  } finally {
    session.endSession();
  }
};

export const confirmPayment = async (req, res) => {
  try {
    const { invoiceId, paymentIndex } = req.params;
    const tenantId = req.user.tenant._id;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    }).populate("customer", "name isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    const payment = invoice.payments[paymentIndex];
    if (!payment) {
      return res.status(404).json({ message: "ุงู„ุฏูุน ุบูŠุฑ ู…ูˆุฌูˆุฏ" });
    }

    if (payment.method !== "transfer") {
      return res
        .status(400)
        .json({ message: "ูู‚ุท ุฏูุนุงุช ุงู„ุชุญูˆูŠู„ ุชุญุชุงุฌ ุฅู„ู‰ ุชุฃูƒูŠุฏ" });
    }

    payment.confirmed = !payment.confirmed;
    if (payment.confirmed) {
      payment.confirmedBy = req.user._id;
      payment.confirmedAt = new Date();

      // Create income records now that the transfer is confirmed
      await createIncomeForPayment({
        tenantId,
        branchId: invoice.branch || null,
        invoice,
        customer: invoice.customer,
        amount: payment.amount,
        userId: req.user._id,
        paymentMethod: "transfer",
        transferType: payment.transferType,
        date: payment.confirmedAt,
      });
    } else {
      payment.confirmedBy = null;
      payment.confirmedAt = null;

      // Remove income records for this unconfirmed transfer
      await Income.deleteMany({
        tenant: tenantId,
        sourceType: "invoice_payment",
        relatedInvoice: invoice._id,
        paymentMethod: "transfer",
        amount: payment.amount,
      });
    }

    await invoice.save();
    res.json(invoice);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

export const updateInvoice = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const {
      items,
      discount,
      tax,
      notes,
      serviceCharge,
      deliveryCharge,
    } = req.body;
    const tenantId = req.user.tenant._id;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    }).populate("customer", "isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "Invoice not found" });
    }

    // Reverse stock for existing product items
    for (const oldItem of invoice.items) {
      if (oldItem.productId) {
        await Product.findOneAndUpdate(
          { _id: oldItem.productId, tenant: tenantId, ...branchFilter },
          { $inc: { stock: Number(oldItem.quantity) } },
        );
      }
    }

    // Clear old items and add new items directly
    invoice.items = [];
    for (const item of items) {
      const quantity = Number(item.quantity || 0);
      const price = Number(item.price || 0);

      // Deduct stock for product items
      if (item.productId) {
        await Product.findOneAndUpdate(
          { _id: item.productId, tenant: tenantId, ...branchFilter },
          { $inc: { stock: -quantity } },
        );
      }

      const newItem = {
        name: item.name,
        quantity,
        price,
        total: quantity * price,
        type: item.type || "product",
        productId: item.productId || null,
        catalogItemId: item.catalogItemId || null,
        serviceId: item.serviceId || null,
      };

      invoice.items.push(newItem);
    }

    // Update fields
    invoice.discount = Math.max(Number(discount) || 0, 0);
    invoice.taxAmount = Math.max(Number(tax) || 0, 0);
    invoice.serviceCharge = Math.max(Number(serviceCharge) || invoice.serviceCharge || 0, 0);
    invoice.deliveryCharge = Math.max(Number(deliveryCharge) || invoice.deliveryCharge || 0, 0);
    
    if (notes !== undefined) invoice.notes = notes.trim();

    invoice.calculateTotals();
    await invoice.save();

    res.json(invoice);
  } catch (err) {
    res.status(err.statusCode || 500).json({ message: err.message });
  }
};

export const deleteInvoice = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const tenantId = req.user.tenant._id;
    const { branchFilter } = await resolveScopedBranch(req);

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    }).populate("customer", "isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "Invoice not found" });
    }

    // Restore stock for product items
    for (const item of invoice.items) {
      if (item.productId) {
        await Product.findOneAndUpdate(
          { _id: item.productId, tenant: tenantId, ...branchFilter },
          { $inc: { stock: Number(item.quantity) } },
        );
      }
    }

    // Delete related income records
    await Income.deleteMany({
      tenant: tenantId,
      sourceType: "invoice_payment",
      relatedInvoice: invoice._id,
    });

    // Delete the invoice
    await Invoice.findByIdAndDelete(invoiceId);

    res.json({ message: "Invoice deleted successfully" });
  } catch (err) {
    res.status(err.statusCode || 500).json({ message: err.message });
  }
};

// โ”€โ”€โ”€ OPEN TAB: Add items to an existing open invoice โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// Feature #4: Restaurant Open Tab System
// Allows a cafรฉ/restaurant to add more items to an in-progress dine-in order
// without creating a new invoice. Called from TableSettleModal > "Add Items" tab.
export const addItemsToOpenTab = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const { items } = req.body;
    const tenantId = req.user?.tenant?._id;
    // โœ… FETCH TENANT FIRST to get tax settings
    const tenant = await Tenant.findById(tenantId);
    const taxRate = tenant?.settings?.taxRate || 14;
    const taxEnabled = tenant?.settings?.taxEnabled ?? true;

    const { branchFilter } = await resolveScopedBranch(req);

    if (!items || !Array.isArray(items) || items.length === 0) {
      return res.status(400).json({ message: "ูŠุฌุจ ุฅุฑุณุงู„ ู‚ุงุฆู…ุฉ ุงู„ุฃุตู†ุงู" });
    }

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    });

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    // Only open/partial invoices can receive more items, EXCEPT for active dine-in tables
    // A dine-in table might have been paid in advance, but the customer wants to add more items.
    const isDineIn = invoice.restaurantData?.orderType === "dine-in";
    if (!["open", "partial", "paid"].includes(invoice.status) && !isDineIn) {
      return res.status(400).json({
        message: "ู„ุง ูŠู…ูƒู† ุฅุถุงูุฉ ุฃุตู†ุงู ู„ูุงุชูˆุฑุฉ ู…ุบู„ู‚ุฉ",
      });
    }

    // Process each new item โ€” handle stock if productId is provided
    for (const item of items) {
      const quantity = Number(item.quantity || 1);
      const price = Number(item.price || 0);

      if (!item.name || quantity <= 0) continue;

      // Deduct stock for product items
      if (item.productId) {
        const product = await Product.findOne({
          _id: item.productId,
          tenant: tenantId,
          ...branchFilter,
        });

        if (product && product.stock < quantity) {
          return res.status(400).json({
            message: `ุงู„ู…ุฎุฒูˆู† ุบูŠุฑ ูƒุงูู ู„ู„ู…ู†ุชุฌ: ${item.name}`,
          });
        }

        if (product) {
          await Product.findOneAndUpdate(
            { _id: item.productId, tenant: tenantId, ...branchFilter },
            { $inc: { stock: -quantity } }
          );
        }
      }

      // โ”€โ”€ Merge with existing item if same identity, otherwise push new โ”€โ”€
      const normalizedType = item.type || "catalog";
      const existingItem = invoice.items.find((existing) => {
        if (item.catalogItemId && existing.catalogItemId) {
          return existing.catalogItemId?.toString() === item.catalogItemId?.toString();
        }
        if (item.productId && existing.productId) {
          return existing.productId?.toString() === item.productId?.toString();
        }
        // Fallback: match by name + type for manual/service items
        return (
          existing.name === String(item.name).trim() &&
          existing.type === normalizedType
        );
      });

      if (existingItem) {
        existingItem.quantity += quantity;
        existingItem.total = existingItem.quantity * existingItem.price;
      } else {
        invoice.items.push({
          name: String(item.name).trim(),
          quantity,
          price,
          total: quantity * price,
          type: normalizedType,
          productId: item.productId || null,
          catalogItemId: item.catalogItemId || null,
        });
      }
    }

    // โœ… Recalculate tax using dynamic rate AFTER all items are added
    if (
      taxEnabled &&
      invoice.restaurantData?.orderType === "dine-in"
    ) {
      const subtotal = invoice.items.reduce(
        (sum, item) => sum + (item.price * item.quantity),
        0
      );
      invoice.taxAmount = Math.round((subtotal * taxRate) / 100 * 100) / 100;
    } else {
      invoice.taxAmount = 0;
    }

    invoice.calculateTotals();
    await invoice.save();

    res.status(200).json({
      message: "ุชู… ุฅุถุงูุฉ ุงู„ุฃุตู†ุงู ู„ู„ุทู„ุจ ุงู„ู‚ุงุฆู… ุจู†ุฌุงุญ",
      invoice,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

// โœ… NEW: Record payment received from driver for delivery orders
// This ensures income is only recorded when driver actually brings the money
export const recordDriverPayment = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const { amount, notes = "" } = req.body;
    const tenantId = req.user.tenant._id;
    const { branchId, branchFilter } = await resolveScopedBranch(req);

    // Validate amount
    if (!amount || Number(amount) <= 0) {
      return res.status(400).json({
        message: "ูŠุฌุจ ุฅุฏุฎุงู„ ู…ุจู„ุบ ู…ูˆุฌุจ",
      });
    }

    // Find invoice
    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    }).populate("customer", "isWalkIn");

    if (!invoice) {
      return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    // Verify it's a delivery order
    if (invoice.restaurantData?.orderType !== "delivery") {
      return res.status(400).json({
        message: "ุชุณุฌูŠู„ ุฏูุน ุงู„ุณุงุฆู‚ ู…ุชุงุญ ูู‚ุท ู„ุทู„ุจุงุช ุงู„ุชูˆุตูŠู„",
      });
    }

    // Verify a driver is assigned
    if (!invoice.restaurantData?.driver?.driverId && !invoice.restaurantData?.driver?.driverUserId) {
      return res.status(400).json({
        message: "ู„ุง ูŠูˆุฌุฏ ุณุงุฆู‚ ู…ุนูŠู‘ู† ู„ู‡ุฐู‡ ุงู„ูุงุชูˆุฑุฉ",
      });
    }

    const paymentAmount = Number(amount);
    if (paymentAmount > invoice.totalAmount) {
      return res.status(400).json({
        message: `ู„ุง ูŠู…ูƒู† ุฃู† ูŠุชุฌุงูˆุฒ ุงู„ู…ุจู„ุบ ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ (${invoice.totalAmount})`,
      });
    }

    // โœ… Record driver payment in the driver payment field
    invoice.restaurantData.driver.paymentReceived = {
      amount: paymentAmount,
      receivedAt: new Date(),
      receivedBy: req.user._id,
      notes: notes.trim(),
    };

    // โœ… Also add to invoice payments to track it
    invoice.payments.push({
      amount: paymentAmount,
      method: "cash",
      receivedBy: req.user._id,
      confirmed: true,
      date: new Date(),
    });

    await invoice.save();

    // โœ… NOW create income records (only when driver payment is actually received)
    await createIncomeForPayment({
      tenantId,
      branchId: invoice.branch || branchId || null,
      invoice,
      customer: invoice.customer,
      amount: paymentAmount,
      userId: req.user._id,
      notes: `ุฏูุน ุงู„ุณุงุฆู‚ - ${invoice.invoiceNumber} ${notes ? `- ${notes}` : ""}`,
      paymentMethod: "cash",
      date: new Date(),
    });

    res.status(200).json({
      status: "success",
      message: `ุชู… ุชุณุฌูŠู„ ุฏูุน ุงู„ุณุงุฆู‚ ุจู†ุฌุงุญ - ${paymentAmount} ุฑูŠุงู„`,
      invoice,
      driverPayment: invoice.restaurantData.driver.paymentReceived,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
// SPLIT BILL โ€” Pay for selected items only
// Called when one person at a shared table wants to settle their own items.

export const splitPayItems = async (req, res) => {
  const session = await mongoose.startSession();
  session.startTransaction();

  try {
    const { invoiceId } = req.params;
    const {
      itemIds,
      paymentMethod = "cash",
      transferType = null,
      customerName,
      customerPhone,
      amount,
      taxRate = 14,
    } = req.body;

    const tenantId = req.user.tenant._id;
    const { branchId, branchFilter } = await resolveScopedBranch(req);

    // โ”€โ”€ Validate inputs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (!itemIds || !Array.isArray(itemIds) || itemIds.length === 0) {
      return res
        .status(400)
        .json({ message: "ูŠุฌุจ ุชุญุฏูŠุฏ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„ ู„ู„ุฏูุน" });
    }

    const invoice = await Invoice.findOne({
      _id: invoiceId,
      tenant: tenantId,
      ...branchFilter,
    }).populate("customer", "isWalkIn name phone").session(session);

    if (!invoice) {
        await session.abortTransaction();
        return res.status(404).json({ message: "ุงู„ูุงุชูˆุฑุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ" });
    }

    if (invoice.status === "cancelled") {
        await session.abortTransaction();
        return res.status(400).json({ message: "ู„ุง ูŠู…ูƒู† ุงู„ุฏูุน ู„ูุงุชูˆุฑุฉ ู…ู„ุบุงุฉ" });
    }

    // โ”€โ”€ Identify items and quantities to split โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    let itemsToSplit = [];
    if (req.body.splitItems && Array.isArray(req.body.splitItems)) {
        // New format: [{ itemId, quantity }]
        itemsToSplit = req.body.splitItems;
    } else if (itemIds && Array.isArray(itemIds)) {
        // Legacy/Full-split format: [itemId, itemId]
        itemsToSplit = itemIds.map(id => ({ itemId: id, quantity: null })); // null means "take all"
    }

    if (itemsToSplit.length === 0) {
        await session.abortTransaction();
        return res.status(400).json({ message: "ูŠุฌุจ ุชุญุฏูŠุฏ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„ ู„ู„ุฏูุน" });
    }

    const selectedItemsForNewInvoice = [];
    
    for (const splitEntry of itemsToSplit) {
        const itemInOriginal = invoice.items.id(splitEntry.itemId);
        if (!itemInOriginal) continue;

        const qtyToSplit = splitEntry.quantity !== null && splitEntry.quantity !== undefined
            ? Math.min(Number(splitEntry.quantity), itemInOriginal.quantity)
            : itemInOriginal.quantity;

        if (qtyToSplit <= 0) continue;

        // Add to the list for the NEW invoice
        selectedItemsForNewInvoice.push({
            ...itemInOriginal.toObject(),
            quantity: qtyToSplit,
            total: roundMoney(qtyToSplit * itemInOriginal.price),
            _id: new mongoose.Types.ObjectId(), // New ID for the split item
        });

        // Update the ORIGINAL invoice item
        if (qtyToSplit >= itemInOriginal.quantity) {
            // Remove entirely
            itemInOriginal.deleteOne();
        } else {
            // Decrement quantity
            itemInOriginal.quantity -= qtyToSplit;
            itemInOriginal.total = roundMoney(itemInOriginal.quantity * itemInOriginal.price);
        }
    }

    if (selectedItemsForNewInvoice.length === 0) {
        await session.abortTransaction();
        return res.status(400).json({ message: "ุงู„ุฃุตู†ุงู ุงู„ู…ุญุฏุฏุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ ููŠ ุงู„ูุงุชูˆุฑุฉ" });
    }

    // โ”€โ”€ Calculate amounts for the split โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    const isDineIn = invoice.restaurantData?.orderType === "dine-in";
    const isTransfer = paymentMethod === "transfer";
    const effectiveTaxRate = isDineIn ? Math.max(0, Number(taxRate) || 0) : 0;

    const splitSubtotalRaw = selectedItemsForNewInvoice.reduce(
        (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
        0
    );
    const splitSubtotal = roundMoney(splitSubtotalRaw);
    const splitTax = roundMoney((splitSubtotalRaw * effectiveTaxRate) / 100);
    const splitTotal = roundMoney(splitSubtotal + splitTax);

    if (isTransfer && !ALLOWED_TRANSFER_TYPES.includes(transferType)) {
      await session.abortTransaction();
      return res.status(400).json({ message: "ู†ูˆุน ุงู„ุชุญูˆูŠู„ ุบูŠุฑ ุตุญูŠุญ" });
    }

    // โ”€โ”€ Validate payment amount โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    const isUnpaid = paymentMethod === "unpaid";
    const paymentAmount = isUnpaid ? 0 : roundMoney(amount);
    const customerRequired = paymentMethod === "unpaid" || paymentMethod === "transfer";

    if (customerRequired && (!customerName?.trim() || !customerPhone?.trim())) {
      await session.abortTransaction();
      return res.status(400).json({ message: "ูŠุฌุจ ุฅุฏุฎุงู„ ุงุณู… ุงู„ุนู…ูŠู„ ูˆุฑู‚ู… ุงู„ู‡ุงุชู" });
    }

    const settlementCustomer = await bindSettlementCustomer({
      tenantId,
      branchId: invoice.branch || branchId || null,
      userId: req.user._id,
      customerName,
      customerPhone,
      fallbackCustomerId: invoice.customer?._id || invoice.customer || null,
      session,
    });

    if (!isUnpaid) {
      if (!paymentAmount || paymentAmount <= 0) {
        await session.abortTransaction();
        return res.status(400).json({ message: "ูŠุฌุจ ุฅุฏุฎุงู„ ู…ุจู„ุบ ุตุญูŠุญ" });
      }
      if (paymentMethod === "cash" && paymentAmount < splitTotal) {
        await session.abortTransaction();
        return res.status(400).json({
          message: `ุงู„ู…ุจู„ุบ ุงู„ู…ุฏููˆุน (${paymentAmount}) ุฃู‚ู„ ู…ู† ุฅุฌู…ุงู„ูŠ ุงู„ุฃุตู†ุงู ุงู„ู…ุญุฏุฏุฉ (${splitTotal})`,
        });
      }
    }

    // โ”€โ”€ 1. Create a NEW Completed Invoice for the split items โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    const newInvoiceNumber = await generateInvoiceNumber(tenantId, invoice.branch || branchId);

    const splitInvoice = new Invoice({
      tenant: tenantId,
      branch: invoice.branch,
      customer: settlementCustomer?._id || invoice.customer,
      issuedBy: req.user._id,
      invoiceNumber: newInvoiceNumber, 
      items: selectedItemsForNewInvoice,
      taxAmount: splitTax,
      discount: 0,
      serviceCharge: 0,
      deliveryCharge: 0,
      restaurantData: {
          ...invoice.restaurantData,
          table: invoice.restaurantData?.table?._id || invoice.restaurantData?.table
      },
      status: isUnpaid ? 'open' : 'paid',
      notes: `ุฏูุน ุฌุฒุฆูŠ ู…ู† ูุงุชูˆุฑุฉ ${invoice.invoiceNumber}`
    });

    if (paymentAmount > 0) {
        splitInvoice.payments.push({
            amount: paymentAmount,
            method: paymentMethod,
            transferType: isTransfer ? transferType : null,
            receivedBy: req.user._id,
            confirmed: true,
            date: new Date(),
        });
    }

    splitInvoice.calculateTotals();
    await splitInvoice.save({ session });

    // โ”€โ”€ 2. Remove items from original invoice โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    invoice.items = invoice.items.filter(
      (item) => !itemIdSet.has(item._id.toString())
    );

    // Recalculate tax for remaining items
    if (isDineIn) {
      const remainingSubtotal = invoice.items.reduce(
        (sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0),
        0
      );
      invoice.taxAmount = roundMoney((remainingSubtotal * effectiveTaxRate) / 100);
    }

    invoice.calculateTotals();

    if (settlementCustomer && (!invoice.customer ||
      (invoice.customer._id?.toString?.() || invoice.customer.toString()) !== settlementCustomer._id.toString())) {
      invoice.customer = settlementCustomer._id;
    }

    await invoice.save({ session });

    // โ”€โ”€ 3. Create income record for the payment โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (paymentAmount > 0) {
      await createIncomeForPayment({
        tenantId,
        branchId: invoice.branch || branchId || null,
        invoice: splitInvoice, // Point to the new split invoice
        customer: settlementCustomer || invoice.customer,
        amount: paymentAmount,
        userId: req.user._id,
        notes: `ุฏูุน ุฌุฒุฆูŠ (ุชู‚ุณูŠู… ุงู„ุญุณุงุจ) โ€” ${invoice.invoiceNumber}`,
        paymentMethod,
        transferType,
        date: new Date(),
      });
    }

    // โ”€โ”€ 4. Release table if no items remain โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    const tableId = invoice.restaurantData?.table?._id || invoice.restaurantData?.table;
    if (invoice.items.length === 0 && tableId) {
      await Table.findByIdAndUpdate(tableId, {
        status: "available",
        currentOrderId: null,
      }, { session });
    }

    await session.commitTransaction();

    return res.status(200).json({
      message: "ุชู… ุณุฏุงุฏ ุงู„ุฃุตู†ุงู ุงู„ู…ุญุฏุฏุฉ ุจู†ุฌุงุญ โœ…",
      invoice, // Return the original updated invoice so UI refreshes
      split: {
        splitInvoiceId: splitInvoice._id,
        itemCount: selectedItems.length,
        subtotal: splitSubtotal,
        tax: splitTax,
        total: splitTotal,
        paid: paymentAmount,
      },
      tableReleased: invoice.items.length === 0,
    });
  } catch (err) {
    await session.abortTransaction();
    console.error("[splitPayItems]", err);
    res.status(err.statusCode || 500).json({ message: err.message });
  } finally {
    session.endSession();
  }
};