File size: 47,610 Bytes
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
 
 
 
 
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
 
 
 
0330133
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
 
 
 
 
 
 
 
 
 
0159174
 
 
 
 
 
 
 
 
c6a4aaf
 
 
 
 
 
 
 
 
0159174
c6a4aaf
0159174
 
 
c6a4aaf
0159174
 
c6a4aaf
 
 
 
0159174
ba7fcc6
 
 
 
 
 
 
 
 
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
ba7fcc6
 
 
 
 
 
 
 
 
 
0159174
 
 
 
ba7fcc6
0159174
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
 
0159174
ba7fcc6
0159174
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
 
 
 
ba7fcc6
0159174
 
ba7fcc6
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
0159174
 
 
ba7fcc6
 
 
 
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
 
 
 
 
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
 
 
 
 
 
 
0159174
ba7fcc6
 
0159174
ba7fcc6
0159174
 
 
 
ba7fcc6
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7fcc6
 
0330133
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6a4aaf
0159174
 
 
 
 
 
 
 
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
import mongoose from "mongoose";
import User from "../models/UserModel.js";
import Tenant from "../models/TenantModel.js";
import Branch from "../models/BranchModel.js";
import Product from "../models/ProductModel.js";
import Invoice from "../models/InvoiceModel.js";
import Income from "../models/IncomeModel.js";
import Expense from "../models/ExpenseModel.js";
import Customer from "../models/CustomerModel.js";
import Supplier from "../models/SupplierModel.js";
import SupplierInvoice from "../models/SupplierInvoiceModel.js";
import {
   buildTenantCredentialsWhatsApp,
   clearAuthCookie,
   createSessionToken,
   setAuthCookie,
   toSlug,
} from "../utils/authCookies.js";
import {
   DEFAULT_SUBSCRIPTION_PACKAGE,
   SUBSCRIPTION_PACKAGES,
   getPackageDetails,
   isUnlimitedCashierLimit,
   normalizePackageKey,
} from "../utils/subscriptionPackages.js";
import {
   buildBranchPayload,
   ensurePrimaryBranchForTenant,
   normalizeBranchCode,
} from "../utils/branchContext.js";

const getPaymentStatus = (tenant) => {
   if (!tenant) return "due";
   const nextDue = tenant.nextPaymentDueAt ? new Date(tenant.nextPaymentDueAt) : null;
   if (!nextDue) return "due";
   return nextDue < new Date() ? "overdue" : "due";
};

const formatCashierLimitLabel = (limit) =>
   isUnlimitedCashierLimit(limit) ? "Unlimited" : `${Number(limit || 0)}`;

const computeCashierUtilization = (tenant) => {
   const used = Number(tenant?.cashierAccountsCount || 0);
   const limit = tenant?.cashierLimit;
   if (isUnlimitedCashierLimit(limit)) {
      return null;
   }

   const numericLimit = Number(limit || 0);
   if (numericLimit <= 0) {
      return 0;
   }

   return Math.min(100, Math.round((used / numericLimit) * 100));
};

const sanitizeTenantPackage = (tenant) => {
   const details = getPackageDetails(tenant?.subscriptionPackage);
   const limit = tenant?.cashierLimit;
   return {
      key: details.key,
      label: details.label,
      cashierLimit: limit,
      cashierLimitLabel: formatCashierLimitLabel(limit),
   };
};

const sanitizeTenant = (tenant) => {
   if (!tenant) {
      return null;
   }

   const packageInfo = sanitizeTenantPackage(tenant);
   const cashierAccountsCount = Number(tenant.cashierAccountsCount || 0);
   const cashierUtilizationPercent = computeCashierUtilization(tenant);

   const branchCount = Number(tenant.branchCount || 1);
   const branchLimit = tenant.branchLimit ?? packageInfo.branchLimit ?? 1;
   const branchUtilizationPercent =
      branchLimit === null
         ? null
         : Math.min(100, Math.round((branchCount / branchLimit) * 100));

   return {
      _id: tenant._id,
      name: tenant.name,
      slug: tenant.slug,
      ownerName: tenant.ownerName,
      ownerEmail: tenant.ownerEmail,
      ownerPhone: tenant.ownerPhone,
      whatsappNumber: tenant.whatsappNumber,
      address: tenant.address,
      status: tenant.status,
      settings: tenant.settings,
      createdAt: tenant.createdAt,
      monthlyFeeAmount: tenant.monthlyFeeAmount || 800,
      monthlyFeeCurrency: tenant.monthlyFeeCurrency || "EGP",
      nextPaymentDueAt: tenant.nextPaymentDueAt || null,
      lastPaymentAt: tenant.lastPaymentAt || null,
      paymentsCount: Array.isArray(tenant.payments) ? tenant.payments.length : 0,
      paymentStatus: getPaymentStatus(tenant),
      subscriptionPackage: packageInfo,
      cashierAccountsCount,
      cashierUtilizationPercent,
      branchCount,
      branchLimit,
      branchUtilizationPercent,
      availableBranchSlots:
         branchLimit === null ? null : Math.max(0, branchLimit - branchCount),
      tenantTypes: Array.isArray(tenant.tenantTypes) ? tenant.tenantTypes : ["sales"],
   };
};

const sanitizeUser = (user) => ({
   _id: user._id,
   username: user.username,
   fullName: user.fullName,
   email: user.email,
   phone: user.phone,
   role: user.role,
   status: user.status,
   tenant: sanitizeTenant(user.tenant),
   assignedBranch: user.assignedBranch ? buildBranchPayload(user.assignedBranch) : null,
   createdAt: user.createdAt,
   lastLoginAt: user.lastLoginAt,
});

const resolveCashierBranchAssignment = async (tenantId, branchId, actorId) => {
   if (branchId) {
      const requested = await Branch.findOne({ _id: branchId, tenant: tenantId });
      if (!requested) {
         throw new Error("BRANCH_NOT_FOUND");
      }
      return requested;
   }

   return ensurePrimaryBranchForTenant(tenantId, actorId);
};

const createUniqueSlug = async (name) => {
   const baseSlug = toSlug(name) || "business";
   let slug = baseSlug;
   let counter = 1;

   while (await Tenant.findOne({ slug })) {
      counter += 1;
      slug = `${baseSlug}-${counter}`;
   }

   return slug;
};

const addOneMonth = (date) => {
   const next = new Date(date);
   next.setMonth(next.getMonth() + 1);
   return next;
};

const normalizeTenantSubscriptionState = async (tenant, session) => {
   if (!tenant) return null;

   let hasChanges = false;
   const normalizedPackage = normalizePackageKey(tenant.subscriptionPackage) || DEFAULT_SUBSCRIPTION_PACKAGE;
   if (tenant.subscriptionPackage !== normalizedPackage) {
      tenant.subscriptionPackage = normalizedPackage;
      hasChanges = true;
   }

   if (typeof tenant.cashierLimit === "undefined") {
      tenant.cashierLimit = getPackageDetails(normalizedPackage).cashierLimit;
      hasChanges = true;
   }

   if (typeof tenant.cashierAccountsCount === "undefined") {
      tenant.cashierAccountsCount = await User.countDocuments({
         tenant: tenant._id,
         role: "cashier",
      }).session(session);
      hasChanges = true;
   }

   if (hasChanges) {
      await tenant.save({ session });
   }

   return tenant;
};

const reserveCashierSlot = async (tenantId, session) => {
   const tenant = await normalizeTenantSubscriptionState(
      await Tenant.findById(tenantId).session(session),
      session
   );
   if (!tenant) {
      throw new Error("TENANT_NOT_FOUND");
   }

   if (isUnlimitedCashierLimit(tenant.cashierLimit)) {
      return tenant;
   }

   const updated = await Tenant.findOneAndUpdate(
      {
         _id: tenantId,
         cashierAccountsCount: { $lt: Number(tenant.cashierLimit || 0) },
      },
      { $inc: { cashierAccountsCount: 1 } },
      { new: true, session }
   );

   if (!updated) {
      throw new Error("CASHIER_LIMIT_REACHED");
   }

   return updated;
};

const releaseCashierSlot = async (tenantId, session) => {
   const tenant = await normalizeTenantSubscriptionState(
      await Tenant.findById(tenantId).session(session),
      session
   );

   if (!tenant) return null;

   return Tenant.findOneAndUpdate(
      {
         _id: tenantId,
         cashierAccountsCount: { $gt: 0 },
      },
      { $inc: { cashierAccountsCount: -1 } },
      { new: true, session }
   );
};

const buildTenantSearchFilter = ({ search, status, packageKey }) => {
   const filter = {};
   if (search) {
      filter.$or = [
         { name: { $regex: search, $options: "i" } },
         { slug: { $regex: search, $options: "i" } },
         { ownerName: { $regex: search, $options: "i" } },
         { ownerPhone: { $regex: search, $options: "i" } },
         { whatsappNumber: { $regex: search, $options: "i" } },
      ];
   }
   if (status) filter.status = status;
   if (packageKey) filter.subscriptionPackage = packageKey;
   return filter;
};

const hydrateTenantRowsForDisplay = async (tenants) => {
   return Promise.all(tenants.map((t) => normalizeTenantSubscriptionState(t)));
};

const buildTenantSummary = (rows, totalVisible, totalAll) => {
   const now = new Date();
   const thirtyDaysAgo = new Date(now.setDate(now.getDate() - 30));

   let totalCashiers = 0;
   let limitSum = 0;
   let nearLimitTenants = 0;
   let overLimitTenants = 0;
   let overduePayments = 0;
   let newTenantsLast30Days = 0;
   let activeTenants = 0;
   let suspendedTenants = 0;

   rows.forEach((t) => {
      totalCashiers += Number(t.cashierAccountsCount || 0);

      const isUnlimited = isUnlimitedCashierLimit(t.cashierLimit);
      if (!isUnlimited) {
         limitSum += Number(t.cashierLimit || 0);
      }

      const util = computeCashierUtilization(t);
      if (util !== null) {
         if (util >= 100) overLimitTenants++;
         else if (util >= 80) nearLimitTenants++;
      }

      if (getPaymentStatus(t) === "overdue") overduePayments++;
      if (new Date(t.createdAt) > thirtyDaysAgo) newTenantsLast30Days++;

      if (t.status === "active") activeTenants++;
      if (t.status === "suspended") suspendedTenants++;
   });

   let capacityUtilizationPercent = null;
   if (limitSum > 0) {
      capacityUtilizationPercent = Math.min(100, Math.round((totalCashiers / limitSum) * 100));
   }

   return {
      totalTenants: totalAll,
      totalVisibleTenants: totalVisible,
      totalCashiers,
      capacityUtilizationPercent,
      nearLimitTenants,
      overLimitTenants,
      overduePayments,
      newTenantsLast30Days,
      activeTenants,
      suspendedTenants,
   };
};

export const checkAdmin = async (req, res) => {
   try {
      const count = await User.countDocuments({ role: "super_admin" });
      res.status(200).json({ hasAdmin: count > 0 });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const setupAdmin = async (req, res) => {
   try {
      const count = await User.countDocuments({ role: "super_admin" });
      if (count > 0) {
         return res.status(400).json({ message: "تم إعداد حساب المسؤول مسبقاً" });
      }

      const body = req.body || {};
      const username = (body.username || "").trim() || "superadmin";
      const password = (body.password || "").trim() || "ChangeMe123!";
      const fullName = (body.fullName || "").trim() || "Platform Admin";
      const email = (body.email || "").trim().toLowerCase() || undefined;

      await User.create({
         username,
         password,
         fullName,
         email,
         role: "super_admin",
      });

      res.status(201).json({
         message: "تم إنشاء حساب المسؤول بنجاح",
         credentials: {
            username,
            password,
         },
      });
   } catch (err) {
      res.status(500).json({ message: err.message });
   }
};

export const login = async (req, res) => {
   try {
      const identifier = req.body.identifier?.trim() || req.body.username?.trim();
      const { password } = req.body;

      if (!identifier || !password) {
         return res.status(400).json({ message: "بيانات تسجيل الدخول مطلوبة" });
      }

      const users = await User.find({
         $or: [{ username: identifier }, { email: identifier.toLowerCase() }],
      }).populate("tenant assignedBranch");

      const matchedUsers = users.filter((candidate) => candidate.matchPassword(password));
      if (!matchedUsers.length) {
         // ✅ Increment failed attempts on all matched-by-username users
         await Promise.all(
            users.map(async (u) => {
               u.failedLoginAttempts = (u.failedLoginAttempts || 0) + 1;
               if (u.failedLoginAttempts >= 5) {
                  u.lockedUntil = new Date(Date.now() + 15 * 60 * 1000); // lock 15 min
               }
               await u.save();
            })
         );
         return res.status(401).json({ message: "خطأ في اسم المستخدم أو كلمة المرور" });
      }

      if (matchedUsers.length > 1) {
         return res.status(400).json({ message: "اسم المستخدم مكرر بين أكثر من شركة، استخدم البريد الإلكتروني لتسجيل الدخول" });
      }

      const user = matchedUsers[0];

      // Check if account is locked
      if (user.lockedUntil && user.lockedUntil > new Date()) {
         const minutesLeft = Math.ceil((user.lockedUntil - new Date()) / 60000);
         return res.status(403).json({
            message: `الحساب مقفل مؤقتاً بسبب محاولات متعددة، حاول بعد ${minutesLeft} دقيقة`
         });
      }

      // Check if account is locked
      if (user.status !== "active") {
         return res.status(403).json({ message: "هذا الحساب موقوف تواصل مع المسئول" });
      }

      if (user.tenant && user.tenant.status !== "active") {
         return res.status(403).json({ message: "تم تعليق حساب المستأجر تواصل مع المسئول" });
      }

      // Reset failed attempts on successful login
      user.failedLoginAttempts = 0;
      user.lockedUntil = null;

      const { token, expiresAt } = createSessionToken();
      if (["cashier"].includes(user.role)) {
         // New token overwrites old one → old device gets 401 on next request
         user.sessionToken = token;
         user.sessionTokenExpiresAt = expiresAt;
      }
      else {
         // owners/admins: just update token normally
         user.sessionToken = token;
         user.sessionTokenExpiresAt = expiresAt;
      }
      user.lastLoginAt = new Date();
      await user.save();
      setAuthCookie(res, token);

      res.status(200).json({
         message: "تم تسجيل الدخول بنجاح",
         user: sanitizeUser(user),
         token,
      });
   } catch (err) {
      res.status(500).json({ message: err.message });
   }
};

export const logout = async (req, res) => {
   try {
      if (req.user) {
         req.user.sessionToken = null;
         await req.user.save();
      }
      clearAuthCookie(res);
      res.status(200).json({ message: "تم تسجيل الخروج بنجاح" });
   } catch (err) {
      res.status(500).json({ message: err.message });
   }
};

export const getCurrentUser = async (req, res) => {
   try {
      if (!req.user) {
         return res.status(401).json({ message: "غير مصرح بالوصول" });
      }

      res.status(200).json({
         user: sanitizeUser(req.user),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getUsers = async (req, res) => {
   try {
      let filter = {};

      if (req.user.role === "super_admin") {
         filter = req.query.tenantId ? { tenant: req.query.tenantId } : { role: "super_admin" };
      } else {
         filter = { tenant: req.user.tenant._id };
      }

      const users = await User.find(filter).populate("tenant assignedBranch").sort({ createdAt: -1 });
      res.status(200).json(users.map(sanitizeUser));
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getBranches = async (req, res) => {
   if (!req.user?.tenant) {
      return res.status(403).json({ message: "Tenant access required" });
   }

   try {
      const tenantId = req.user.tenant._id;
      await ensurePrimaryBranchForTenant(tenantId, req.user._id);

      const query = { tenant: tenantId };
      if (req.user.role === "cashier") {
         query._id = req.user.assignedBranch?._id || req.user.assignedBranch;
      }

      const branches = await Branch.find(query).sort({ isPrimary: -1, createdAt: 1 });
      res.status(200).json({
         data: branches.map(buildBranchPayload),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const createBranch = async (req, res) => {
   if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "فقط إدارة الحساب يمكنها إنشاء فروع" });
   }

   try {
      const tenantId = req.user.tenant._id;
      const name = req.body.name?.trim();
      const address = req.body.address?.trim() || "";
      const managerName = req.body.manager?.trim() || "";
      const code = normalizeBranchCode(req.body.code || name);

      if (!name) {
         return res.status(400).json({ message: "اسم الفرع مطلوب" });
      }

      // ✅ Enforce branch limit
      const tenant = await Tenant.findById(tenantId);
      const pkg = getPackageDetails(tenant.subscriptionPackage);
      if (pkg.branchLimit !== null && tenant.branchCount >= pkg.branchLimit) {
         return res.status(403).json({
            message: `باقتك الحالية (${pkg.label}) تسمح بـ ${pkg.branchLimit} فرع فقط. يرجى الترقية لإضافة فروع جديدة.`,
         });
      }

      const existsByName = await Branch.findOne({ tenant: tenantId, name });
      if (existsByName) {
         return res.status(400).json({ message: "اسم الفرع مستخدم بالفعل" });
      }

      if (code) {
         const existsByCode = await Branch.findOne({ tenant: tenantId, code });
         if (existsByCode) {
            return res.status(400).json({ message: "كود الفرع مستخدم بالفعل" });
         }
      }

      const branch = await Branch.create({
         tenant: tenantId,
         name,
         code,
         address,
         managerName,
         isPrimary: false,
         createdBy: req.user._id,
      });

      // ✅ Increment branch count
      await Tenant.findByIdAndUpdate(tenantId, { $inc: { branchCount: 1 } });

      res.status(201).json({
         message: "تم إنشاء الفرع بنجاح",
         branch: buildBranchPayload(branch),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const updateBranch = async (req, res) => {
   if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "فقط إدارة الحساب يمكنها تعديل الفروع" });
   }

   try {
      const tenantId = req.user.tenant._id;
      const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
      if (!branch) {
         return res.status(404).json({ message: "الفرع غير موجود" });
      }

      if (typeof req.body.name === "string" && req.body.name.trim()) {
         const nextName = req.body.name.trim();
         const nameConflict = await Branch.findOne({ tenant: tenantId, name: nextName, _id: { $ne: branch._id } });
         if (nameConflict) {
            return res.status(400).json({ message: "اسم الفرع مستخدم بالفعل" });
         }
         branch.name = nextName;
      }

      if (typeof req.body.code === "string") {
         const nextCode = normalizeBranchCode(req.body.code);
         if (nextCode) {
            const codeConflict = await Branch.findOne({ tenant: tenantId, code: nextCode, _id: { $ne: branch._id } });
            if (codeConflict) {
               return res.status(400).json({ message: "كود الفرع مستخدم بالفعل" });
            }
         }
         branch.code = nextCode;
      }

      if (typeof req.body.address === "string") {
         branch.address = req.body.address.trim();
      }

      if (typeof req.body.manager === "string") {
         branch.managerName = req.body.manager.trim();
      }

      if (req.body.status && ["active", "suspended"].includes(req.body.status)) {
         if (branch.isPrimary && req.body.status === "suspended") {
            return res.status(400).json({ message: "لا يمكن إيقاف الفرع الرئيسي" });
         }
         branch.status = req.body.status;
      }

      await branch.save();
      res.status(200).json({
         message: "تم تحديث بيانات الفرع بنجاح",
         branch: buildBranchPayload(branch),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const deleteBranch = async (req, res) => {
   if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "فقط إدارة الحساب يمكنها حذف الفروع" });
   }

   try {
      const tenantId = req.user.tenant._id;
      const branch = await Branch.findOne({ _id: req.params.id, tenant: tenantId });
      if (!branch) {
         return res.status(404).json({ message: "الفرع غير موجود" });
      }
      if (branch.isPrimary) {
         return res.status(400).json({ message: "لا يمكن حذف الفرع الرئيسي" });
      }

      const [assignedUsers, products, customers, invoices, incomes, expenses, suppliers, supplierInvoices] = await Promise.all([
         User.countDocuments({ tenant: tenantId, assignedBranch: branch._id }),
         Product.countDocuments({ tenant: tenantId, branch: branch._id }),
         Customer.countDocuments({ tenant: tenantId, branch: branch._id }),
         Invoice.countDocuments({ tenant: tenantId, branch: branch._id }),
         Income.countDocuments({ tenant: tenantId, branch: branch._id }),
         Expense.countDocuments({ tenant: tenantId, branch: branch._id }),
         Supplier.countDocuments({ tenant: tenantId, branch: branch._id }),
         SupplierInvoice.countDocuments({ tenant: tenantId, branch: branch._id }),
      ]);

      const hasLinkedData =
         assignedUsers > 0 ||
         products > 0 ||
         customers > 0 ||
         invoices > 0 ||
         incomes > 0 ||
         expenses > 0 ||
         suppliers > 0 ||
         supplierInvoices > 0;

      if (hasLinkedData) {
         return res.status(400).json({ message: "لا يمكن حذف الفرع لوجود بيانات مرتبطة به (مستخدمين أو معاملات مالية)" });
      }

      await branch.deleteOne();
      await Tenant.findByIdAndUpdate(tenantId, { $inc: { branchCount: -1 } });

      res.status(200).json({ message: "تم حذف الفرع بنجاح" });
   }
   catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const createUser = async (req, res) => {
   if (!req.user?.tenant) {
      return res.status(403).json({ message: "إدارة المستخدمين الداخلية متاحة فقط داخل حسابات المستأجرين" });
   }

   if (!["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "فقط أدوار إدارة المستأجر يمكنها إنشاء مستخدمين" });
   }

   const username = req.body.username?.trim();
   const fullName = req.body.fullName?.trim() || username;
   const password = req.body.password?.trim();
   const email = req.body.email?.trim()?.toLowerCase() || undefined;
   const phone = req.body.phone?.trim() || "";
   const requestedBranchId = req.body.branchId || null;
   const role = "cashier";

   if (!username || !password) {
      return res.status(400).json({ message: "اسم المستخدم وكلمة المرور مطلوبان" });
   }

   try {
      const assignedBranch = await resolveCashierBranchAssignment(req.user.tenant._id, requestedBranchId, req.user._id);
      const session = await mongoose.startSession();
      let createdUser = null;

      try {
         await session.withTransaction(async () => {
            const usernameExists = await User.findOne({ username, tenant: req.user.tenant._id }).session(session);
            if (usernameExists) {
               throw new Error("USERNAME_EXISTS");
            }

            if (email) {
               const emailExists = await User.findOne({ email }).session(session);
               if (emailExists) {
                  throw new Error("EMAIL_EXISTS");
               }
            }

            await reserveCashierSlot(req.user.tenant._id, session);

            const users = await User.create(
               [
                  {
                     username,
                     fullName,
                     email,
                     phone,
                     password,
                     role,
                     tenant: req.user.tenant._id,
                     assignedBranch: assignedBranch._id,
                  },
               ],
               { session }
            );
            createdUser = users[0];
         });
      } finally {
         await session.endSession();
      }

      const user = await User.findById(createdUser._id).populate("tenant assignedBranch");

      res.status(201).json({
         message: "تم إنشاء المستخدم بنجاح",
         user: sanitizeUser(user),
      });
   } catch (err) {
      if (err.message === "USERNAME_EXISTS") {
         return res.status(400).json({ message: "اسم المستخدم مستخدم مسبقاً داخل هذه الشركة" });
      }
      if (err.message === "EMAIL_EXISTS") {
         return res.status(400).json({ message: "البريد الإلكتروني مستخدم بالفعل" });
      }
      if (err.message === "CASHIER_LIMIT_REACHED") {
         return res.status(400).json({ message: "لا يمكن إنشاء كاشير جديد، تم الوصول إلى الحد الأقصى للباقة" });
      }
      res.status(500).json({ message: err.message });
   }
};

export const deleteUser = async (req, res) => {
   if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "ليس لديك صلاحية حذف المستخدمين" });
   }

   if (req.user._id.toString() === req.params.id) {
      return res.status(400).json({ message: "لا يمكنك حذف حسابك النشط" });
   }

   try {
      const session = await mongoose.startSession();

      try {
         await session.withTransaction(async () => {
            const targetUser = await User.findOne({ _id: req.params.id, tenant: req.user.tenant._id }).session(session);
            if (!targetUser) {
               throw new Error("USER_NOT_FOUND");
            }
            if (targetUser.role === "owner") {
               throw new Error("OWNER_PROTECTED");
            }
            if (targetUser.role === "cashier") {
               await releaseCashierSlot(req.user.tenant._id, session);
            }
            await targetUser.deleteOne({ session });
         });
      } finally {
         await session.endSession();
      }

      res.status(200).json({ message: "تم حذف المستخدم بنجاح" });
   } catch (error) {
      if (error.message === "USER_NOT_FOUND") {
         return res.status(404).json({ message: "المستخدم غير موجود" });
      }
      if (error.message === "OWNER_PROTECTED") {
         return res.status(400).json({ message: "لا يمكن حذف حساب المالك من هذه الشاشة" });
      }
      res.status(500).json({ message: error.message });
   }
};

export const updateUser = async (req, res) => {
   if (!req.user?.tenant || !["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "ليس لديك صلاحية تعديل المستخدمين" });
   }

   try {
      const targetUser = await User.findOne({ _id: req.params.id, tenant: req.user.tenant._id }).populate("tenant assignedBranch");

      if (!targetUser) {
         return res.status(404).json({ message: "المستخدم غير موجود" });
      }

      if (targetUser.role === "owner") {
         return res.status(400).json({ message: "لا يمكن تعديل حساب المالك من هذه الشاشة" });
      }

      if (req.user.role === "admin" && targetUser.role !== "cashier") {
         return res.status(403).json({ message: "يمكن للمسؤول إدارة حسابات الكاشير فقط" });
      }

      if (req.user._id.toString() === targetUser._id.toString() && req.body.status === "suspended") {
         return res.status(400).json({ message: "لا يمكنك تعليق حسابك أثناء الجلسة النشطة" });
      }

      const incomingRole = req.body.role;
      const requestedBranchId = req.body.branchId || null;
      const assignedBranch = await resolveCashierBranchAssignment(req.user.tenant._id, requestedBranchId, req.user._id);
      if (incomingRole && incomingRole !== "cashier") {
         return res.status(400).json({ message: "يمكن إدارة حسابات الكاشير فقط داخل حسابات المستأجرين" });
      }

      const roleChanged = Boolean(incomingRole) && targetUser.role !== incomingRole;

      if (roleChanged) {
         const session = await mongoose.startSession();

         try {
            await session.withTransaction(async () => {
               const userInTransaction = await User.findOne({ _id: req.params.id, tenant: req.user.tenant._id }).session(session);
               if (!userInTransaction) {
                  throw new Error("USER_NOT_FOUND");
               }

               if (userInTransaction.role === "cashier" && incomingRole !== "cashier") {
                  await releaseCashierSlot(req.user.tenant._id, session);
               }

               if (userInTransaction.role !== "cashier" && incomingRole === "cashier") {
                  await reserveCashierSlot(req.user.tenant._id, session);
               }

               userInTransaction.role = incomingRole;

               if (req.body.status) {
                  if (!["active", "suspended"].includes(req.body.status)) {
                     throw new Error("INVALID_STATUS");
                  }
                  userInTransaction.status = req.body.status;
               }

               userInTransaction.fullName = req.body.fullName?.trim() || userInTransaction.fullName;
               userInTransaction.email = req.body.email?.trim()?.toLowerCase() || userInTransaction.email;
               userInTransaction.phone = req.body.phone?.trim() || userInTransaction.phone;
               userInTransaction.assignedBranch = assignedBranch._id;
               await userInTransaction.save({ session });
            });
         } finally {
            await session.endSession();
         }

         const refreshed = await User.findById(req.params.id).populate("tenant assignedBranch");
         return res.status(200).json({
            message: "تم تحديث بيانات المستخدم",
            user: sanitizeUser(refreshed),
         });
      }

      if (req.body.status) {
         if (!["active", "suspended"].includes(req.body.status)) {
            return res.status(400).json({ message: "حالة المستخدم غير صالحة" });
         }
         targetUser.status = req.body.status;
      }

      targetUser.fullName = req.body.fullName?.trim() || targetUser.fullName;
      targetUser.email = req.body.email?.trim()?.toLowerCase() || targetUser.email;
      targetUser.phone = req.body.phone?.trim() || targetUser.phone;
      targetUser.assignedBranch = assignedBranch._id;

      await targetUser.save();

      res.status(200).json({
         message: "تم تحديث بيانات المستخدم",
         user: sanitizeUser(targetUser),
      });
   } catch (error) {
      if (error.message === "CASHIER_LIMIT_REACHED") {
         return res.status(400).json({ message: "لا يمكن إنشاء كاشير جديد، تم الوصول إلى الحد الأقصى للباقة" });
      }
      if (error.message === "INVALID_STATUS") {
         return res.status(400).json({ message: "حالة المستخدم غير صالحة" });
      }
      res.status(500).json({ message: error.message });
   }
};

export const getTenants = async (req, res) => {
   if (req.user.role !== "super_admin") {
      return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه الوصول إلى المستأجرين" });
   }

   try {
      const page = Math.max(1, Number(req.query.page) || 1);
      const limit = Math.min(50, Math.max(5, Number(req.query.limit) || 10));
      const search = req.query.search?.trim() || "";
      const status = req.query.status?.trim() || "";
      const packageKey = req.query.package?.trim()?.toLowerCase() || "";
      const skip = (page - 1) * limit;

      const filter = buildTenantSearchFilter({ search, status, packageKey });

      const [tenants, total, allTenantsCount, currentPageRows] = await Promise.all([
         Tenant.find(filter).sort({ createdAt: -1 }).skip(skip).limit(limit),
         Tenant.countDocuments(filter),
         Tenant.countDocuments({}),
         Tenant.find(filter).sort({ createdAt: -1 }).limit(500),
      ]);

      await Promise.all([hydrateTenantRowsForDisplay(tenants), hydrateTenantRowsForDisplay(currentPageRows)]);

      const totalPages = Math.max(1, Math.ceil(total / limit));
      const serialized = tenants.map(sanitizeTenant);
      const summary = buildTenantSummary(currentPageRows, total, allTenantsCount);

      res.status(200).json({
         data: serialized,
         pagination: {
            page,
            limit,
            total,
            totalPages,
            hasNextPage: page < totalPages,
            hasPrevPage: page > 1,
         },
         filters: {
            search,
            status,
            package: packageKey || null,
         },
         packageOptions: Object.values(SUBSCRIPTION_PACKAGES).map((pkg) => ({
            key: pkg.key,
            label: pkg.label,
            cashierLimit: pkg.cashierLimit,
         })),
         summary,
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getTenantProfile = async (req, res) => {
   if (!req.user?.tenant) {
      return res.status(403).json({ message: "هذا الملف الشخصي متاح فقط لمستخدمي المستأجر" });
   }

   try {
      res.status(200).json({
         tenant: sanitizeTenant(req.user.tenant),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const updateTenantProfile = async (req, res) => {
   if (!req.user?.tenant) {
      return res.status(403).json({ message: "هذا الملف الشخصي متاح فقط لمستخدمي المستأجر" });
   }

   if (!["owner", "admin"].includes(req.user.role)) {
      return res.status(403).json({ message: "فقط أدوار إدارة المستأجر يمكنها تحديث إعدادات الشركة" });
   }

   try {
      const tenant = await Tenant.findById(req.user.tenant._id);

      if (!tenant) {
         return res.status(404).json({ message: "المستأجر غير موجود" });
      }

      tenant.name = req.body.name?.trim() || tenant.name;
      tenant.ownerName = req.body.ownerName?.trim() || tenant.ownerName;
      tenant.ownerEmail = req.body.ownerEmail?.trim()?.toLowerCase() || "";
      tenant.ownerPhone = req.body.ownerPhone?.trim() || "";
      tenant.whatsappNumber = req.body.whatsappNumber?.trim() || "";
      tenant.address = req.body.address?.trim() || "";
      tenant.settings = {
         ...tenant.settings,
         currency: req.body.currency?.trim() || tenant.settings?.currency || "EGP",
         lowStockThreshold:
            Number(req.body.lowStockThreshold) > 0
               ? Number(req.body.lowStockThreshold)
               : tenant.settings?.lowStockThreshold || 5,
      };

      await tenant.save();

      const owner = await User.findOne({ tenant: tenant._id, role: "owner" });
      if (owner) {
         owner.fullName = tenant.ownerName;
         owner.email = tenant.ownerEmail || undefined;
         owner.phone = tenant.ownerPhone;
         await owner.save();
      }

      await req.user.populate("tenant assignedBranch");

      res.status(200).json({
         message: "تم تحديث ملف الشركة بنجاح",
         tenant: sanitizeTenant(tenant),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const changePassword = async (req, res) => {
   try {
      const oldPassword = req.body.oldPassword?.trim();
      const newPassword = req.body.newPassword?.trim();
      const confirmPassword = req.body.confirmPassword?.trim();

      if (!oldPassword || !newPassword || !confirmPassword) {
         return res.status(400).json({ message: "جميع حقول كلمة المرور مطلوبة" });
      }

      if (newPassword.length < 6) {
         return res.status(400).json({ message: "كلمة المرور الجديدة يجب أن تكون 6 أحرف على الأقل" });
      }
      // const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
      // if (!passwordRegex.test(newPassword)) {
      //    return res.status(400).json({
      //       message: "كلمة المرور يجب أن تكون 8 أحرف على الأقل وتحتوي على حروف وأرقام"
      //    });
      // }

      if (newPassword !== confirmPassword) {
         return res.status(400).json({ message: "كلمة المرور الجديدة وتأكيدها غير متطابقين" });
      }

      const user = await User.findById(req.user._id);
      if (!user || !user.matchPassword(oldPassword)) {
         return res.status(400).json({ message: "كلمة المرور القديمة غير صحيحة" });
      }

      if (oldPassword === newPassword) {
         return res.status(400).json({ message: "كلمة المرور الجديدة يجب أن تختلف عن القديمة" });
      }

      user.password = newPassword;
      await user.save();

      res.status(200).json({ message: "تم تغيير كلمة المرور بنجاح" });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const updateTenantStatus = async (req, res) => {
   if (req.user.role !== "super_admin") {
      return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه تحديث حالة المستأجر" });
   }

   const status = req.body.status;
   if (!["active", "suspended"].includes(status)) {
      return res.status(400).json({ message: "حالة المستأجر غير صالحة" });
   }

   try {
      const tenant = await Tenant.findById(req.params.id);
      if (!tenant) {
         return res.status(404).json({ message: "المستأجر غير موجود" });
      }

      tenant.status = status;
      await tenant.save();

      await User.updateMany({ tenant: tenant._id }, { status });

      res.status(200).json({
         message: `تم تحديث حالة المستأجر إلى ${status === "active" ? "نشط" : "موقوف"}`,
         tenant: sanitizeTenant(tenant),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const updateTenantPackage = async (req, res) => {
   if (req.user.role !== "super_admin") {
      return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه تحديث باقات المستأجرين" });
   }

   try {
      const packageKey = normalizePackageKey(req.body.subscriptionPackage);
      if (!packageKey) {
         return res.status(400).json({ message: "الباقة المحددة غير صالحة" });
      }

      const tenant = await Tenant.findById(req.params.id);
      if (!tenant) {
         return res.status(404).json({ message: "المستأجر غير موجود" });
      }

      await normalizeTenantSubscriptionState(tenant);

      const nextPackage = getPackageDetails(packageKey);
      const currentCashiers = Number(tenant.cashierAccountsCount || 0);
      const currentBranches = Number(tenant.branchCount || 1);

      // ✅ Check cashier limit
      if (!isUnlimitedCashierLimit(nextPackage.cashierLimit) && currentCashiers > nextPackage.cashierLimit) {
         return res.status(400).json({
            message: `لا يمكن تخفيض الباقة. المستأجر لديه ${currentCashiers} كاشير وحد الباقة الجديدة ${nextPackage.cashierLimit}.`,
         });
      }

      // ✅ Check branch limit
      if (nextPackage.branchLimit !== null && currentBranches > nextPackage.branchLimit) {
         return res.status(400).json({
            message: `لا يمكن تخفيض الباقة. المستأجر لديه ${currentBranches} فرع وحد الباقة الجديدة ${nextPackage.branchLimit}.`,
         });
      }

      tenant.subscriptionPackage = nextPackage.key;
      tenant.cashierLimit = nextPackage.cashierLimit;
      tenant.branchLimit = nextPackage.branchLimit;   // ✅ sync
      await tenant.save();

      res.status(200).json({
         message: "تم تحديث باقة المستأجر بنجاح",
         tenant: sanitizeTenant(tenant),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const getDbUsage = async (req, res) => {
   if (req.user.role !== 'super_admin') {
      return res.status(403).json({ message: 'فقط مسؤول النظام يمكنه الوصول إلى مقاييس استخدام قاعدة البيانات' });
   }

   try {
      const stats = await mongoose.connection.db.stats();
      res.status(200).json({
         storageSize: stats.storageSize,
         dataSize: stats.dataSize,
         indexSize: stats.indexSize,
         fileSize: stats.fileSize || null,
         fsTotalSize: stats.fsTotalSize || null,
         fsUsedSize: stats.fsUsedSize || null,
         collections: stats.collections,
         objects: stats.objects,
         indexes: stats.indexes,
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const recordTenantPayment = async (req, res) => {
   const tenantId = req.params.id;
   const amount = Number(req.body.amount || 800);
   const method = req.body.method?.trim() || 'manual';
   const note = req.body.note?.trim() || 'سداد الرسوم الشهرية';

   try {
      const tenant = await Tenant.findById(tenantId);
      if (!tenant) {
         return res.status(404).json({ message: 'المستأجر غير موجود' });
      }

      if (req.user.role !== 'super_admin') {
         if (!req.user.tenant || req.user.tenant._id.toString() !== tenant._id.toString()) {
            return res.status(403).json({ message: 'ليس لديك صلاحية تسجيل المدفوعات لهذا المستأجر' });
         }
      }

      const paymentDate = new Date();
      tenant.payments = tenant.payments || [];
      tenant.payments.push({
         amount,
         date: paymentDate,
         method,
         note,
         recordedBy: req.user._id,
      });
      tenant.lastPaymentAt = paymentDate;
      tenant.nextPaymentDueAt = addOneMonth(tenant.nextPaymentDueAt || paymentDate);
      await tenant.save();

      res.status(200).json({
         message: 'تم تسجيل الدفعة بنجاح',
         tenant: sanitizeTenant(tenant),
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};

export const createTenantOwner = async (req, res) => {
   if (req.user.role !== "super_admin") {
      return res.status(403).json({ message: "فقط مسؤول المنصة يمكنه إنشاء مستأجرين" });
   }

   try {
      const companyName = req.body.companyName?.trim();
      const ownerName = req.body.ownerName?.trim();
      const username = req.body.username?.trim();
      const password = req.body.password?.trim();
      const email = req.body.email?.trim()?.toLowerCase() || "";
      const phone = req.body.phone?.trim() || "";
      const whatsappNumber = req.body.whatsappNumber?.trim() || phone;
      const address = req.body.address?.trim() || "";
      const packageKey = normalizePackageKey(req.body.subscriptionPackage) || DEFAULT_SUBSCRIPTION_PACKAGE;
      const packageDetails = getPackageDetails(packageKey);

      // Handle tenantTypes - ensure it's an array and contains valid types
      let tenantTypes = req.body.tenantTypes || ["sales"];
      if (!Array.isArray(tenantTypes)) {
         tenantTypes = [tenantTypes];
      }

      // Validate and deduplicate tenant types
      const validTypes = ["restaurant", "cafe", "sales"];
      tenantTypes = [...new Set(tenantTypes.filter(type => validTypes.includes(type)))];

      if (tenantTypes.length === 0) {
         tenantTypes = ["sales"];
      }

      if (!companyName || !ownerName || !username || !password) {
         return res.status(400).json({ message: "بيانات الشركة والمالك مطلوبة" });
      }

      if (email) {
         const existingEmail = await User.findOne({ email });
         if (existingEmail) {
            return res.status(400).json({ message: "البريد الإلكتروني مستخدم بالفعل" });
         }
      }

      const slug = await createUniqueSlug(companyName);

      const tenant = await Tenant.create({
         name: companyName,
         slug,
         ownerName,
         ownerEmail: email,
         ownerPhone: phone,
         whatsappNumber,
         address,
         monthlyFeeAmount: 800,
         monthlyFeeCurrency: "EGP",
         nextPaymentDueAt: addOneMonth(new Date()),
         subscriptionPackage: packageDetails.key,
         cashierLimit: packageDetails.cashierLimit,
         cashierAccountsCount: 0,
         branchLimit: packageDetails.branchLimit,
         branchCount: 1,
         tenantTypes,
      });

      const primaryBranch = await Branch.create({
         tenant: tenant._id,
         name: "Main Branch",
         code: "MAIN",
         isPrimary: true,
         status: "active",
      });

      const owner = await User.create({
         username,
         fullName: ownerName,
         email: email || undefined,
         phone,
         password,
         role: "owner",
         tenant: tenant._id,
         assignedBranch: primaryBranch._id,
      });

      await owner.populate("tenant assignedBranch");

      const loginUrl = `${(process.env.FRONTEND_URL || "http://localhost:5173").replace(/\/$/, "")}`;
      const onboarding = buildTenantCredentialsWhatsApp({
         ownerName,
         username,
         temporaryPassword: password,
         loginUrl,
      });

      res.status(201).json({
         message: "تم إنشاء حساب مالك المستأجر بنجاح",
         tenant: sanitizeTenant(tenant),
         owner: sanitizeUser(owner),
         onboarding: {
            loginUrl,
            // temporaryPassword: password,
            whatsappMessage: onboarding.message,
            whatsappLink: onboarding.whatsappLink,
         },
      });
   } catch (error) {
      res.status(500).json({ message: error.message });
   }
};