File size: 75,387 Bytes
16a83e0
 
 
 
 
 
 
 
096c895
 
 
16a83e0
 
 
 
 
 
 
acb1bd4
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e76d669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0dcff5
096c895
e76d669
 
 
 
 
b0dcff5
 
e546c83
b0dcff5
 
 
 
e546c83
b0dcff5
096c895
 
 
e76d669
 
 
 
 
 
 
 
 
 
096c895
e76d669
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
 
2292087
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c23d5cf
f37235c
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c23d5cf
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f37235c
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
 
16a83e0
 
bb6a0c8
 
16a83e0
 
bb6a0c8
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6d6108
16a83e0
 
d6d6108
 
b6c6de0
d6d6108
 
16a83e0
 
d6d6108
16a83e0
 
 
 
b6c6de0
 
 
16a83e0
d6d6108
b6c6de0
 
d6d6108
 
 
b6c6de0
 
 
d6d6108
b6c6de0
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
090858a
16a83e0
 
 
 
 
 
090858a
 
 
 
 
096c895
16a83e0
acb1bd4
 
7560d9e
 
 
 
 
16a83e0
096c895
 
 
 
7560d9e
 
090858a
096c895
 
 
 
 
 
 
 
 
7560d9e
 
090858a
096c895
 
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1966575
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb6a0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c23d5cf
bb6a0c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acb1bd4
 
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
acb1bd4
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db0be24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db0be24
 
 
 
16a83e0
 
 
db0be24
 
 
 
 
 
 
2292087
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c23d5cf
 
16a83e0
 
c23d5cf
16a83e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { Telegraf, Markup } = require('telegraf');
const Product = require('../models/Product');
const Order = require('../models/Order');
const Category = require('../models/Category');
const Banner = require('../models/Banner');
const dns = require('dns');
const https = require('https');
const http = require('http');
const { GoogleGenerativeAI } = require('@google/generative-ai');

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || '');

dns.setDefaultResultOrder('ipv4first');

// AI rasm yuklab olish (redirect'lar bilan)
function downloadImage(url) {
    return new Promise((resolve, reject) => {
        const protocol = url.startsWith('https') ? https : http;
        const req = protocol.get(url, { timeout: 45000 }, (res) => {
            // Redirect bo'lsa β€” kuzatib borish
            if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
                return downloadImage(res.headers.location).then(resolve).catch(reject);
            }
            if (res.statusCode !== 200) {
                return reject(new Error(`Status: ${res.statusCode}`));
            }
            const chunks = [];
            res.on('data', chunk => chunks.push(chunk));
            res.on('end', () => resolve(Buffer.concat(chunks)));
            res.on('error', reject);
        });
        req.on('error', reject);
        req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
    });
}

// O'zbekcha-Inglizcha sodda lug'at (Gemini ishlamasa fallback)
const uzToEn = {
    'kiyim': 'clothing', 'kiyimlar': 'clothes', 'moda': 'fashion', 'ayol': 'woman', 'erkak': 'man',
    'go\'zal': 'beautiful', 'chiroyli': 'beautiful', 'zamonaviy': 'modern', 'yangi': 'new',
    'chegirma': 'sale discount', 'skidka': 'sale discount', 'aksiya': 'promotion sale',
    'arzon': 'affordable price', 'narx': 'price',
    'yozgi': 'summer', 'qishki': 'winter', 'bahorgi': 'spring', 'kuzgi': 'autumn',
    'kolleksiya': 'collection', 'sport': 'sports athletic', 'sportiv': 'sports athletic',
    'athietivk': 'athletic sportswear', 'atletik': 'athletic sportswear',
    'texnika': 'technology gadgets', 'gadjet': 'gadgets devices', 'telefon': 'smartphone phone',
    'kompyuter': 'computer laptop', 'audio': 'audio headphones',
    'sovga': 'gift present', 'bayram': 'holiday celebration', 'tovar': 'product', 'tavaar': 'product',
    'tovarlar': 'products', 'tavaarlar': 'products', 'barch': 'all', 'barcha': 'all',
    'reklama': 'advertisement', 'banner': 'promotional banner', 'dizayn': 'design',
    'dizayinda': 'in design style', 'premium': 'premium luxury', 'klassik': 'classic elegant',
    'rangli': 'colorful', 'qora': 'black', 'oq': 'white', 'qizil': 'red', 'ko\'k': 'blue',
    'yashil': 'green', 'sariq': 'yellow', 'pushti': 'pink',
    'kurtka': 'jacket', 'kostyum': 'suit', 'kastiyum': 'suit', 'ko\'ylak': 'shirt dress',
    'shim': 'pants trousers', 'futbolka': 't-shirt', 'palto': 'coat overcoat',
    'tufli': 'shoes', 'krossovka': 'sneakers', 'sumka': 'bag handbag',
    'bolalar': 'children kids', 'bola': 'child kid', 'oila': 'family',
    'do\'kon': 'store shop', 'magazin': 'store shop', 'savdo': 'commerce shopping',
    'yasa': '', 'yoq': '', 'deb': '', 'yozilgan': 'with text overlay',
    'mantiya': 'graduation gown mantle', 'manti': 'graduation gown coat',
};

function translateUzToEn(text) {
    let result = text.toLowerCase();
    // Har bir so'zni tarjima qilish
    for (const [uz, en] of Object.entries(uzToEn)) {
        result = result.replace(new RegExp(uz.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), en);
    }
    // Raqamlarni saqlab qolish (masalan: 30%)
    return result.trim();
}

// AI yordamida (Gemini) promptni professional kengaytirish
async function enhancePromptWithGemini(userText, templateBase = '') {
    // Avval Gemini bilan urinib ko'rish
    if (process.env.GEMINI_API_KEY) {
        try {
            const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
            const prompt = `You are an expert AI image prompt engineer for an e-commerce platform.
The user wants to generate a banner image, but they write in Uzbek and might have typos.
CRITICAL RULE: Interpret words in FASHION, CLOTHING, TECH, or E-COMMERCE contexts. E.g., if they write "manti", "mantiani", or "mantiya", they mean "graduation gown", "coat", or "mantle" (clothing), NEVER the food (dumplings).

Step 1: Understand their intent and correct typos.
Step 2: Convert the idea into a clean, highly descriptive English prompt for Midjourney/Flux.
Step 3: Keep it heavily focused on the SUBJECT. DO NOT add generic tags like "banner" or "advertising" that ruin the immersion. Just describe the scene, the models, the clothes, and the environment. Add: ", photorealistic, cinematic, highly detailed, no text".
Example Output: "A handsome male student and a beautiful female student wearing elegant graduation gowns, evening graduation party, cinematic lighting, photorealistic, no text"

Template Context: ${templateBase || 'None'}
User's Idea: "${userText}"

Respond ONLY with the final English prompt string, and nothing else.`;
            const result = await model.generateContent(prompt);
            const enhanced = result.response.text().trim();
            console.log('[AI BANNER] Gemini enhanced:', enhanced);
            return enhanced;
        } catch (e) {
            console.error("[AI BANNER] Gemini FAILED:", e.message);
            // Gemini xato qilsa β€” fallback'ga tushadi (pastga)
        }
    } else {
        console.warn("[AI BANNER] GEMINI_API_KEY not found, using dictionary fallback");
    }
    
    // FALLBACK: Gemini ishlamasa, oddiy lug'at orqali tarjima
    const translated = translateUzToEn(userText);
    const base = templateBase ? templateBase + ', ' : '';
    const fallback = `${base}${translated}, professional product photography, photorealistic, cinematic lighting, highly detailed`;
    console.log('[AI BANNER] Fallback prompt:', fallback);
    return fallback;
}

// AI Banner Shablon Promptlari
const aiTemplates = {
    'fashion': {
        label: 'πŸ‘— Kiyim/Moda',
        base: 'elegant fashion collection showcase, stylish models wearing designer clothing, luxury boutique atmosphere, soft studio lighting, fashion editorial photography, haute couture, magazine quality'
    },
    'tech': {
        label: 'πŸ“± Texnika',
        base: 'modern technology products showcase, sleek gadgets and devices, futuristic minimalist design, cool blue LED lighting, professional product photography, tech store display'
    },
    'holiday': {
        label: '🎁 Bayram/Sovga',
        base: 'festive celebration gift boxes, beautifully wrapped presents, warm holiday atmosphere, golden decorations, bokeh lights background, joyful celebration mood'
    },
    'sale': {
        label: '🏷 Chegirma/Aksiya',
        base: 'exciting shopping sale promotion, vibrant colorful shopping bags, dynamic energy, confetti, excited shoppers, retail celebration atmosphere, bold vibrant colors'
    },
    'lifestyle': {
        label: '🌿 Lifestyle',
        base: 'premium lifestyle photography, beautiful natural setting, warm golden hour lighting, elegant composition, aspirational mood, luxury brand aesthetic'
    },
    'sport': {
        label: '⚽ Sport',
        base: 'dynamic sports athletic photography, active lifestyle, energetic motion blur, fitness motivation, professional sports equipment, vibrant action shot'
    }
};

let bot;

const line = '━━━━━━━━━━━━━━━━━━━━━━━━━━';
const thinLine = '─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─';
const formatPrice = (num) => Number(num).toLocaleString('uz-UZ');
const formatDate = (d) => {
    const date = new Date(d);
    return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const getMainMenu = () => {
    return Markup.inlineKeyboard([
        [Markup.button.callback('βž• Yangi tovar', 'action_addproduct'), Markup.button.callback('πŸ“¦ Tovarlar', 'action_products_0')],
        [Markup.button.callback('πŸ“ Kategoriyalar', 'action_categories'), Markup.button.callback('πŸ” Qidirish', 'action_search')],
        [Markup.button.callback('πŸ“‹ Barcha Buyurtmalar', 'action_orders_0'), Markup.button.callback('πŸ”Ž Turniket (Chek O\'qish)', 'action_search_order')],
        [Markup.button.callback('πŸ“Š Statistika', 'action_stats'), Markup.button.callback('🏞 Reklamalar', 'action_banners')],
        [Markup.button.callback('πŸ“ Do\'kon Manzili', 'action_set_location'), Markup.button.callback('πŸ“₯ Excel', 'action_export_excel')],
        [Markup.button.callback('πŸ“’ Push Xabar', 'action_send_push'), Markup.button.callback('❓ Yordam', 'action_help')]
    ]);
};

if (process.env.BOT_TOKEN && process.env.BOT_TOKEN !== 'YOUR_TELEGRAM_BOT_TOKEN') {
    bot = new Telegraf(process.env.BOT_TOKEN, { telegram: { apiRoot: 'https://api.telegram.org' } });
    const TIMEOUT_MS = 30 * 60 * 1000; // 30 daqiqa
    const rawAppState = {};
    const appState = new Proxy(rawAppState, {
        set(target, prop, value) {
            if (target[prop] && target[prop].timer) {
                clearTimeout(target[prop].timer);
            }
            if (value && typeof value === 'object') {
                value.timer = setTimeout(() => {
                    delete target[prop];
                    try {
                        bot.telegram.sendMessage(prop, '⏳ Uzoq vaqt harakatsizlik sababli joriy amaliyot xavfsiz bekor qilindi. Bosh menyudasiz.', { parse_mode: 'Markdown', ...getMainMenu() });
                    } catch(e) {}
                }, TIMEOUT_MS);
            }
            target[prop] = value;
            return true;
        },
        deleteProperty(target, prop) {
            if (target[prop] && target[prop].timer) {
                clearTimeout(target[prop].timer);
            }
            delete target[prop];
            return true;
        }
    });
    const isAdmin = (ctx) => ctx.from.id.toString() === process.env.ADMIN_ID;

    bot.start(async (ctx) => {
        if (!isAdmin(ctx)) return ctx.reply('⚠️ Siz admin emassiz.');
        delete appState[ctx.from.id];
        try {
            const logoPath = require('path').join(__dirname, '../assets/mtextile_logo.png');
            await ctx.replyWithPhoto({ source: logoPath }, {
                caption: `${line}\nπŸ‘” *MTEXTILE ADMIN PANEL V4.0*\n${line}\n\nQuyidagi menyudan tanlang:`,
                parse_mode: 'Markdown',
                ...getMainMenu()
            });
        } catch(e) {
            ctx.reply(`${line}\nπŸ‘” *MTEXTILE ADMIN PANEL V4.0*\n${line}\n\nQuyidagi menyudan tanlang:`, { parse_mode: 'Markdown', ...getMainMenu() });
        }
    });

    // Istalgan paytda chala jarayonni bekor qilish
    bot.command('cancel', (ctx) => {
        if (!isAdmin(ctx)) return;
        const had = !!appState[ctx.from.id];
        delete appState[ctx.from.id];
        ctx.reply(had ? 'βœ… Jarayon bekor qilindi.' : 'ℹ️ Faol jarayon yo\'q.', getMainMenu());
    });

    bot.hears('❌ Bekor qilish', (ctx) => {
        if (!isAdmin(ctx)) return;
        delete appState[ctx.from.id];
        ctx.reply('βœ… Bekor qilindi.', getMainMenu());
    });

    bot.action('action_home', (ctx) => {
        if (!isAdmin(ctx)) return;
        delete appState[ctx.from.id];
        try { ctx.deleteMessage(); } catch (e) {}
        ctx.reply(`${line}\nπŸ›’ *ASOSIY MENYU*\n${line}`, { parse_mode: 'Markdown', ...getMainMenu() });
    });

    // ==========================================
    // KATEGORIYALAR BOSHQARUVI
    // ==========================================
    bot.action('action_categories', async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            const categories = await Category.find().sort({ order: 1 });
            let msg = `${line}\nπŸ“ *KATEGORIYALAR*\n${line}\n\n`;
            if (categories.length === 0) msg += `πŸ“­ Hozircha kategoriyalar yo'q.`;
            else {
                categories.forEach(c => { msg += `πŸ”Ή *${c.name}*\n`; });
            }
            
            const buttons = [[Markup.button.callback('βž• Yangi kategoriya', 'action_addcategory')]];
            categories.forEach(c => {
                buttons.push([
                    Markup.button.callback(`✏️ ${c.name}`, `edit_cat_${c._id}`),
                    Markup.button.callback(`πŸ—‘ ${c.name}`, `del_cat_confirm_${c._id}`)
                ]);
            });
            buttons.push([Markup.button.callback('🏠 Menyu', 'action_home')]);
            
            try { await ctx.deleteMessage(); } catch(e){}
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    bot.action('action_addcategory', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'adding_category' };
        ctx.reply('✏️ Yangi kategoriya nomini yozing (Masalan: Smartfonlar):', { parse_mode: 'Markdown', reply_markup: { force_reply: true } });
    });

    bot.action(/del_cat_confirm_(.+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        const cId = ctx.match[1];
        await ctx.answerCbQuery();
        try { await ctx.deleteMessage(); } catch(e){}
        ctx.reply('⚠️ *Kategoriyani o\'chirmoqchimisiz?*\nUnga tegishli tovarlar o\'chmaydi, lekin kategoriyasi bo\'sh bo\'lib qoladi.', {
            parse_mode: 'Markdown',
            ...Markup.inlineKeyboard([[Markup.button.callback('βœ… Ha, o\'chirish', `delcat_${cId}`), Markup.button.callback('❌ Yo\'q', 'action_categories')]])
        });
    });

    bot.action(/delcat_(.+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            await Category.findByIdAndDelete(ctx.match[1]);
            ctx.answerCbQuery('Kategoriya o\'chirildi');
            try { await ctx.deleteMessage(); } catch(e){}
            // Kategoriya ro'yxatini qayta ko'rsatish
            const categories = await Category.find().sort({ order: 1 });
            let msg = `${line}\nπŸ“ *KATEGORIYALAR*\n${line}\n\n`;
            if (categories.length === 0) msg += 'πŸ“­ Hozircha kategoriyalar yo\'q.';
            else categories.forEach(c => { msg += `πŸ”Ή *${c.name}*\n`; });
            const buttons = [[Markup.button.callback('βž• Yangi kategoriya', 'action_addcategory')]];
            categories.forEach(c => {
                buttons.push([
                    Markup.button.callback(`✏️ ${c.name}`, `edit_cat_${c._id}`),
                    Markup.button.callback(`πŸ—‘ ${c.name}`, `del_cat_confirm_${c._id}`)
                ]);
            });
            buttons.push([Markup.button.callback('🏠 Menyu', 'action_home')]);
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    bot.action(/edit_cat_(.*)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'editing_category', catId: ctx.match[1] };
        ctx.answerCbQuery();
        ctx.reply('✏️ Kategoriya uchun yangi nom yozing:', { reply_markup: { force_reply: true } });
    });

    // ==========================================
    // TOVARLAR VA TO'LIQ TAHRIRLASH
    // ==========================================
    bot.action('action_addproduct', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'name' };
        ctx.answerCbQuery();
        ctx.reply('βž• *Yangi Tovar Qo\'shish*\n\nπŸ“„ 1-qadam: Tovarning nomini yozing:', { parse_mode: 'Markdown' });
    });

    bot.action(/action_products_(\d+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        const page = parseInt(ctx.match[1]);
        const limit = 2; // Keng tugmalar uchun kamroq limit
        const skip = page * limit;

        try {
            const productCount = await Product.countDocuments();
            const products = await Product.find().sort({ createdAt: -1 }).skip(skip).limit(limit);

            if (products.length === 0) return ctx.answerCbQuery('πŸ“­ Tovar topilmadi.');
            await ctx.answerCbQuery();
            try { await ctx.deleteMessage(); } catch (e) {}

            await ctx.reply(`${line}\nπŸ“¦ *TOVARLAR RO'YXATI*  (${page + 1}-sahifa)\n${line}\nJami: *${productCount}* ta tovar`, { parse_mode: 'Markdown' });

            for (const p of products) {
                const msg = `🏷 *${p.name}*\n${thinLine}\nπŸ“ Kat: \`${p.category}\`\nπŸ’° Narx: *${formatPrice(p.price)} so'm*\nπŸ“„ ${p.description || '-'}`;

                const buttons = [
                    [Markup.button.callback('✏️ Nomi', `edit_pname_${p._id}`), Markup.button.callback('✏️ Narx', `edit_price_${p._id}`)],
                    [Markup.button.callback('πŸ“ Tavsif', `edit_desc_${p._id}`), Markup.button.callback('πŸ“ Kategoriya', `edit_pcat_${p._id}`)],
                    [Markup.button.callback('πŸ“Έ Rasm', `edit_pimg_${p._id}`), Markup.button.callback('πŸ“ Razmer', `edit_psize_${p._id}`)],
                    [Markup.button.callback('πŸ—‘ O\'chirish', `del_confirm_${p._id}`)]
                ];

                if (p.imageUrl && p.imageUrl.startsWith('http')) {
                    try {
                        let photoSource = p.imageUrl;
                        // Agar bizning proxy URL bo'lsa, Telegramning o'zining file_id sini ajratib olamiz
                        if (p.imageUrl.includes('/api/image/')) {
                            photoSource = p.imageUrl.split('/api/image/')[1];
                        }
                        await ctx.replyWithPhoto(photoSource, { caption: msg, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                    } catch (err) {
                        // Agar rasm xato qilsa (yo'q qolib ketsa), rasm o'rniga faqat text jo'natish
                        await ctx.reply(msg + "\n\n⚠️ (Rasm mavjud emas yoki xato)", { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                    }
                } else {
                    await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                }
            }

            const navButtons = [];
            if (page > 0) navButtons.push(Markup.button.callback('⬅️ Oldingi', `action_products_${page - 1}`));
            navButtons.push(Markup.button.callback(`πŸ“„ ${page + 1}/${Math.ceil(productCount / limit)}`, 'noop'));
            if (skip + limit < productCount) navButtons.push(Markup.button.callback('Keyingi ➑️', `action_products_${page + 1}`));

            await ctx.reply(`${thinLine}`, { ...Markup.inlineKeyboard([navButtons, [Markup.button.callback('🏠 Menyu', 'action_home')]]) });
        } catch (e) { ctx.reply('❌ Xato: ' + e.message); }
    });

    bot.action(/edit_pname_(.*)/, (ctx) => {
        appState[ctx.from.id] = { step: 'edit_pname', pId: ctx.match[1] };
        ctx.reply('Yangi nomni yozing:');
    });
    bot.action(/edit_price_(.*)/, (ctx) => {
        appState[ctx.from.id] = { step: 'editing_price', productId: ctx.match[1] };
        ctx.reply('Yangi narxni yozing (faqat son):');
    });
    bot.action(/edit_desc_(.*)/, (ctx) => {
        appState[ctx.from.id] = { step: 'editing_desc', productId: ctx.match[1] };
        ctx.reply('Yangi tavsif yozing:');
    });
    bot.action(/edit_pimg_(.*)/, (ctx) => {
        appState[ctx.from.id] = { step: 'edit_pimg', pId: ctx.match[1] };
        ctx.reply('Yangi rasm yuboring yoki rasm linkini tashlang:');
    });
    bot.action(/edit_psize_(.*)/, (ctx) => {
        appState[ctx.from.id] = { step: 'edit_psize', pId: ctx.match[1] };
        ctx.reply('πŸ‘• Razmerlarni vergul bilan yozing (Masalan: 44, 46, 48)\nYoki razmersiz qilish uchu "yoq" deb yozing:');
    });
    bot.action(/edit_pcat_(.*)/, async (ctx) => {
        const categories = await Category.find();
        if(categories.length === 0) return ctx.reply('Kategoriyalar mavjud emas. Avval kategoriya yarating.');
        appState[ctx.from.id] = { step: 'exec_edit_pcat', pId: ctx.match[1] };
        const buttons = [];
        let row = [];
        categories.forEach((c, i) => {
            row.push(Markup.button.callback(c.name, `setpcat_${c.name}`));
            if(row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; }
        });
        ctx.reply('Qaysi kategoriyaga o\'zgartiramiz?', Markup.inlineKeyboard(buttons));
    });

    bot.action(/setpcat_(.+)/, async (ctx) => {
        const state = appState[ctx.from.id];
        if(!state || state.step !== 'exec_edit_pcat') return;
        try {
            await Product.findByIdAndUpdate(state.pId, { category: ctx.match[1] });
            ctx.reply('βœ… Kategoriya yangilandi!', getMainMenu());
        } catch(e){}
        delete appState[ctx.from.id];
    });

    bot.action(/del_confirm_(.*)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        try { await ctx.deleteMessage(); } catch(e){}
        ctx.reply('⚠️ *O\'chirmoqchimisiz?*', { parse_mode: 'Markdown', ...Markup.inlineKeyboard([[Markup.button.callback('βœ… Ha', `del_product_${ctx.match[1]}`), Markup.button.callback('❌ Yo\'q', 'action_home')]]) });
    });
    bot.action(/del_product_(.*)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            await Product.findByIdAndDelete(ctx.match[1]);
            ctx.reply(`βœ… O'chirildi.`, getMainMenu());
        } catch (e) {}
    });

    // ==========================================
    // BUYURTMALAR BOSHQAARUVI
    // ==========================================
    bot.action(/action_orders_(\d+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        delete appState[ctx.from.id];
        const page = parseInt(ctx.match[1]);
        const limit = 3;
        const skip = page * limit;

        try {
            const orderCount = await Order.countDocuments();
            const orders = await Order.find().sort({ createdAt: -1 }).skip(skip).limit(limit);

            if (orders.length === 0) return ctx.answerCbQuery('πŸ“­ Hozircha buyurtmalar yo\'q.');
            await ctx.answerCbQuery();
            try { await ctx.deleteMessage(); } catch(e){}

            await ctx.reply(`${line}\nπŸ“‹ *BUYURTMALAR* (${page+1}-sahifa)\n${line}\nJami: *${orderCount}* ta`, { parse_mode: 'Markdown' });

            for (const o of orders) {
                let productsText = "";
                o.products.forEach(p => { productsText += `β€” ${p.name} (${p.quantity} ta) \n`; });
                let statusEmoji = o.status === 'Kutilmoqda' ? '⏳' : o.status === 'Xaridorga topshirildi' ? 'βœ…' : o.status === 'Olib ketishga tayyor' ? 'πŸ›' : 'πŸ“₯';
                const msg = `🧾 *ID:* \`${o._id}\`\nπŸ‘€ Mijoz: *${o.customerName}*\nπŸ“ž Tel: ${o.phone}\nπŸ“ Izoh: ${o.comment}\n\nπŸ“ *Tovarlar:*\n${productsText}\nπŸ’° *Jami:* ${formatPrice(o.totalAmount)} so'm\nπŸ“Œ *Holati:* ${statusEmoji} ${o.status}\nπŸ•’ Vaqt: ${formatDate(o.createdAt)}`;
                
                await ctx.reply(msg, { parse_mode: 'Markdown', ...orderStatusButtonsForNotify(o._id, o.status) });
            }

            const navButtons = [];
            if (page > 0) navButtons.push(Markup.button.callback('⬅️', `action_orders_${page - 1}`));
            navButtons.push(Markup.button.callback(`${page + 1}/${Math.ceil(orderCount / limit)}`, 'noop'));
            if (skip + limit < orderCount) navButtons.push(Markup.button.callback('➑️', `action_orders_${page + 1}`));
            
            await ctx.reply(`${thinLine}`, { ...Markup.inlineKeyboard([navButtons, [Markup.button.callback('🏠 Menyu', 'action_home')]]) });
        } catch(e) { ctx.reply('Xatolik'); }
    });

    bot.action(/order_status_(accept|ship|deliver|cancel)_(.*)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        const action = ctx.match[1];
        const orderId = ctx.match[2];
        
        let newStatus = 'Kutilmoqda';
        if (action === 'accept') newStatus = 'Yig\'ilmoqda';
        if (action === 'ship') newStatus = 'Olib ketishga tayyor';
        if (action === 'deliver') newStatus = 'Xaridorga topshirildi';
        if (action === 'cancel') newStatus = 'Bekor qilindi';

        try {
            await Order.findByIdAndUpdate(orderId, { status: newStatus });
            ctx.answerCbQuery(`Holat: ${newStatus}`);
            // Xabardagi tugmalarni yangilab, tanlanganiga pichka qo'yish
            await ctx.editMessageReplyMarkup(orderStatusButtonsForNotify(orderId, newStatus).reply_markup);
        } catch(e) { ctx.answerCbQuery('Xato yuz berdi'); }
    });

    // ==========================================
    // STATISTIKA & QIDIRUV
    // ==========================================
    bot.action('action_stats', async (ctx) => {
        if (!isAdmin(ctx)) return;
        delete appState[ctx.from.id];
        try {
            const pCount = await Product.countDocuments();
            const oCount = await Order.countDocuments();
            const cCount = await Category.countDocuments();
            // Jami tushumni hisoblash
            const orders = await Order.find({ status: { $ne: 'Bekor qilindi' } });
            let totalMoney = 0;
            orders.forEach(o => totalMoney += o.totalAmount);

            const msg = `${line}\nπŸ“Š *STATISTIKA VA HISOBOT*\n${line}\n\nπŸ“¦ Jami tovarlar: *${pCount}*\nπŸ“ Kategoriyalar: *${cCount}*\nπŸ“‹ Barcha buyurtmalar: *${oCount}*\n\nπŸ’° *Umumiy tushum:* ${formatPrice(totalMoney)} so'm`;
            
            try { await ctx.deleteMessage(); } catch(e){}
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard([[Markup.button.callback('🏠 Menyu', 'action_home')]])});
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    bot.action('action_search', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'searching_product' };
        ctx.answerCbQuery();
        ctx.reply('πŸ” *Qidirish*\n\nTovar nomini yozib yuboring (Masalan: "Kastiyum"):', { parse_mode: 'Markdown' });
    });

    bot.action('action_search_order', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'searching_order' };
        ctx.answerCbQuery();
        ctx.reply('πŸ”Ž *Turniket (Chek O\'qish)*\n\nMijoz ko\'rsatgan QR Koddagi 24 xonali ID raqamini yuboring:', { parse_mode: 'Markdown' });
    });

    bot.action('action_export_excel', async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            ctx.answerCbQuery('πŸ“₯ Tayorlanmoqda...');
            const products = await Product.find().sort({ category: 1, name: 1 });
            if (products.length === 0) return ctx.reply('πŸ“­ Eksport qilish uchun tovar yo\'q.', getMainMenu());
            
            let csv = 'Nomi,Kategoriya,Narx,Tavsif,Razmerlar\n';
            products.forEach(p => {
                const sizes = p.sizes ? p.sizes.join('; ') : '';
                const desc = (p.description || '').replace(/,/g, ' ').replace(/\n/g, ' ');
                csv += `"${p.name}","${p.category || ''}",${p.price},"${desc}","${sizes}"\n`;
            });
            
            await ctx.replyWithDocument({
                source: Buffer.from(csv, 'utf-8'),
                filename: `tovarlar_${new Date().toISOString().slice(0,10)}.csv`
            }, { caption: `πŸ“Š Jami ${products.length} ta tovar eksport qilindi.` });
        } catch(e) {
            ctx.reply('❌ Xatolik: ' + e.message);
        }
    });

    // Filter stub olib tashlandi

    bot.action('action_help', (ctx) => {
        ctx.answerCbQuery();
        let msg = `❓ *YORDAM*\n\n` +
                  `Quyidagi bo'limlar orqali do'konni to'liq boshqarasiz:\n\n` +
                  `πŸ“¦ *Tovarlar* - Tahrirlash, O'chirish va Rasm o'zgartirish.\n` +
                  `πŸ“ *Kategoriyalar* - Guruhlar yaratish, nomini o'zgartirish.\n` +
                  `πŸ“‹ *Buyurtmalar* - Holatini (yig'ilmoqda, tayyor) tasdiqlash.\n` +
                  `πŸ” *Qidirish* - Ismi bilan izlab topib tahrirlash.\n` +
                  `πŸ“Š *Statistika* - Tushumlar va statistika.`;
        ctx.reply(msg, { parse_mode: 'Markdown' });
    });

    // ==========================================
    // 🏞 REKLAMA BANNERLARI β€” PREMIUM PANEL V2.0
    // ==========================================
    bot.action('action_banners', async (ctx) => {
        if (!isAdmin(ctx)) return;
        delete appState[ctx.from.id];
        try {
            const banners = await Banner.find().sort({ order: 1 });
            // Muddati o'tganlarni avtomatik o'chirish
            const now = new Date();
            for (const b of banners) {
                if (b.expiresAt && new Date(b.expiresAt) < now) {
                    b.isActive = false;
                    await b.save();
                }
            }
            const activeBanners = banners.filter(b => b.isActive);
            
            let msg = `${line}\n🏞 *REKLAMA BANNERLARI*\n${line}\n\n`;
            if (activeBanners.length === 0) {
                msg += `πŸ“­ Aktiv bannerlar yo'q.\n\nπŸ’‘ _Quyidagi tugmalar orqali yangi banner qo'shing:_`;
            } else {
                msg += `βœ… *${activeBanners.length}* ta aktiv banner\n\n`;
                activeBanners.forEach((b, i) => {
                    const titleStr = b.title ? b.title : '(Nomi yo\'q)';
                    const linkStr = b.linkType === 'none' ? 'β€”' : 
                        b.linkType === 'category' ? `πŸ“ ${b.linkValue}` :
                        b.linkType === 'product' ? `πŸ“¦ ${b.linkValue}` :
                        `πŸ”— ${b.linkValue}`;
                    const expStr = b.expiresAt ? formatDate(b.expiresAt) : 'β™Ύ Muddatsiz';
                    msg += `*${i + 1}.* ${titleStr}\n   ↳ ${linkStr} | ${expStr}\n\n`;
                });
            }

            const buttons = [
                [Markup.button.callback('βž• Rasm yuklash', 'banner_add_photo'), Markup.button.callback('🎨 AI yaratish', 'banner_ai_menu')]
            ];
            
            activeBanners.forEach((b, index) => {
                buttons.push([
                    Markup.button.callback(`πŸ“Έ #${index + 1} ko'rish`, `banner_view_${b._id}`),
                    Markup.button.callback(`✏️ Tahrirlash`, `banner_edit_${b._id}`),
                    Markup.button.callback(`πŸ—‘`, `banner_del_confirm_${b._id}`)
                ]);
            });
            
            if (activeBanners.length > 1) {
                buttons.push([Markup.button.callback('πŸ”€ Tartibni o\'zgartirish', 'banner_reorder')]);
            }
            buttons.push([Markup.button.callback('🏠 Menyu', 'action_home')]);
            
            try { await ctx.deleteMessage(); } catch(e){}
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato: ' + e.message); }
    });

    // πŸ“Έ Banner ko'rish yoki tahrirlash (rasmli preview)
    bot.action(/banner_(view|edit)_(.+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            const bannerId = ctx.match[2];
            const banner = await Banner.findById(bannerId);
            if (!banner) return ctx.answerCbQuery('Banner topilmadi');
            await ctx.answerCbQuery();
            try { await ctx.deleteMessage(); } catch(e){}
            
            const titleStr = banner.title || '(Nomi yo\'q)';
            const subtitleStr = banner.subtitle || 'β€”';
            const linkStr = banner.linkType === 'none' ? 'Havolasiz' : 
                `${banner.linkType}: ${banner.linkValue}`;
            const expStr = banner.expiresAt ? formatDate(banner.expiresAt) : 'Muddatsiz';
            const statusStr = banner.isActive ? 'βœ… Faol' : '⏸ O\'chirilgan';
            
            const caption = `🏞 *BANNER TAFSILOTLARI*\n${line}\n\nπŸ“Œ *Sarlavha:* ${titleStr}\nπŸ“ *Matn:* ${subtitleStr}\nπŸ”— *Havola:* ${linkStr}\nπŸ“… *Muddat:* ${expStr}\nπŸ“Š *Holat:* ${statusStr}`;
            
            const buttons = [
                [Markup.button.callback('✏️ Sarlavha', `banner_set_title_${banner._id}`), Markup.button.callback('πŸ“ Matn', `banner_set_subtitle_${banner._id}`)],
                [Markup.button.callback('πŸ”— Havola', `banner_set_link_${banner._id}`), Markup.button.callback('πŸ“… Muddat', `banner_set_expire_${banner._id}`)],
                [Markup.button.callback('πŸ”™ Orqaga', 'action_banners')]
            ];
            
            if (banner.imageUrl && banner.imageUrl.startsWith('http')) {
                try {
                    let photoSource = banner.imageUrl;
                    if (photoSource.includes('/api/image/')) photoSource = photoSource.split('/api/image/')[1];
                    await ctx.replyWithPhoto(photoSource, { caption, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                } catch(e) {
                    await ctx.reply(caption + '\n\n⚠️ (Rasm yuklanmadi)', { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                }
            } else {
                await ctx.reply(caption, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
            }
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    // ✏️ Banner tahrirlash β€” Sarlavha
    bot.action(/banner_set_title_(.+)/, (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'banner_edit_title', bannerId: ctx.match[1] };
        ctx.answerCbQuery();
        ctx.reply('πŸ“Œ Banner uchun yangi *sarlavha* yozing:\n\n_Masalan: "Yozgi Chegirma 50%"_', { parse_mode: 'Markdown' });
    });

    // ✏️ Banner tahrirlash β€” Subtitle
    bot.action(/banner_set_subtitle_(.+)/, (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'banner_edit_subtitle', bannerId: ctx.match[1] };
        ctx.answerCbQuery();
        ctx.reply('πŸ“ Banner uchun *qo\'shimcha matn* yozing:\n\n_Masalan: "Barcha kiyimlarga amal qiladi"_\n\nO\'tkazish uchun "yoq" deb yozing.', { parse_mode: 'Markdown' });
    });

    // πŸ”— Banner tahrirlash β€” Link
    bot.action(/banner_set_link_(.+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        const bannerId = ctx.match[1];
        ctx.answerCbQuery();
        const categories = await Category.find().sort({ order: 1 });
        const buttons = [
            [Markup.button.callback('❌ Havolasiz', `banner_link_none_${bannerId}`)]
        ];
        let row = [];
        categories.forEach((c, i) => {
            row.push(Markup.button.callback(`πŸ“ ${c.name}`, `banner_link_cat_${bannerId}_${c.name}`));
            if (row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; }
        });
        buttons.push([Markup.button.callback('πŸ”— Tashqi URL', `banner_link_url_${bannerId}`)]);
        buttons.push([Markup.button.callback('πŸ”™ Orqaga', `banner_view_${bannerId}`)]);
        ctx.reply('πŸ”— *Banner havolasini tanlang:*\n\nFoydalanuvchi bannerni bosganda qayerga yo\'naltirilsin?', { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
    });

    bot.action(/banner_link_none_(.+)/, async (ctx) => {
        await Banner.findByIdAndUpdate(ctx.match[1], { linkType: 'none', linkValue: '' });
        ctx.answerCbQuery('βœ… Havola olib tashlandi');
        try { ctx.deleteMessage(); } catch(e) {}
    });

    bot.action(/banner_link_cat_([^_]+)_(.+)/, async (ctx) => {
        const bannerId = ctx.match[1];
        const catName = ctx.match[2];
        await Banner.findByIdAndUpdate(bannerId, { linkType: 'category', linkValue: catName });
        ctx.answerCbQuery(`βœ… Havola: ${catName} kategoriyasi`);
        try { ctx.deleteMessage(); } catch(e) {}
    });

    bot.action(/banner_link_url_(.+)/, (ctx) => {
        appState[ctx.from.id] = { step: 'banner_edit_link_url', bannerId: ctx.match[1] };
        ctx.answerCbQuery();
        ctx.reply('πŸ”— Tashqi URL manzilini yozing:\n\n_Masalan: https://example.com_', { parse_mode: 'Markdown' });
    });

    // πŸ“… Banner tahrirlash β€” Muddat
    bot.action(/banner_set_expire_(.+)/, (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'banner_edit_expire', bannerId: ctx.match[1] };
        ctx.answerCbQuery();
        ctx.reply('πŸ“… Banner tugash sanasini yozing:\n\n_Format: KK.OO.YYYY (masalan: 01.06.2026)_\n\nMuddatsiz qilish uchun "yoq" deb yozing.', { parse_mode: 'Markdown' });
    });

    // πŸ”€ Tartibni o'zgartirish
    bot.action('banner_reorder', async (ctx) => {
        if (!isAdmin(ctx)) return;
        try {
            const banners = await Banner.find({ isActive: true }).sort({ order: 1 });
            if (banners.length < 2) return ctx.answerCbQuery('Kamida 2 ta banner kerak');
            
            let msg = `πŸ”€ *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`;
            const buttons = [];
            banners.forEach((b, i) => {
                const titleStr = b.title || `Banner ${i + 1}`;
                msg += `*${i + 1}.* ${titleStr}\n`;
                const row = [];
                if (i > 0) row.push(Markup.button.callback(`⬆️ ${i + 1}`, `banner_moveup_${b._id}`));
                if (i < banners.length - 1) row.push(Markup.button.callback(`⬇️ ${i + 1}`, `banner_movedn_${b._id}`));
                if (row.length > 0) buttons.push(row);
            });
            buttons.push([Markup.button.callback('πŸ”™ Orqaga', 'action_banners')]);
            
            await ctx.answerCbQuery();
            try { ctx.deleteMessage(); } catch(e) {}
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    bot.action(/banner_moveup_(.+)/, async (ctx) => {
        try {
            const banners = await Banner.find({ isActive: true }).sort({ order: 1 });
            const idx = banners.findIndex(b => b._id.toString() === ctx.match[1]);
            if (idx > 0) {
                const tempOrder = banners[idx].order;
                banners[idx].order = banners[idx - 1].order;
                banners[idx - 1].order = tempOrder;
                await banners[idx].save();
                await banners[idx - 1].save();
            }
            ctx.answerCbQuery('⬆️ Yuqoriga ko\'tarildi');
            // Refreshing banner list
            try { ctx.deleteMessage(); } catch(e) {}
            // Re-trigger reorder view
            const updatedBanners = await Banner.find({ isActive: true }).sort({ order: 1 });
            let msg = `πŸ”€ *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`;
            const buttons = [];
            updatedBanners.forEach((b, i) => {
                msg += `*${i + 1}.* ${b.title || 'Banner ' + (i+1)}\n`;
                const row = [];
                if (i > 0) row.push(Markup.button.callback(`⬆️ ${i + 1}`, `banner_moveup_${b._id}`));
                if (i < updatedBanners.length - 1) row.push(Markup.button.callback(`⬇️ ${i + 1}`, `banner_movedn_${b._id}`));
                if (row.length > 0) buttons.push(row);
            });
            buttons.push([Markup.button.callback('πŸ”™ Orqaga', 'action_banners')]);
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    bot.action(/banner_movedn_(.+)/, async (ctx) => {
        try {
            const banners = await Banner.find({ isActive: true }).sort({ order: 1 });
            const idx = banners.findIndex(b => b._id.toString() === ctx.match[1]);
            if (idx < banners.length - 1) {
                const tempOrder = banners[idx].order;
                banners[idx].order = banners[idx + 1].order;
                banners[idx + 1].order = tempOrder;
                await banners[idx].save();
                await banners[idx + 1].save();
            }
            ctx.answerCbQuery('⬇️ Pastga tushirildi');
            try { ctx.deleteMessage(); } catch(e) {}
            const updatedBanners = await Banner.find({ isActive: true }).sort({ order: 1 });
            let msg = `πŸ”€ *TARTIBNI O'ZGARTIRISH*\n${line}\n\n`;
            const buttons = [];
            updatedBanners.forEach((b, i) => {
                msg += `*${i + 1}.* ${b.title || 'Banner ' + (i+1)}\n`;
                const row = [];
                if (i > 0) row.push(Markup.button.callback(`⬆️ ${i + 1}`, `banner_moveup_${b._id}`));
                if (i < updatedBanners.length - 1) row.push(Markup.button.callback(`⬇️ ${i + 1}`, `banner_movedn_${b._id}`));
                if (row.length > 0) buttons.push(row);
            });
            buttons.push([Markup.button.callback('πŸ”™ Orqaga', 'action_banners')]);
            ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
        } catch(e) { ctx.answerCbQuery('Xato'); }
    });

    // βž• Yangi banner qo'shish (rasm yuklash)
    bot.action('banner_add_photo', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'banner_wizard_photo' };
        ctx.answerCbQuery();
        ctx.reply(`πŸ“Έ *YANGI BANNER QO'SHISH* (1/4)\n${thinLine}\n\nπŸ–Ό Rasm yuboring (Landscape / Yotqizilgan format tavsiya etiladi):`, { parse_mode: 'Markdown' });
    });

    // πŸ—‘ Banner o'chirish β€” Tasdiqlash
    bot.action(/banner_del_confirm_(.+)/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        const bannerId = ctx.match[1];
        console.log('[BANNER DELETE] Confirm requested for:', bannerId);
        try { await ctx.answerCbQuery(); } catch(e) {}
        try { await ctx.deleteMessage(); } catch(e) {}
        await ctx.reply('⚠️ *Bannerni o\'chirmoqchimisiz?*\n\nBu amalni ortga qaytarib bo\'lmaydi.', {
            parse_mode: 'Markdown',
            ...Markup.inlineKeyboard([
                [Markup.button.callback('βœ… Ha, o\'chirish', `bdel_${bannerId}`), Markup.button.callback('❌ Yo\'q', 'action_banners')]
            ])
        });
    });

    // πŸ—‘ Banner o'chirish β€” Yakuniy bajarish (ikkala nom ham ishlaydi)
    async function executeBannerDelete(ctx, bannerId) {
        console.log('[BANNER DELETE] Executing for:', bannerId);
        try {
            const result = await Banner.findByIdAndDelete(bannerId);
            console.log('[BANNER DELETE] Result:', result ? 'OK Deleted' : 'Not found in DB');
            try { await ctx.answerCbQuery('βœ… O\'chirildi!'); } catch(e) {}
            try { await ctx.deleteMessage(); } catch(e) {}
            await ctx.reply('βœ… Banner muvaffaqiyatli o\'chirildi!', getMainMenu());
        } catch(e) {
            console.error('[BANNER DELETE] DB Error:', e.message);
            try { await ctx.answerCbQuery('❌ Xato'); } catch(e2) {}
            await ctx.reply('❌ Xatolik: ' + e.message, getMainMenu());
        }
    }
    bot.action(/^bdel_(.+)$/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        await executeBannerDelete(ctx, ctx.match[1]);
    });
    bot.action(/^banner_del_exec_(.+)$/, async (ctx) => {
        if (!isAdmin(ctx)) return;
        await executeBannerDelete(ctx, ctx.match[1]);
    });

    // ==========================================
    // 🎨 AI BANNER YARATISH β€” PREMIUM V2.0
    // ==========================================
    bot.action('banner_ai_menu', (ctx) => {
        if (!isAdmin(ctx)) return;
        ctx.answerCbQuery();
        const buttons = [];
        const templateKeys = Object.keys(aiTemplates);
        let row = [];
        templateKeys.forEach((key, i) => {
            row.push(Markup.button.callback(aiTemplates[key].label, `ai_tpl_${key}`));
            if (row.length === 2 || i === templateKeys.length - 1) { buttons.push(row); row = []; }
        });
        buttons.push([Markup.button.callback('✍️ Erkin yozish', 'ai_free_prompt')]);
        buttons.push([Markup.button.callback('πŸ”™ Orqaga', 'action_banners')]);
        
        try { ctx.deleteMessage(); } catch(e) {}
        ctx.reply(`🎨 *AI BANNER YARATISH*\n${line}\n\nQanday turdagi banner kerak?\nShablon tanlang yoki erkin yozing:`, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
    });

    // Shablon tanlanganda
    bot.action(/ai_tpl_(.+)/, (ctx) => {
        if (!isAdmin(ctx)) return;
        const templateKey = ctx.match[1];
        const template = aiTemplates[templateKey];
        if (!template) return ctx.answerCbQuery('Shablon topilmadi');
        
        appState[ctx.from.id] = { step: 'ai_template_prompt', templateKey, templateBase: template.base };
        ctx.answerCbQuery();
        ctx.reply(`🎨 *${template.label} shabloni tanlandi!*\n\nEndi qo'shimcha tavsif bering (o'zbekchada):\n\n_Masalan: "chiroyli qizil kiyimlar, yozgi kolleksiya"_\n\nπŸ’‘ _Yoki batafsil yozmang β€” shunchaki_ "davom" _deb yozing_`, { parse_mode: 'Markdown' });
    });

    // Erkin prompt
    bot.action('ai_free_prompt', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'ai_free_prompt_input' };
        ctx.answerCbQuery();
        ctx.reply(`✍️ *ERKIN AI BANNER*\n${thinLine}\n\nRasmda nima bo'lishini o'zbekcha yoki inglizcha batafsil yozing:\n\n_"Kiyimlar chegirmasi, yozgi aksiya"_\n_"Yangi yil sovg'alari, bayram kayfiyati"_\n_"Go'zal ayollar kiyimlari, zamonaviy moda"_\n\nπŸ’‘ _Qancha batafsil yozsangiz, shuncha sifatli rasm!_`, { parse_mode: 'Markdown' });
    });

    // AI rasmni 2 variantda yaratish funksiyasi (ENG KUCHLI BEPUL MODELLAR)
    async function generateAIBannerVariants(ctx, finalPrompt, originalPrompt) {
        const userId = ctx.from.id;
        const ts1 = Date.now();
        const ts2 = ts1 + 12345;
        const encoded = encodeURIComponent(finalPrompt);
        
        // 2026 yildagi eng kuchli bepul modellar (Pollinations orqali):
        // Variant 1: GPT Image (OpenAI DALL-E darajasi β€” eng sifatli)
        // Variant 2: Seedream5 (Google DeepMind β€” fotorealistik)
        const url1 = `https://image.pollinations.ai/prompt/${encoded}?width=1024&height=430&seed=${ts1}&nologo=true&model=gptimage`;
        const url2 = `https://image.pollinations.ai/prompt/${encoded}?width=1024&height=430&seed=${ts2}&nologo=true&model=seedream5`;
        
        try {
            await ctx.reply('⏳ *2 ta super model* ishga tushmoqda...\n\nπŸ”Ή GPT Image (OpenAI)\nπŸ”Ή Seedream5 (Google)\n\n_Kuting, 20-60 soniya..._', { parse_mode: 'Markdown' });
            
            // Ikkalasini xavfsiz yuklab olish qotib qolmasligi uchun biroz kutamiz (stagger resquests)
            let res1, res2;
            try { res1 = await downloadImage(url1); } catch (err) { res1 = null; console.error("URL1 fail:", err); }
            await new Promise(r => setTimeout(r, 1000)); // 1 soniya pauza
            try { res2 = await downloadImage(url2); } catch (err) { res2 = null; console.error("URL2 fail:", err); }
            
            let msg1, msg2;
            let fileId1 = null, fileId2 = null;

            // 1-variant tekshiriladi
            if (res1) {
                msg1 = await ctx.replyWithPhoto({ source: res1, filename: 'variant1.jpg' }, {
                    caption: `🎨 *Variant 1 β€” GPT Image (OpenAI)*\nπŸ“ _"${originalPrompt}"_`,
                    parse_mode: 'Markdown',
                    ...Markup.inlineKeyboard([[Markup.button.callback('βœ… Shu rasmni tanlash', 'ai_pick_1')]])
                });
                fileId1 = msg1.photo[msg1.photo.length - 1].file_id;
            } else {
                await ctx.reply('⚠️ Variant 1 ni yuklab olishda serverda xatolik yuz berdi.');
            }

            // 2-variant tekshiriladi
            if (res2) {
                msg2 = await ctx.replyWithPhoto({ source: res2, filename: 'variant2.jpg' }, {
                    caption: `🎨 *Variant 2 β€” Seedream5 (Google)*\nπŸ“ _"${originalPrompt}"_`,
                    parse_mode: 'Markdown',
                    ...Markup.inlineKeyboard([[Markup.button.callback('βœ… Shu rasmni tanlash', 'ai_pick_2')]])
                });
                fileId2 = msg2.photo[msg2.photo.length - 1].file_id;
            } else {
                await ctx.reply('⚠️ Variant 2 ni yuklab olishda serverda xatolik yuz berdi.');
            }

            if (!fileId1 && !fileId2) {
                throw new Error("Ikkala rasm ham yuklanmadi. Iltimos, qayta urining.");
            }
            
            appState[userId] = { 
                step: 'ai_picking_variant', 
                lastPrompt: originalPrompt,
                finalPrompt,
                fileId1, fileId2
            };
            
            await ctx.reply('Qaysi variantni tanlaysiz? Yoki qayta yarating:', {
                ...Markup.inlineKeyboard([
                    [Markup.button.callback('πŸ”„ Qayta yaratish (2 variant)', 'ai_regenerate_v2')],
                    [Markup.button.callback('❌ Bekor qilish', 'action_banners')]
                ])
            });
        } catch(e) {
            ctx.reply('❌ AI rasm yaratishda xatolik: ' + e.message + '\nQayta urinib ko\'ring.', getMainMenu());
            delete appState[userId];
        }
    }

    // Variant tanlash
    bot.action('ai_pick_1', async (ctx) => {
        if (!isAdmin(ctx)) return;
        const state = appState[ctx.from.id];
        if (!state || !state.fileId1) return ctx.answerCbQuery('Variant topilmadi');
        await saveAIBannerFromFileId(ctx, state.fileId1, state.lastPrompt);
    });

    bot.action('ai_pick_2', async (ctx) => {
        if (!isAdmin(ctx)) return;
        const state = appState[ctx.from.id];
        if (!state || !state.fileId2) return ctx.answerCbQuery('Variant topilmadi');
        await saveAIBannerFromFileId(ctx, state.fileId2, state.lastPrompt);
    });

    // AI rasmni file_id orqali saqlash (TO'G'RI USUL)
    async function saveAIBannerFromFileId(ctx, fileId, title) {
        try {
            const imgUrl = `https://ibrohm-savdobotadmin.hf.space/api/image/${fileId}`;
            const bannerCount = await Banner.countDocuments({ isActive: true });
            await new Banner({ 
                imageUrl: imgUrl, 
                title: title || '', 
                order: bannerCount,
                isActive: true
            }).save();
            ctx.answerCbQuery('βœ… Saqlandi!');
            try { await ctx.deleteMessage(); } catch(e) {}
            ctx.reply(`βœ… AI banner saqlandi va ilovada ko'rinadi!\n\nπŸ“Œ _Sarlavha, havola va muddatni "🏞 Reklamalar" bo'limidan tahrirlashingiz mumkin._`, { parse_mode: 'Markdown', ...getMainMenu() });
        } catch(e) { ctx.answerCbQuery('Xato: ' + e.message); }
        delete appState[ctx.from.id];
    }

    // Qayta yaratish (2 variant)
    bot.action('ai_regenerate_v2', async (ctx) => {
        if (!isAdmin(ctx)) return;
        const state = appState[ctx.from.id];
        if (state && state.finalPrompt) {
            ctx.answerCbQuery('πŸ”„ Qayta yaratilmoqda...');
            try { ctx.deleteMessage(); } catch(e) {}
            await generateAIBannerVariants(ctx, state.finalPrompt, state.lastPrompt);
        } else {
            ctx.answerCbQuery('Avval tavsif yozing');
        }
    });

    // Eski ai_regenerate va ai_save_last funksiyalari xavfsizlik va optimizatsiya maqsadida o'chirildi (V3.6)

    // ==========================================
    // MATN XABARLARI
    // ==========================================
    bot.on('text', async (ctx) => {
        const userId = ctx.from.id;
        if (!isAdmin(ctx)) return;
        const state = appState[userId];
        if (!state) return;
        const text = ctx.message.text;

        // Katgeoriya edit/add
        if (state.step === 'adding_category') {
            try {
                await new Category({ name: text }).save();
                ctx.reply(`βœ… *${text}* kategoriyasi qo'shildi!`, { parse_mode: 'Markdown', ...getMainMenu() });
            } catch(e) { ctx.reply('Xato (ehtimol oldin qo\'shilgan)'); }
            delete appState[userId]; return;
        }
        if (state.step === 'editing_category') {
            try {
                await Category.findByIdAndUpdate(state.catId, { name: text });
                ctx.reply(`βœ… Kategoriya yangilandi!`, getMainMenu());
            } catch(e) {}
            delete appState[userId]; return;
        }

        // ══════ B2C Kassir Qidiruv (Variant 2) ══════
        if (state.step === 'searching_order') {
            try {
                const searchTxt = text.trim();
                let order = null;
                
                // Mongoose ObjectId orqali qidirish (24 hex characters)
                if (/^[0-9a-fA-F]{24}$/.test(searchTxt)) {
                    order = await Order.findById(searchTxt);
                } 
                // Agar qisqa qidiruv bo'lsa
                if (!order) {
                    const match = await Order.find({ _id: { $regex: searchTxt, $options: 'i' } }).limit(1);
                    if (match && match.length > 0) order = match[0];
                }

                if (!order) {
                    ctx.reply('❌ Buyurtma topilmadi. Raqamni tekshirib qayta yuboring:', { reply_markup: { force_reply: true } });
                    return; // Return so they can try again without dropping state
                }

                let productsText = "";
                order.products.forEach(p => { 
                    productsText += `β€” ${p.name} (${p.quantity} ta) x ${formatPrice(p.price)}\n`; 
                });
                
                const statusEmoji = order.status === 'Kutilmoqda' ? '⏳' : order.status === 'Xaridorga topshirildi' ? 'βœ…' : order.status === 'Olib ketishga tayyor' ? 'πŸ›' : 'πŸ“₯';
                const msg = `🧾 *TOPILDI β€” ID:* \`${order._id}\`\n${thinLine}\n` +
                            `πŸ‘€ Mijoz: *${order.customerName}*\nπŸ“ž Tel: ${order.phone}\n\nπŸ“ *Tovarlar:*\n${productsText}\n` +
                            `πŸ’° *Jami summa:* ${formatPrice(order.totalAmount)} so'm\n\n` +
                            `Hozirgi holati: ${statusEmoji} ${order.status}\n\n` +
                            `πŸ’³ *XARIDOR TO'LOV QILDIMI?*`;

                const buttons = [
                    [Markup.button.callback('βœ… Pul Olindi (Yopish)', `order_status_deliver_${order._id}`)],
                    [Markup.button.callback('❌ Bekor Qilish', `order_status_cancel_${order._id}`)],
                    [Markup.button.callback('🏠 Menyu', 'action_home')]
                ];

                ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
            } catch (e) {
                ctx.reply('Xatolik yuz berdi: ' + e.message, getMainMenu());
            }
            delete appState[userId]; return;
        }


        // Mahsulot edit
        if (state.step === 'editing_price') {
            const num = Number(text);
            if (!isNaN(num)) {
                await Product.findByIdAndUpdate(state.productId, { price: num });
                ctx.reply('βœ… Narx yangilandi', getMainMenu());
            }
            delete appState[userId]; return;
        }
        if (state.step === 'edit_pname') {
            await Product.findByIdAndUpdate(state.pId, { name: text });
            ctx.reply('βœ… Nom yangilandi', getMainMenu());
            delete appState[userId]; return;
        }
        if (state.step === 'editing_desc') {
            await Product.findByIdAndUpdate(state.productId, { description: text });
            ctx.reply('βœ… Tavsif yangilandi', getMainMenu());
            delete appState[userId]; return;
        }
        if (state.step === 'edit_pimg') {
            await Product.findByIdAndUpdate(state.pId, { imageUrl: text === 'yoq' ? '' : text });
            ctx.reply('βœ… Rasm URL yangilandi', getMainMenu());
            delete appState[userId]; return;
        }
        if (state.step === 'edit_psize') {
            let sizes = [];
            if (text.toLowerCase() !== 'yoq') {
                sizes = text.split(',').map(s => s.trim()).filter(s => s.length > 0);
            }
            await Product.findByIdAndUpdate(state.pId, { sizes: sizes });
            ctx.reply('βœ… Razmerlar yangilandi', getMainMenu());
            delete appState[userId]; return;
        }

        // Banner tahrirlash β€” Sarlavha
        if (state.step === 'banner_edit_title') {
            try {
                await Banner.findByIdAndUpdate(state.bannerId, { title: text });
                ctx.reply('βœ… Sarlavha yangilandi!', getMainMenu());
            } catch(e) { ctx.reply('Xato'); }
            delete appState[userId]; return;
        }
        if (state.step === 'banner_edit_subtitle') {
            try {
                const val = text.toLowerCase() === 'yoq' ? '' : text;
                await Banner.findByIdAndUpdate(state.bannerId, { subtitle: val });
                ctx.reply('βœ… Matn yangilandi!', getMainMenu());
            } catch(e) { ctx.reply('Xato'); }
            delete appState[userId]; return;
        }
        if (state.step === 'banner_edit_link_url') {
            try {
                await Banner.findByIdAndUpdate(state.bannerId, { linkType: 'url', linkValue: text });
                ctx.reply('βœ… Havola yangilandi!', getMainMenu());
            } catch(e) { ctx.reply('Xato'); }
            delete appState[userId]; return;
        }
        if (state.step === 'banner_edit_expire') {
            try {
                if (text.toLowerCase() === 'yoq') {
                    await Banner.findByIdAndUpdate(state.bannerId, { expiresAt: null });
                    ctx.reply('βœ… Muddat olib tashlandi (muddatsiz).', getMainMenu());
                } else {
                    const parts = text.split('.');
                    if (parts.length === 3) {
                        const date = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
                        await Banner.findByIdAndUpdate(state.bannerId, { expiresAt: date });
                        ctx.reply(`βœ… Muddat belgilandi: ${text}`, getMainMenu());
                    } else {
                        ctx.reply('❌ Noto\'g\'ri format. KK.OO.YYYY (masalan: 01.06.2026)', getMainMenu());
                    }
                }
            } catch(e) { ctx.reply('Xato'); }
            delete appState[userId]; return;
        }

        // Banner wizard β€” sarlavha (2/4 qadam)
        if (state.step === 'banner_wizard_title') {
            state.bannerTitle = text;
            state.step = 'banner_wizard_link';
            const categories = await Category.find().sort({ order: 1 });
            const buttons = [
                [Markup.button.callback('❌ Havolasiz', 'bwiz_link_none')]
            ];
            let row = [];
            categories.forEach((c, i) => {
                row.push(Markup.button.callback(`πŸ“ ${c.name}`, `bwiz_link_cat_${c.name}`));
                if (row.length === 2 || i === categories.length - 1) { buttons.push(row); row = []; }
            });
            buttons.push([Markup.button.callback('πŸ”— Tashqi URL', 'bwiz_link_url')]);
            ctx.reply(`πŸ“Έ *YANGI BANNER* (3/4)\n${thinLine}\n\nπŸ”— Havola turini tanlang:`, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
            return;
        }

        // Banner wizard β€” URL kiritish
        if (state.step === 'banner_wizard_url') {
            state.bannerLinkType = 'url';
            state.bannerLinkValue = text;
            // Saqlash
            try {
                const bannerCount = await Banner.countDocuments({ isActive: true });
                await new Banner({
                    imageUrl: state.bannerImageUrl,
                    title: state.bannerTitle || '',
                    linkType: state.bannerLinkType || 'none',
                    linkValue: state.bannerLinkValue || '',
                    order: bannerCount,
                    isActive: true
                }).save();
                ctx.reply('βœ… Yangi banner saqlandi va ilovada ko\'rinadi!', getMainMenu());
            } catch(e) { ctx.reply('Xato: ' + e.message); }
            delete appState[userId]; return;
        }

        // AI Banner β€” Shablon bilan
        if (state.step === 'ai_template_prompt') {
            try {
                const userText = text.toLowerCase() === 'davom' ? '' : text;
                await ctx.reply('🧠 Gemini loyihangizni anglab, mukammal prompt tuzmoqda...');
                const finalPrompt = await enhancePromptWithGemini(userText, state.templateBase);
                appState[userId] = { step: 'ai_generating', lastPrompt: text, templateBase: state.templateBase, finalPrompt };
                await generateAIBannerVariants(ctx, finalPrompt, text || aiTemplates[state.templateKey]?.label || 'AI Banner');
            } catch (e) {
                console.error("ai_template_prompt error:", e);
                ctx.reply('❌ Kechirasiz, tarmoqda uzilish yuz berdi. Iltimos qayta urining.', getMainMenu());
                delete appState[userId];
            }
            return;
        }

        // AI Banner β€” Erkin yozish
        if (state.step === 'ai_free_prompt_input') {
            try {
                await ctx.reply('🧠 Gemini sizning fikringiz asosida mukammal prompt tuzmoqda...');
                const finalPrompt = await enhancePromptWithGemini(text);
                appState[userId] = { step: 'ai_generating', lastPrompt: text, finalPrompt };
                await generateAIBannerVariants(ctx, finalPrompt, text);
            } catch (e) {
                console.error("ai_free_prompt_input error:", e);
                ctx.reply('❌ Kechirasiz, tarmoqda xatolik yuz berdi. Iltimos qayta urining.', getMainMenu());
                delete appState[userId];
            }
            return;
        }

        // Qidiruv
        if (state.step === 'searching_product') {
            try {
                const results = await Product.find({ name: { $regex: text, $options: 'i' } }).limit(10);
                if (results.length === 0) return ctx.reply('πŸ“­ Bunday tovar topilmadi.', getMainMenu());
                
                await ctx.reply(`πŸ” *Natijalar:* (${results.length} ta)`, { parse_mode: 'Markdown' });
                for(let p of results) {
                    const msg = `🏷 *${p.name}*\nπŸ’° Narx: *${formatPrice(p.price)} sum*`;
                    const buttons = [
                        [Markup.button.callback('✏️ Nomi', `edit_pname_${p._id}`), Markup.button.callback('✏️ Narx', `edit_price_${p._id}`)],
                        [Markup.button.callback('πŸ“ Tavsif', `edit_desc_${p._id}`), Markup.button.callback('πŸ“Έ Rasm', `edit_pimg_${p._id}`)],
                        [Markup.button.callback('πŸ“ Razmer', `edit_psize_${p._id}`), Markup.button.callback('πŸ—‘ O\'chirish', `del_confirm_${p._id}`)]
                    ];
                    
                    if (p.imageUrl && p.imageUrl.startsWith('http')) {
                        try {
                            let photoSource = p.imageUrl;
                            if (photoSource.includes('/api/image/')) photoSource = photoSource.split('/api/image/')[1];
                            await ctx.replyWithPhoto(photoSource, { caption: msg, parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                        } catch(e) {
                            await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                        }
                    } else {
                        await ctx.reply(msg, { parse_mode: 'Markdown', ...Markup.inlineKeyboard(buttons) });
                    }
                }
            } catch(e) {}
            delete appState[userId]; return;
        }

        // Yangi Tovar wizard
        if (state.step === 'name') {
            state.name = text; state.step = 'description';
            ctx.reply('πŸ“„ 2-qadam: Tavsifni yozing:');
        } else if (state.step === 'description') {
            state.description = text; state.step = 'price';
            ctx.reply('πŸ’° 3-qadam: Narxni yozing (son):');
        } else if (state.step === 'price') {
            state.price = Number(text) || 0; state.step = 'category';
            const categories = await Category.find();
            if(categories.length === 0) return ctx.reply('Kategoriya yo\'q! Avval yarating.');
            const buttons = []; let row = [];
            categories.forEach((c, i) => {
                row.push(Markup.button.callback(c.name, `set_add_cat_${c.name}`));
                if(row.length === 2 || i === categories.length-1) { buttons.push(row); row = []; }
            });
            ctx.reply('πŸ“ 4-qadam: Kategoriyani tanlang:', Markup.inlineKeyboard(buttons));
        } else if (state.step === 'sizes') {
            state.sizes = [];
            if (text.toLowerCase() !== 'yoq') {
                state.sizes = text.split(',').map(s => s.trim()).filter(s => s.length > 0);
            }
            state.step = 'image';
            ctx.reply('πŸ–Ό 6-qadam: Rasm URL yozing yoki rasmni yuboring ("yoq" xam mumkin):');
        } else if (state.step === 'image') {
            state.imageUrl = text === 'yoq' ? '' : text;
            try {
                await new Product(state).save();
                ctx.reply('βœ… Tovar saqlandi!', getMainMenu());
            } catch(e) {}
            delete appState[userId];
            return;
        }

        // --- PUSH XABARNOMA ---
        if (state.step === 'push_title') {
            appState[userId] = { step: 'push_message', pushTitle: text };
            ctx.reply('πŸ“ 2-qadam: Xabar matnini yozing:');
            return;
        }
        if (state.step === 'push_message') {
            appState[userId] = { step: 'push_image', pushTitle: state.pushTitle, pushMessage: text };
            ctx.reply('πŸ–Ό 3-qadam: Ilovada chiqadigan rasm URL tasvirini yozing (yoki menga hozir rasm yuboring).\n\nAgar rasm kerakmas bo\'lsa "yoq" deb yozing:', { reply_markup: { force_reply: true } });
            return;
        }
        if (state.step === 'push_image') {
            const pushImage = text.toLowerCase() === 'yoq' ? '' : text;
            state.pushImage = pushImage;
            appState[userId] = { ...state, step: 'push_confirm' };
            ctx.reply(`πŸ“’ Siz quyidagi xabarni BARCHA mijoz telefonlariga (Push) yubormoqchisiz:\n\n*Sarlavha:* ${state.pushTitle}\n*Matn:* ${state.pushMessage}\n*Rasm:* ${pushImage ? 'Ulangan' : 'Yo\'q'}\n\nβœ… Xabarni tasdiqlaysizmi? (ha / yo'q)`, { parse_mode: 'Markdown' });
            return;
        }
        if (state.step === 'push_confirm') {
            if (text.toLowerCase() === 'ha') {
                ctx.reply('⏳ Xabar yuborilmoqda...');
                const { sendPushToAll } = require('./firebase');
                sendPushToAll(state.pushTitle, state.pushMessage, state.pushImage).then(res => {
                    if (res.success) {
                        ctx.reply('βœ… Xabar muvaffaqiyatli HAMMAGA tarqatildi!', getMainMenu());
                    } else {
                        ctx.reply('❌ Xatolik yuz berdi: ' + res.error, getMainMenu());
                    }
                });
            } else {
                ctx.reply('❌ Bekor qilindi.', getMainMenu());
            }
            delete appState[userId];
            return;
        }
    });

    bot.action(/set_add_cat_(.+)/, async (ctx) => {
        const state = appState[ctx.from.id];
        if(!state || state.step !== 'category') return;
        state.category = ctx.match[1];
        state.step = 'sizes';
        ctx.reply('πŸ‘• 5-qadam: Bu tovar qanday razmerlarda bor? Vergul bilan yozing (Masalan: 44, 46, 48).\nYoki razmersiz bo\'lsa "yoq" deb yozing:');
    });

    bot.on('photo', async (ctx) => {
        const userId = ctx.from.id;
        if (!isAdmin(ctx)) return;
        const state = appState[userId];
        if (!state) return;
        
        const photo = ctx.message.photo[ctx.message.photo.length - 1];
        const fileId = photo.file_id;
        // Rasmning haqiqiy ID sini olib dinamik url qaytarish, chunki Telegram url 1 soatda eskiredi
        const imgUrl = `https://ibrohm-savdobotadmin.hf.space/api/image/${fileId}`;

        if (state.step === 'image') {
            state.imageUrl = imgUrl;
            await new Product(state).save();
            ctx.reply('βœ… Tovar saqlandi!', getMainMenu());
            delete appState[userId];
        } else if(state.step === 'edit_pimg') {
            await Product.findByIdAndUpdate(state.pId, { imageUrl: imgUrl });
            ctx.reply('βœ… Rasm yangilandi!', getMainMenu());
            delete appState[userId];
        } else if(state.step === 'banner_wizard_photo') {
            // Banner wizard Step 1 β†’ go to step 2, ask for title
            appState[userId] = { ...state, step: 'banner_wizard_title', bannerImageUrl: imgUrl };
            ctx.reply(`πŸ“Έ *YANGI BANNER* (2/4)\n${thinLine}\n\nπŸ“Œ Banner uchun sarlavha yozing:\n\n_Masalan: "Yozgi Chegirma 50%"_\n\nO'tkazish uchun "yoq" deb yozing.`, { parse_mode: 'Markdown' });
        } else if(state.step === 'push_image') {
            state.pushImage = imgUrl;
            appState[userId] = { ...state, step: 'push_confirm' };
            ctx.reply(`πŸ“’ Siz quyidagi xabarni BARCHA mijoz telefonlariga (Push) yubormoqchisiz:\n\n*Sarlavha:* ${state.pushTitle}\n*Matn:* ${state.pushMessage}\n*Rasm:* Ulangan\n\nβœ… Xabarni tasdiqlaysizmi? (ha / yo'q)`, { parse_mode: 'Markdown' });
        }
    });

    bot.action('action_send_push', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'push_title' };
        ctx.answerCbQuery();
        ctx.reply('πŸ“’ *Xabarnoma yuborish (Push)*\n\n1-qadam: Xabar sarlavhasini yozing (Masalan: 🚨 YANGI CHEGIRMA!):', { parse_mode: 'Markdown', reply_markup: { force_reply: true } });
    });

    bot.action('action_set_location', (ctx) => {
        if (!isAdmin(ctx)) return;
        appState[ctx.from.id] = { step: 'set_store_location' };
        ctx.answerCbQuery();
        ctx.reply('πŸ“ *Do\'kon Manzilini o\'rnatish*\n\nTelegramning **πŸ“Ž Qistirish (Attachment)** tugmasini bosib, xaritadan **Location (Joylashuv)** yuboring.', { parse_mode: 'Markdown' });
    });

    bot.on('location', async (ctx) => {
        const userId = ctx.from.id;
        if (!isAdmin(ctx)) return;
        const state = appState[userId];
        if (!state || state.step !== 'set_store_location') return;

        const { latitude, longitude } = ctx.message.location;

        try {
            const Setting = require('../models/Setting');
            await Setting.findOneAndUpdate(
                { key: 'store_location' },
                { value: { lat: latitude, lng: longitude } },
                { upsert: true }
            );
            ctx.reply(`βœ… Do'kon manzili muvaffaqiyatli saqlandi!\nπŸ“ Koordinatalar: ${latitude}, ${longitude}\n\nIlovadan xaridorlar ushbu xaritani endi bemalol navigator orqali ochishlari mumkin!`, getMainMenu());
        } catch (e) {
            ctx.reply('❌ Saqlashda xatolik yuz berdi: ' + e.message, getMainMenu());
        }
        delete appState[userId];
    });

    // Banner wizard β€” Havola tanlash callbacklari
    bot.action('bwiz_link_none', async (ctx) => {
        const state = appState[ctx.from.id];
        if (!state) return;
        try {
            const bannerCount = await Banner.countDocuments({ isActive: true });
            await new Banner({
                imageUrl: state.bannerImageUrl,
                title: state.bannerTitle && state.bannerTitle.toLowerCase() !== 'yoq' ? state.bannerTitle : '',
                linkType: 'none',
                linkValue: '',
                order: bannerCount,
                isActive: true
            }).save();
            ctx.answerCbQuery('βœ… Saqlandi!');
            try { ctx.deleteMessage(); } catch(e) {}
            ctx.reply('βœ… Yangi banner saqlandi va ilovada ko\'rinadi!', getMainMenu());
        } catch(e) { ctx.answerCbQuery('Xato'); }
        delete appState[ctx.from.id];
    });

    bot.action(/bwiz_link_cat_(.+)/, async (ctx) => {
        const state = appState[ctx.from.id];
        if (!state) return;
        try {
            const bannerCount = await Banner.countDocuments({ isActive: true });
            await new Banner({
                imageUrl: state.bannerImageUrl,
                title: state.bannerTitle && state.bannerTitle.toLowerCase() !== 'yoq' ? state.bannerTitle : '',
                linkType: 'category',
                linkValue: ctx.match[1],
                order: bannerCount,
                isActive: true
            }).save();
            ctx.answerCbQuery('βœ… Saqlandi!');
            try { ctx.deleteMessage(); } catch(e) {}
            ctx.reply(`βœ… Banner saqlandi! Havola: πŸ“ ${ctx.match[1]}`, getMainMenu());
        } catch(e) { ctx.answerCbQuery('Xato'); }
        delete appState[ctx.from.id];
    });

    bot.action('bwiz_link_url', (ctx) => {
        const state = appState[ctx.from.id];
        if (!state) return;
        state.step = 'banner_wizard_url';
        ctx.answerCbQuery();
        ctx.reply('πŸ”— Tashqi URL manzilini yozing:', { parse_mode: 'Markdown' });
    });

    bot.launch().then(() => {
        console.log('πŸ€– Telegram Bot V4.0 Premium ishga tushdi.');
    }).catch((err) => {
        console.error('❌ Bot ishga tushmadi:', err.message);
    });
}

// ── Buyurtma holat tugmalari (notifyAdmin uchun) ────────────
const orderStatusButtonsForNotify = (orderId, currentStatus) => {
    const s = (label, status) => currentStatus === status ? `βœ… ${label}` : label;
    return Markup.inlineKeyboard([
        [
            Markup.button.callback(s('πŸ“₯ Yig\'ish', 'Yig\'ilmoqda'), `order_status_accept_${orderId}`),
            Markup.button.callback(s('πŸ› Tayyor', 'Olib ketishga tayyor'), `order_status_ship_${orderId}`)
        ],
        [
            Markup.button.callback(s('βœ… Topshirildi', 'Xaridorga topshirildi'), `order_status_deliver_${orderId}`),
            Markup.button.callback(s('❌ Bekor', 'Bekor qilindi'), `order_status_cancel_${orderId}`)
        ]
    ]);
};

// ── Admin Notification (Yangi buyurtma xabari) ──────────────
const notifyAdmin = async (orderInfo, orderId) => {
    try {
        if (bot && process.env.ADMIN_ID) {
            const msg = await bot.telegram.sendMessage(
                process.env.ADMIN_ID,
                orderInfo,
                { parse_mode: 'Markdown' }
            );
            
            if (orderId) {
                await bot.telegram.editMessageReplyMarkup(
                    process.env.ADMIN_ID,
                    msg.message_id,
                    null,
                    orderStatusButtonsForNotify(orderId, 'Kutilmoqda').reply_markup
                );
            }
        }
    } catch (e) {
        console.error('Adminga xabar yuborishda xato:', e.message);
    }
};

module.exports = { bot, notifyAdmin };