File size: 20,444 Bytes
89ec743
 
 
 
 
 
 
 
 
 
 
545959e
fff265a
7e47e6a
 
89ec743
 
 
 
 
bc118c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89ec743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc118c5
89ec743
 
 
 
 
bc118c5
89ec743
 
bc118c5
 
 
 
 
89ec743
bc118c5
89ec743
 
 
 
 
bc118c5
89ec743
 
 
 
 
 
bc118c5
89ec743
bc118c5
89ec743
 
bc118c5
 
89ec743
 
bc118c5
89ec743
 
bc118c5
89ec743
 
 
 
 
 
bc118c5
89ec743
 
 
 
 
 
bc118c5
89ec743
bfde415
 
 
89ec743
 
bc118c5
89ec743
bc118c5
 
 
 
 
 
89ec743
 
bc118c5
89ec743
 
bc118c5
89ec743
 
 
 
 
d22e23c
 
 
 
bc118c5
d22e23c
 
 
bc118c5
 
 
d22e23c
 
 
bc118c5
 
d22e23c
 
 
bc118c5
d22e23c
 
 
bc118c5
d22e23c
 
89ec743
 
 
 
 
 
 
 
6eb0ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89ec743
 
 
 
 
 
 
bc118c5
6eb0ba5
d22e23c
89ec743
d22e23c
 
 
 
 
 
bc118c5
89ec743
d22e23c
 
 
89ec743
 
 
 
 
d22e23c
 
 
 
 
 
 
bc118c5
d22e23c
 
 
 
 
 
 
 
 
bc118c5
d22e23c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc118c5
d22e23c
 
 
 
 
 
 
 
 
bc118c5
d22e23c
 
 
 
 
 
 
 
6eb0ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e47e6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b5ed19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eb0ba5
89ec743
 
 
 
 
 
 
6eb0ba5
89ec743
d22e23c
89ec743
 
 
 
 
 
 
 
 
d22e23c
89ec743
d22e23c
 
 
 
 
 
 
89ec743
d22e23c
 
89ec743
 
 
 
 
 
 
 
bc118c5
89ec743
bc118c5
89ec743
 
bc118c5
 
89ec743
 
 
 
 
bc118c5
 
89ec743
 
 
 
 
 
 
 
bc118c5
89ec743
bc118c5
89ec743
 
bc118c5
 
89ec743
 
 
 
 
bc118c5
 
89ec743
 
 
 
 
 
 
bc118c5
89ec743
 
 
 
bc118c5
89ec743
bc118c5
89ec743
 
 
 
 
 
bc118c5
89ec743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { Markup } = require('telegraf');
const User = require('../models/User');
const Product = require('../models/Product');
const Order = require('../models/Order');
const ExcelJS = require('exceljs');

// Helper to get Dashboard Buttons
const getDashboardButtons = () => {
    return [
        [Markup.button.callback("πŸ“Š Statistika", "admin_stats"), Markup.button.callback("πŸ“¦ Yangi buyurtmalar", "admin_orders_new")],
        [Markup.button.callback("βž• Mahsulot qo'shish", "admin_add_product"), Markup.button.callback("πŸ—‘ Mahsulot o'chirish", "admin_delete_product")],
        [Markup.button.callback("✏️ Mahsulotni tahrirlash", "admin_edit_product_list"), Markup.button.callback("πŸ‘₯ Foydalanuvchilar", "admin_users")],
        [Markup.button.callback("πŸ“‰ Excel Export", "admin_excel_export"), Markup.button.callback("πŸ“’ Reklama yuborish", "admin_broadcast")],
        [Markup.button.callback("πŸ”₯ Aksiya (Flash Sale)", "admin_flash_sale"), Markup.button.callback("πŸ“¦ Ombor Boshqaruvi", "admin_inventory")],
        [Markup.button.callback("βš™οΈ Do'kon Sozlamalari", "admin_settings"), Markup.button.callback("πŸ”‘ API Integratsiya", "admin_api")] // Added API Button
    ];
};

// Admin Dashboard Menu
exports.showDashboard = (ctx) => {
    // Middleware ensures ctx.i18n is present
    const i18n = ctx.i18n;
    const text = i18n.admin.dash_title;

    // Dynamic Buttons
    const buttons = [
        [Markup.button.callback(i18n.admin.btn_stats, "admin_stats"), Markup.button.callback(i18n.admin.btn_new_orders, "admin_orders_new")],
        [Markup.button.callback(i18n.admin.btn_add_prod, "admin_add_product"), Markup.button.callback(i18n.admin.btn_del_prod, "admin_delete_product")],
        [Markup.button.callback(i18n.admin.btn_edit_prod, "admin_edit_product_list"), Markup.button.callback(i18n.admin.btn_users, "admin_users")],
        [Markup.button.callback(i18n.admin.btn_excel, "admin_excel_export"), Markup.button.callback(i18n.admin.btn_broadcast, "admin_broadcast")],
        [Markup.button.callback(i18n.admin.btn_flash, "admin_flash_sale"), Markup.button.callback(i18n.admin.btn_inv, "admin_inventory")],
        [Markup.button.callback(i18n.admin.btn_settings, "admin_settings"), Markup.button.callback(i18n.admin.btn_api, "admin_api")]
    ];

    const keyboard = Markup.inlineKeyboard(buttons);

    try {
        if (ctx.callbackQuery) {
            ctx.editMessageText(text, { parse_mode: 'Markdown', ...keyboard }).catch(e => ctx.replyWithMarkdown(text, keyboard));
        } else {
            ctx.replyWithMarkdown(text, keyboard);
        }
    } catch (e) {
        ctx.replyWithMarkdown(text, keyboard);
    }
};

// Statistics
exports.showStats = async (ctx) => {
    try {
        const i18n = ctx.i18n;
        const userCount = await User.countDocuments();
        const productCount = await Product.countDocuments();
        const orders = await Order.find();

        const revenue = orders
            .filter(o => o.status === 'completed' || o.status === 'delivered')
            .reduce((sum, o) => sum + o.total, 0);

        const text = `${i18n.admin.stats_title}\n\n` +
            `${i18n.admin.stats_users}: ${userCount}\n` +
            `${i18n.admin.stats_prods}: ${productCount}\n` +
            `${i18n.admin.stats_orders}: ${orders.length}\n` +
            `${i18n.admin.stats_rev}: ${revenue.toLocaleString()} ${i18n.currency}`;

        const keyboard = Markup.inlineKeyboard([[Markup.button.callback(i18n.admin.back, "admin_dashboard")]]);

        ctx.editMessageText(text, { parse_mode: 'HTML', ...keyboard })
            .catch(e => ctx.replyWithHTML(text, keyboard));
    } catch (err) {
        console.error(err);
        ctx.answerCbQuery(ctx.i18n.admin.error);
    }
};

// Show New Orders
exports.showNewOrders = async (ctx) => {
    try {
        const i18n = ctx.i18n;
        const orders = await Order.find({ status: 'new' });
        const backBtn = [Markup.button.callback(i18n.admin.back, "admin_dashboard")];

        if (!orders || orders.length === 0) {
            return ctx.editMessageText(i18n.admin.no_new_orders, Markup.inlineKeyboard([backBtn]))
                .catch(e => ctx.reply(i18n.admin.no_new_orders, Markup.inlineKeyboard([backBtn])));
        }

        const orderButtons = orders.map(o => [Markup.button.callback(`#${o.id} - ${o.total.toLocaleString()} ${i18n.currency}`, `admin_order_${o.id}`)]);
        orderButtons.push(backBtn);

        const text = `${i18n.admin.btn_new_orders}: ${orders.length}`;
        const keyboard = Markup.inlineKeyboard(orderButtons);

        ctx.editMessageText(text, { parse_mode: 'Markdown', ...keyboard })
            .catch(e => ctx.replyWithMarkdown(text, keyboard));
    } catch (err) {
        console.error(err);
        ctx.answerCbQuery(ctx.i18n.admin.error);
    }
};

// View Single Order Details
exports.viewOrder = async (ctx, orderId) => {
    try {
        const i18n = ctx.i18n;
        const id = parseInt(orderId);

        if (isNaN(id)) return ctx.answerCbQuery("❌ Invalid Order ID");

        const order = await Order.findOne({ id: id });

        if (!order) return ctx.answerCbQuery("Buyurtma topilmadi."); // Low Priority to localize this tiny string fallback

        let text = `${i18n.admin.order_title}${order.id}**\n` +
            `${i18n.admin.client}: ${order.user}\n` +
            `${i18n.admin.tel}: ${order.phone}\n` +
            `${i18n.admin.date}: ${new Date(order.createdAt).toLocaleString()}\n` +
            `${i18n.admin.status_label}: ${order.status.toUpperCase()}\n\n` +
            `${i18n.admin.items}\n`;

        order.items.forEach(i => {
            text += `- ${i.name} (${i.count}x) - ${i.price.toLocaleString()} ${i18n.currency}\n`;
        });

        text += `\n${i18n.admin.total_label} ${order.total.toLocaleString()} ${i18n.currency}`;

        if (order.location) {
            ctx.replyWithLocation(order.location.latitude, order.location.longitude);
        }

        // Dynamic Buttons based on Status
        let actionButtons = [];
        if (order.status === 'new') {
            actionButtons = [
                [Markup.button.callback(i18n.admin.btn_accept, `order_accept_${order.id}`), Markup.button.callback(i18n.admin.btn_reject, `order_reject_${order.id}`)]
            ];
        } else if (order.status === 'accepted') {
            actionButtons = [
                [Markup.button.callback(i18n.admin.btn_invoice, `gen_invoice_${order.id}`)],
                [Markup.button.callback(i18n.admin.btn_ship, `order_ship_${order.id}`)],
                [Markup.button.callback(i18n.admin.btn_reject, `order_reject_${order.id}`)]
            ];
        } else if (order.status === 'shipping') {
            actionButtons = [
                [Markup.button.callback(i18n.admin.btn_deliver, `order_deliver_${order.id}`)],
                [Markup.button.callback(i18n.admin.btn_reject, `order_reject_${order.id}`)]
            ];
        } else if (order.status === 'delivered') {
            actionButtons = [
                [Markup.button.callback(i18n.admin.btn_archive, "admin_orders_new")]
            ];
        }

        actionButtons.push([Markup.button.callback(i18n.admin.back, "admin_orders_new")]);

        const contextKeyboard = Markup.inlineKeyboard(actionButtons);

        ctx.editMessageText(text, { parse_mode: 'HTML', ...contextKeyboard })
            .catch(e => ctx.replyWithHTML(text, contextKeyboard));
    } catch (err) {
        console.error(err);
    }
};

// Helper: Generate Invoice Text
const generateInvoice = (order) => {
    const date = new Date(order.createdAt).toLocaleString('uz-UZ');
    let items = "";
    order.items.forEach(i => {
        items += `- ${i.name} (${i.count}x) : ${i.price.toLocaleString()} so'm\n`;
    });

    return `🧾 **CHECK**\n\n` +
        `πŸ†” Buyurtma: #${order.id}\n` +
        `πŸ“… Sana: ${date}\n` +
        `πŸ‘€ Mijoz: ${order.user} (${order.phone})\n` +
        `πŸ’³ To'lov: ${order.paymentMethod === 'click' ? 'Click/Karta' : 'Naqd'}\n` +
        `------------------------------\n` +
        `${items}` +
        `------------------------------\n` +
        `πŸ’° **JAMI: ${order.total.toLocaleString()} so'm**\n\n` +
        `βœ… Status: TO'LANDI`;
};

// Accept Order
exports.acceptOrder = async (ctx, orderId) => {
    try {
        const id = parseInt(orderId);
        await Order.updateOne({ id: id }, { status: 'accepted' });
        const order = await Order.findOne({ id: id });

        ctx.answerCbQuery(ctx.i18n.admin.alert_accepted);

        // Notify User
        if (order) {
            const User = require('../models/User');
            const locales = require('../locales');
            const user = await User.findOne({ id: order.userId });
            const lang = (user && user.language) ? user.language : 'uz';
            const i18n = locales[lang] || locales.uz;

            ctx.telegram.sendMessage(order.userId, `${i18n.status_accepted}\n#${id} ${i18n.status_proccess || "Accepted"}.`);
        }

        // Refresh View
        exports.viewOrder(ctx, id);
    } catch (err) {
        console.error(err);
    }
};

// Ship Order
exports.shipOrder = async (ctx, orderId) => {
    try {
        const id = parseInt(orderId);
        await Order.updateOne({ id: id }, { status: 'shipping' });
        const order = await Order.findOne({ id: id });

        ctx.answerCbQuery(ctx.i18n.admin.alert_shipping);

        // Notify User
        if (order) {
            const User = require('../models/User');
            const locales = require('../locales');
            const user = await User.findOne({ id: order.userId });
            const lang = (user && user.language) ? user.language : 'uz';
            const i18n = locales[lang] || locales.uz;

            ctx.telegram.sendMessage(order.userId, `${i18n.status_shipping}\n#${id}`);
        }

        exports.viewOrder(ctx, id);
    } catch (e) {
        console.error(e);
    }
};

// Deliver Order
exports.deliverOrder = async (ctx, orderId) => {
    try {
        const id = parseInt(orderId);
        await Order.updateOne({ id: id }, { status: 'delivered' });
        const order = await Order.findOne({ id: id });

        ctx.answerCbQuery(ctx.i18n.admin.alert_delivered);

        // Notify User
        if (order) {
            const User = require('../models/User');
            const locales = require('../locales');
            const user = await User.findOne({ id: order.userId });
            const lang = (user && user.language) ? user.language : 'uz';
            const i18n = locales[lang] || locales.uz;

            ctx.telegram.sendMessage(order.userId, `${i18n.status_delivered}\n#${id}`);
        }

        exports.viewOrder(ctx, id);
    } catch (e) {
        console.error(e);
    }
};

// Generate Invoice Action Handler
exports.showInvoice = async (ctx, orderId) => {
    try {
        const id = parseInt(orderId);
        const order = await Order.findOne({ id: id });
        if (!order) return ctx.answerCbQuery("Buyurtma yo'q");

        const invoice = generateInvoice(order);
        await ctx.replyWithMarkdown(invoice);
        ctx.answerCbQuery("Chek tayyor!");
    } catch (e) {
        console.error(e);
    }
};

exports.toggleBlockUser = async (ctx, userId, isBlock) => {
    try {
        await User.updateOne({ id: userId }, { isBlocked: isBlock });
        const msg = isBlock ? "Foydalanuvchi bloklandi 🚫" : "Foydalanuvchi blokdan chiqarildi βœ…";
        ctx.answerCbQuery(msg);
        exports.manageUser(ctx, userId); // Refresh view
    } catch (e) {
        console.error(e);
    }
};

// --- API Key Management ---
const crypto = require('crypto');
const Settings = require('../models/Settings');

exports.showApiMenu = async (ctx) => {
    try {
        const apiKeySetting = await Settings.findOne({ key: 'api_secret_key' });
        const apiKey = apiKeySetting ? apiKeySetting.value : "⚠️ Mavjud emas";

        let text = `πŸ”‘ **API Integratsiya Sozlamalari**\n\n` +
            `Sizning API Kalitingiz (Secret Key):\n` +
            `<code>${apiKey}</code>\n\n` +
            `⚠️ **Eslatma:** Bu kalit orqali kelajakdagi APK mobil ilovani bot bazasiga ulashingiz mumkin. Kalitni birovga bermang!`;

        const keyboard = Markup.inlineKeyboard([
            [Markup.button.callback("πŸ”„ Yangi Kalit Yaratish", "admin_api_generate")],
            [Markup.button.callback("πŸ”™ Orqaga", "admin_dashboard")]
        ]);

        ctx.editMessageText(text, { parse_mode: 'HTML', ...keyboard })
            .catch(e => ctx.replyWithHTML(text, keyboard));
    } catch (e) {
        console.error(e);
        ctx.reply("Xatolik");
    }
};

exports.generateApiKey = async (ctx) => {
    try {
        // Generate new key
        const newKey = "sk_live_" + crypto.randomBytes(16).toString('hex');

        await Settings.findOneAndUpdate(
            { key: 'api_secret_key' },
            { value: newKey },
            { upsert: true, new: true }
        );

        ctx.answerCbQuery("Yangi kalit yaratildi βœ…");
        exports.showApiMenu(ctx);
    } catch (e) {
        console.error(e);
        ctx.answerCbQuery("Xatolik");
    }
};

// --- Mass Price Update ---
exports.startMassPriceUpdate = (ctx) => {
    ctx.reply("πŸ“ˆ **Narxlarni ommaviy o'zgartirish**\n\nBarcha mahsulotlar narxini foiz (%) hisobida oshirish yoki kamaytirish mumkin.\n\nMasalan:\n+10 => Narxlar 10% ga oshadi.\n-5 => Narxlar 5% ga kamayadi.\n\nIltimos, foizni yozing:", Markup.keyboard([['❌ Bekor qilish']]).resize());
    ctx.session.isMassUpdating = true;
};

exports.handleMassUpdate = async (ctx) => {
    if (!ctx.session.isMassUpdating) return false;

    const text = ctx.message.text;
    if (text === '❌ Bekor qilish') {
        ctx.session.isMassUpdating = false;
        exports.showDashboard(ctx); // Return to dashboard
        return true;
    }

    const percent = parseFloat(text);
    if (isNaN(percent)) {
        ctx.reply("⚠️ Iltimos, raqam yozing (masalan: 10 yoki -5).");
        return true;
    }

    try {
        const products = await Product.find();
        let changed = 0;

        for (const p of products) {
            const oldPrice = p.price;
            const newPrice = Math.round(oldPrice * (1 + percent / 100)); // Simple formula

            await Product.updateOne({ id: p.id }, { price: newPrice });
            changed++;
        }

        ctx.reply(`βœ… **Muvaffaqiyatli!**\n\n${changed} ta mahsulot narxi ${percent}% ga o'zgartirildi.`);
        ctx.session.isMassUpdating = false;
        exports.showDashboard(ctx);
    } catch (e) {
        console.error(e);
        ctx.reply("Xatolik yuz berdi.");
    }
    return true;
};

// Reject Order (Refund Logic)
exports.rejectOrder = async (ctx, orderId) => {
    try {
        const id = parseInt(orderId);
        const order = await Order.findOne({ id: id });

        if (!order) return ctx.answerCbQuery("Buyurtma topilmadi");

        // Restore Stock Logic (Automatic Refund)
        if (order.status !== 'canceled') {
            const Product = require('../models/Product');
            for (const item of order.items) {
                await Product.updateOne({ id: item.id }, { $inc: { quantity: item.count } });
            }
        }

        await Order.updateOne({ id: id }, { status: 'canceled' });

        ctx.answerCbQuery("Buyurtma bekor qilindi ❌");

        // Notify User
        if (order) {
            const User = require('../models/User');
            const locales = require('../locales');
            const user = await User.findOne({ id: order.userId });
            const lang = (user && user.language) ? user.language : 'uz';
            const i18n = locales[lang] || locales.uz;

            ctx.telegram.sendMessage(order.userId, `${i18n.status_canceled}\nBuyurtma #${id} bekor qilindi.\n(Sabab bo'lsa admin bilan bog'laning)`);
        }

        exports.showNewOrders(ctx);
    } catch (err) {
        console.error(err);
    }
};

// Edit Product List
exports.showEditProductList = async (ctx) => {
    try {
        const i18n = ctx.i18n;
        const products = await Product.find();
        const backBtn = [Markup.button.callback(i18n.admin.back, "admin_dashboard")];

        if (!products || products.length === 0) {
            return ctx.editMessageText(i18n.admin.no_edit_prod, Markup.inlineKeyboard([backBtn]))
                .catch(e => ctx.reply(i18n.admin.no_edit_prod, Markup.inlineKeyboard([backBtn])));
        }

        const buttons = products.map(p => [Markup.button.callback(`✏️ ${p.name || 'Nomsiz'}`, `edit_prod_${p.id}`)]);
        buttons.push(backBtn);

        ctx.editMessageText(i18n.admin.select_edit, Markup.inlineKeyboard(buttons))
            .catch(e => ctx.reply(i18n.admin.select_edit, Markup.inlineKeyboard(buttons)));
    } catch (err) {
        console.error(err);
    }
};

// Delete Product List
exports.showDeleteProductList = async (ctx) => {
    try {
        const i18n = ctx.i18n;
        const products = await Product.find();
        const backBtn = [Markup.button.callback(i18n.admin.back, "admin_dashboard")];

        if (!products || products.length === 0) {
            return ctx.editMessageText(i18n.admin.no_del_prod, Markup.inlineKeyboard([backBtn]))
                .catch(e => ctx.reply(i18n.admin.no_del_prod, Markup.inlineKeyboard([backBtn])));
        }

        const buttons = products.map(p => [Markup.button.callback(`πŸ—‘ ${p.name}`, `delete_prod_${p.id}`)]);
        buttons.push(backBtn);

        ctx.editMessageText(i18n.admin.select_del, Markup.inlineKeyboard(buttons))
            .catch(e => ctx.reply(i18n.admin.select_del, Markup.inlineKeyboard(buttons)));
    } catch (err) {
        console.error(err);
    }
};

exports.deleteProduct = async (ctx, prodId) => {
    try {
        const i18n = ctx.i18n;
        const id = parseInt(prodId);
        const result = await Product.findOneAndDelete({ id: id });

        if (result) {
            ctx.answerCbQuery(i18n.admin.del_success, { show_alert: true });
        } else {
            ctx.answerCbQuery(i18n.admin.del_fail, { show_alert: true });
        }

        // Refresh list
        exports.showDeleteProductList(ctx);
    } catch (err) {
        console.error("Delete Error:", err);
        ctx.answerCbQuery(ctx.i18n.admin.error);
    }
};

// Excel Export
exports.exportOrders = async (ctx) => {
    try {
        ctx.reply("πŸ“‰ Fayl tayyorlanmoqda...");

        const orders = await Order.find().sort({ createdAt: -1 });
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('Buyurtmalar');

        worksheet.columns = [
            { header: 'ID', key: 'id', width: 15 },
            { header: 'Mijoz', key: 'user', width: 20 },
            { header: 'Telefon', key: 'phone', width: 15 },
            { header: 'Manzil', key: 'address', width: 30 },
            { header: 'Yetkazib berish', key: 'delivery', width: 15 },
            { header: 'To\'lov', key: 'payment', width: 10 },
            { header: 'Jami (so\'m)', key: 'total', width: 15 },
            { header: 'Status', key: 'status', width: 10 },
            { header: 'Vaqt', key: 'date', width: 20 },
            { header: 'Mahsulotlar', key: 'items', width: 50 },
            { header: 'Izoh', key: 'comment', width: 30 }
        ];

        orders.forEach(order => {
            const itemsStr = order.items.map(i => `${i.name} (${i.count}x)`).join(', ');
            const locStr = order.location ? `${order.location.latitude}, ${order.location.longitude}` : 'Olib ketish';

            worksheet.addRow({
                id: order.id,
                user: order.user,
                phone: order.phone,
                address: locStr,
                delivery: order.deliveryMethod,
                payment: order.paymentMethod,
                total: order.total,
                status: order.status,
                date: new Date(order.createdAt).toLocaleString(),
                items: itemsStr,
                comment: order.comment || ''
            });
        });

        const buffer = await workbook.xlsx.writeBuffer();

        await ctx.replyWithDocument({ source: buffer, filename: `Buyurtmalar_${new Date().toLocaleDateString()}.xlsx` });
    } catch (err) {
        console.error("Excel Export Error:", err);
        ctx.reply("Fayl yaratishda xato bo'ldi.");
    }
};