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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
"""
MTXtyle - Database operatsiyalari (SQLite + aiosqlite)
"""
import aiosqlite
import time
from config import DATABASE_PATH, CATEGORIES


async def init_db():
    """Jadvallarni yaratish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        # Kategoriyalar jadvali
        await db.execute("""
            CREATE TABLE IF NOT EXISTS categories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                slug TEXT UNIQUE NOT NULL,
                name TEXT NOT NULL,
                emoji TEXT DEFAULT ''
            )
        """)

        # Mahsulotlar jadvali
        await db.execute("""
            CREATE TABLE IF NOT EXISTS products (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                description TEXT DEFAULT '',
                price INTEGER NOT NULL,
                category_id INTEGER,
                photo_id TEXT DEFAULT '',
                in_stock INTEGER DEFAULT 1,
                created_at REAL DEFAULT 0,
                FOREIGN KEY (category_id) REFERENCES categories(id)
            )
        """)

        # Savat jadvali
        await db.execute("""
            CREATE TABLE IF NOT EXISTS cart_items (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                product_id INTEGER NOT NULL,
                quantity INTEGER DEFAULT 1,
                FOREIGN KEY (product_id) REFERENCES products(id)
            )
        """)

        # Buyurtmalar jadvali
        await db.execute("""
            CREATE TABLE IF NOT EXISTS orders (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                full_name TEXT NOT NULL,
                phone TEXT NOT NULL,
                address TEXT NOT NULL,
                total_price INTEGER DEFAULT 0,
                status TEXT DEFAULT 'yangi',
                created_at REAL DEFAULT 0
            )
        """)

        # Buyurtma elementlari
        await db.execute("""
            CREATE TABLE IF NOT EXISTS order_items (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                order_id INTEGER NOT NULL,
                product_id INTEGER NOT NULL,
                product_name TEXT NOT NULL,
                quantity INTEGER DEFAULT 1,
                price INTEGER DEFAULT 0,
                FOREIGN KEY (order_id) REFERENCES orders(id),
                FOREIGN KEY (product_id) REFERENCES products(id)
            )
        """)

        # Users table for broadcast
        await db.execute("""
            CREATE TABLE IF NOT EXISTS users (
                user_id INTEGER PRIMARY KEY,
                username TEXT,
                full_name TEXT,
                joined_at REAL
            )
        """)

        await db.commit()

        # Default kategoriyalarni qo'shish
        for slug, info in CATEGORIES.items():
            try:
                await db.execute(
                    "INSERT OR IGNORE INTO categories (slug, name, emoji) VALUES (?, ?, ?)",
                    (slug, info["name"], info["emoji"])
                )
            except Exception:
                pass
        await db.commit()


# ==================== KATEGORIYALAR ====================

async def get_categories():
    """Barcha kategoriyalarni olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT * FROM categories ORDER BY id")
        rows = await cursor.fetchall()
        return [dict(row) for row in rows]


async def get_category_by_slug(slug):
    """Slug bo'yicha kategoriya olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT * FROM categories WHERE slug = ?", (slug,))
        row = await cursor.fetchone()
        return dict(row) if row else None


async def get_category_by_id(category_id):
    """ID bo'yicha kategoriya olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT * FROM categories WHERE id = ?", (category_id,))
        row = await cursor.fetchone()
        return dict(row) if row else None


# ==================== MAHSULOTLAR ====================

async def add_product(name, description, price, category_id, photo_id=""):
    """Yangi mahsulot qo'shish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        cursor = await db.execute(
            """INSERT INTO products (name, description, price, category_id, photo_id, created_at)
               VALUES (?, ?, ?, ?, ?, ?)""",
            (name, description, price, category_id, photo_id, time.time())
        )
        await db.commit()
        return cursor.lastrowid


async def get_products_by_category(category_id, page=0, per_page=5):
    """Kategoriya bo'yicha mahsulotlarni olish (pagination bilan)"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        offset = page * per_page

        # Umumiy sonni olish
        cursor = await db.execute(
            "SELECT COUNT(*) as cnt FROM products WHERE category_id = ? AND in_stock = 1",
            (category_id,)
        )
        row = await cursor.fetchone()
        total = row["cnt"]

        # Mahsulotlarni olish
        cursor = await db.execute(
            """SELECT * FROM products WHERE category_id = ? AND in_stock = 1
               ORDER BY created_at DESC LIMIT ? OFFSET ?""",
            (category_id, per_page, offset)
        )
        rows = await cursor.fetchall()
        products = [dict(r) for r in rows]

        return products, total


async def get_product_by_id(product_id):
    """ID bo'yicha mahsulot olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT * FROM products WHERE id = ?", (product_id,))
        row = await cursor.fetchone()
        return dict(row) if row else None


async def get_all_products():
    """Barcha mahsulotlarni olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute(
            "SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.created_at DESC"
        )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


async def update_product(product_id, **kwargs):
    """Mahsulotni yangilash"""
    allowed_fields = {"name", "description", "price", "category_id", "photo_id", "in_stock"}
    fields = {k: v for k, v in kwargs.items() if k in allowed_fields}
    if not fields:
        return False

    set_clause = ", ".join(f"{k} = ?" for k in fields)
    values = list(fields.values()) + [product_id]

    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute(f"UPDATE products SET {set_clause} WHERE id = ?", values)
        await db.commit()
        return True


async def delete_product(product_id):
    """Mahsulotni o'chirish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute("DELETE FROM products WHERE id = ?", (product_id,))
        await db.commit()


async def search_products(query):
    """Mahsulotlarni qidirish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute(
            "SELECT * FROM products WHERE in_stock = 1 AND (name LIKE ? OR description LIKE ?) ORDER BY created_at DESC",
            (f"%{query}%", f"%{query}%")
        )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


# ==================== SAVAT (CART) ====================

async def add_to_cart(user_id, product_id, quantity=1):
    """Savatga mahsulot qo'shish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        # Mavjudligini tekshirish
        cursor = await db.execute(
            "SELECT * FROM cart_items WHERE user_id = ? AND product_id = ?",
            (user_id, product_id)
        )
        existing = await cursor.fetchone()

        if existing:
            new_qty = existing[3] + quantity
            if new_qty <= 0:
                await db.execute(
                    "DELETE FROM cart_items WHERE user_id = ? AND product_id = ?",
                    (user_id, product_id)
                )
            else:
                await db.execute(
                    "UPDATE cart_items SET quantity = ? WHERE user_id = ? AND product_id = ?",
                    (new_qty, user_id, product_id)
                )
        else:
            if quantity > 0:
                await db.execute(
                    "INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)",
                    (user_id, product_id, quantity)
                )
        await db.commit()


async def get_cart(user_id):
    """Foydalanuvchi savatini olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute(
            """SELECT ci.*, p.name, p.price, p.photo_id
               FROM cart_items ci
               JOIN products p ON ci.product_id = p.id
               WHERE ci.user_id = ?""",
            (user_id,)
        )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


async def get_cart_total(user_id):
    """Savat umumiy summasini olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        cursor = await db.execute(
            """SELECT COALESCE(SUM(ci.quantity * p.price), 0) as total
               FROM cart_items ci
               JOIN products p ON ci.product_id = p.id
               WHERE ci.user_id = ?""",
            (user_id,)
        )
        row = await cursor.fetchone()
        return row[0]


async def update_cart_quantity(user_id, product_id, quantity):
    """Savatdagi mahsulot miqdorini o'zgartirish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        if quantity <= 0:
            await db.execute(
                "DELETE FROM cart_items WHERE user_id = ? AND product_id = ?",
                (user_id, product_id)
            )
        else:
            await db.execute(
                "UPDATE cart_items SET quantity = ? WHERE user_id = ? AND product_id = ?",
                (quantity, user_id, product_id)
            )
        await db.commit()


async def remove_from_cart(user_id, product_id):
    """Savatdan mahsulotni o'chirish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute(
            "DELETE FROM cart_items WHERE user_id = ? AND product_id = ?",
            (user_id, product_id)
        )
        await db.commit()


async def clear_cart(user_id):
    """Savatni tozalash"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute("DELETE FROM cart_items WHERE user_id = ?", (user_id,))
        await db.commit()


# ==================== USERS & BROADCAST ====================

async def add_user(user_id, username, full_name):
    """Yangi foydalanuvchini qo'shish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute(
            "INSERT OR IGNORE INTO users (user_id, username, full_name, joined_at) VALUES (?, ?, ?, ?)",
            (user_id, username, full_name, time.time())
        )
        await db.commit()

async def get_all_users():
    """Barcha foydalanuvchilarni olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT user_id FROM users")
        rows = await cursor.fetchall()
        return [row["user_id"] for row in rows]

async def get_all_orders_with_items():
    """Excel export uchun barcha buyurtmalar va mahsulotlar"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("""
            SELECT o.id, o.user_id, o.full_name, o.phone, o.address, o.total_price, o.status, o.created_at,
                   oi.product_name, oi.quantity, oi.price
            FROM orders o
            JOIN order_items oi ON o.id = oi.order_id
            ORDER BY o.created_at DESC
        """)
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]

# ==================== BUYURTMALAR ====================

async def create_order(user_id, full_name, phone, address):
    """Yangi buyurtma yaratish"""
    cart = await get_cart(user_id)
    if not cart:
        return None

    total = await get_cart_total(user_id)

    async with aiosqlite.connect(DATABASE_PATH) as db:
        cursor = await db.execute(
            """INSERT INTO orders (user_id, full_name, phone, address, total_price, status, created_at)
               VALUES (?, ?, ?, ?, ?, 'yangi', ?)""",
            (user_id, full_name, phone, address, total, time.time())
        )
        order_id = cursor.lastrowid

        # Savat elementlarini buyurtmaga ko'chirish
        for item in cart:
            await db.execute(
                """INSERT INTO order_items (order_id, product_id, product_name, quantity, price)
                   VALUES (?, ?, ?, ?, ?)""",
                (order_id, item["product_id"], item["name"], item["quantity"], item["price"])
            )

        await db.commit()

    # Savatni tozalash
    await clear_cart(user_id)
    return order_id


async def get_order(order_id):
    """Buyurtmani olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute("SELECT * FROM orders WHERE id = ?", (order_id,))
        row = await cursor.fetchone()
        return dict(row) if row else None


async def get_order_items(order_id):
    """Buyurtma elementlarini olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute(
            "SELECT * FROM order_items WHERE order_id = ?", (order_id,)
        )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


async def get_user_orders(user_id):
    """Foydalanuvchi buyurtmalarini olish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        cursor = await db.execute(
            "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC",
            (user_id,)
        )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


async def update_order_status(order_id, status):
    """Buyurtma statusini o'zgartirish"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute(
            "UPDATE orders SET status = ? WHERE id = ?",
            (status, order_id)
        )
        await db.commit()


async def get_all_orders(status=None):
    """Barcha buyurtmalarni olish (admin uchun)"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        db.row_factory = aiosqlite.Row
        if status:
            cursor = await db.execute(
                "SELECT * FROM orders WHERE status = ? ORDER BY created_at DESC",
                (status,)
            )
        else:
            cursor = await db.execute(
                "SELECT * FROM orders ORDER BY created_at DESC LIMIT 50"
            )
        rows = await cursor.fetchall()
        return [dict(r) for r in rows]


# ==================== STATISTIKA ====================

async def get_stats():
    """Umumiy statistika (admin uchun)"""
    async with aiosqlite.connect(DATABASE_PATH) as db:
        stats = {}

        cursor = await db.execute("SELECT COUNT(*) FROM products WHERE in_stock = 1")
        row = await cursor.fetchone()
        stats["products_count"] = row[0]

        cursor = await db.execute("SELECT COUNT(*) FROM orders")
        row = await cursor.fetchone()
        stats["orders_count"] = row[0]

        cursor = await db.execute("SELECT COUNT(*) FROM orders WHERE status = 'yangi'")
        row = await cursor.fetchone()
        stats["new_orders"] = row[0]

        cursor = await db.execute(
            "SELECT COALESCE(SUM(total_price), 0) FROM orders WHERE status != 'bekor_qilindi'"
        )
        row = await cursor.fetchone()
        stats["total_revenue"] = row[0]

        cursor = await db.execute("SELECT COUNT(DISTINCT user_id) FROM orders")
        row = await cursor.fetchone()
        stats["unique_customers"] = row[0]

        return stats