запомни код # Импорт необходимых модулей
import logging
import json
import os
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, Message
from telegram.ext import (
    ApplicationBuilder, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
)
from telegram.error import BadRequest

# Настройка логирования
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

# Пути к файлам данных
USER_DATA_FILE = 'acclogger.txt'
PRODUCTS_FILE = 'products.json'
LOCALES_FILE = 'locales.json'
IMAGES_DIR = 'images'  # Директория для хранения изображений

# Убедимся, что директория для изображений существует
os.makedirs(IMAGES_DIR, exist_ok=True)

# Словари для хранения данных
user_data = {}
products = []
locales = {}

# Функция для загрузки данных локализации
def load_locales():
    global locales
    if os.path.exists(LOCALES_FILE):
        try:
            with open(LOCALES_FILE, 'r', encoding='utf-8') as f:
                locales = json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            logging.error(f"Ошибка при чтении файла {LOCALES_FILE}: {e}")
            locales = {}
    else:
        locales = {}

# Функция для получения перевода по ключу и языку пользователя
def get_translation(user_id, key, **kwargs):
    user_info = user_data.get(str(user_id), {})
    user_lang = user_info.get('language', 'ru')
    translation = locales.get(user_lang, {}).get(key, '')
    if kwargs:
        translation = translation.format(**kwargs)
    return translation

# Функция для загрузки данных пользователей из файла
def load_user_data():
    global user_data
    if os.path.exists(USER_DATA_FILE):
        try:
            with open(USER_DATA_FILE, 'r', encoding='utf-8') as f:
                user_data = json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            logging.error(f"Ошибка при чтении файла {USER_DATA_FILE}: {e}")
            user_data = {}
    else:
        user_data = {}

# Функция для сохранения данных пользователей в файл
def save_user_data():
    try:
        with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(user_data, f, ensure_ascii=False, indent=4)
    except IOError as e:
        logging.error(f"Ошибка при сохранении файла {USER_DATA_FILE}: {e}")

# Функция для загрузки товаров из файла
def load_products():
    global products
    if os.path.exists(PRODUCTS_FILE):
        try:
            with open(PRODUCTS_FILE, 'r', encoding='utf-8') as f:
                products = json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            logging.error(f"Ошибка при чтении файла {PRODUCTS_FILE}: {e}")
            products = []
    else:
        products = []

# Функция для сохранения товаров в файл
def save_products():
    try:
        with open(PRODUCTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(products, f, ensure_ascii=False, indent=4)
    except IOError as e:
        logging.error(f"Ошибка при сохранении файла {PRODUCTS_FILE}: {e}")

# Функция для инициализации админ-аккаунтов
def initialize_admin_accounts():
    admins = [
        {
            'login': 'admin1',
            'password': 'password1',
            'username': 'Admin1'
        },
        {
            'login': 'admin2',
            'password': 'password2',
            'username': 'Admin2'
        },
        {
            'login': 'admin3',
            'password': 'password3',
            'username': 'Admin3'
        }
    ]
    initialize_admin_accounts.admins = admins

# Функция для проверки учетных данных администратора
def check_admin_credentials(login, password):
    for admin in initialize_admin_accounts.admins:
        if admin['login'] == login and admin['password'] == password:
            return admin
    return None

# Обработчик команды /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    user_id = str(user.id)

    if user_id not in user_data:
        # Если пользователь впервые, предлагаем выбрать язык
        keyboard = [
            [
                InlineKeyboardButton("Русский", callback_data='set_language_ru'),
                InlineKeyboardButton("Беларуская", callback_data='set_language_by'),
            ],
            [
                InlineKeyboardButton("Қазақша", callback_data='set_language_kz'),
                InlineKeyboardButton("Тоҷикӣ", callback_data='set_language_tj'),
            ],
            [
                InlineKeyboardButton("Ўзбекча", callback_data='set_language_uz'),
                InlineKeyboardButton("English", callback_data='set_language_en'),
            ]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        await update.effective_message.reply_text("🌐 Пожалуйста, выберите язык:", reply_markup=reply_markup)
    else:
        # Если язык уже выбран, приветствуем пользователя
        await send_welcome_message(update, context)

# Обработчик выбора языка
async def set_language(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    user = query.from_user
    user_id = str(user.id)
    data = query.data
    language_code = data.split('_')[-1]

    username = user.username or user.full_name

    # Обновляем или создаем данные пользователя
    user_data[user_id] = user_data.get(user_id, {})
    user_data[user_id].update({
        'username': username,
        'language': language_code,
        'balance': user_data[user_id].get('balance', 0),
        'cart': user_data[user_id].get('cart', []),
        'reviews': user_data[user_id].get('reviews', {}),
        'purchase_history': user_data[user_id].get('purchase_history', []),
        'admin': user_data[user_id].get('admin', False),
        'login': user_data[user_id].get('login', ''),
        'password': user_data[user_id].get('password', ''),
        'blocked': user_data[user_id].get('blocked', False),
        'is_admin': user_data[user_id].get('is_admin', False),
        'notes': user_data[user_id].get('notes', '')
    })
    save_user_data()

    await send_welcome_message(update, context)

# Функция для отправки приветственного сообщения
async def send_welcome_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    user_id = str(user.id)

    username = user_data[user_id]['username']
    welcome_text = get_translation(user_id, 'welcome', username=username)

    # Кнопки "Товары" и "Личный кабинет"
    keyboard = [
        [
            InlineKeyboardButton(get_translation(user_id, 'products'), callback_data='show_products'),
            InlineKeyboardButton(get_translation(user_id, 'personal_cabinet'), callback_data='personal_cabinet')
        ]
    ]

    # Если пользователь является администратором, добавляем кнопку админ-панели
    if user_data[user_id].get('is_admin'):
        keyboard.append([InlineKeyboardButton(get_translation(user_id, 'admin_panel'), callback_data='admin_panel')])

    reply_markup = InlineKeyboardMarkup(keyboard)

    await update.effective_message.reply_text(welcome_text, reply_markup=reply_markup)

# Обработчик для показа личного кабинета
async def personal_cabinet(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user = query.from_user
    user_id = str(user.id)
    await query.answer()

    # Получаем данные пользователя
    user_info = user_data.get(user_id, None)

    if not user_info:
        await query.edit_message_text("Пользователь не найден.")
        return

    # Формируем сообщение с информацией о пользователе
    cabinet_text = (
        f"{get_translation(user_id, 'personal_cabinet')}\n\n"
        f"{get_translation(user_id, 'balance')}: {user_info.get('balance', 0)}₽\n"
        f"{get_translation(user_id, 'cart')}: {', '.join(user_info.get('cart', [])) or get_translation(user_id, 'empty')}\n"
        f"{get_translation(user_id, 'purchase_history')}: {', '.join(user_info.get('purchase_history', [])) or get_translation(user_id, 'no_purchases')}\n"
        f"{get_translation(user_id, 'reviews')}: {', '.join([f'{k}: {v}' for k, v in user_info.get('reviews', {}).items()]) or get_translation(user_id, 'no_reviews')}"
    )

    # Кнопки для личного кабинета
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'cart'), callback_data='view_cart')],
        [InlineKeyboardButton(get_translation(user_id, 'top_up_balance'), callback_data='top_up_balance')],
        [InlineKeyboardButton(get_translation(user_id, 'change_language'), callback_data='change_language')],
        [InlineKeyboardButton(get_translation(user_id, 'main_menu'), callback_data='main_menu')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(cabinet_text, reply_markup=reply_markup)

# Обработчик для смены языка из личного кабинета
async def change_language_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    # Предлагаем выбрать язык
    keyboard = [
        [
            InlineKeyboardButton("Русский", callback_data='set_language_ru'),
            InlineKeyboardButton("Беларуская", callback_data='set_language_by'),
        ],
        [
            InlineKeyboardButton("Қазақша", callback_data='set_language_kz'),
            InlineKeyboardButton("Тоҷикӣ", callback_data='set_language_tj'),
        ],
        [
            InlineKeyboardButton("Ўзбекча", callback_data='set_language_uz'),
            InlineKeyboardButton("English", callback_data='set_language_en'),
        ],
        [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='personal_cabinet')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    choose_language_text = get_translation(user_id, 'choose_language')
    await query.edit_message_text(choose_language_text, reply_markup=reply_markup)

# Обработчик для пополнения баланса (пока выводит сообщение об ошибке)
async def top_up_balance(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user = query.from_user
    user_id = str(user.id)
    await query.answer(get_translation(user_id, 'function_not_implemented'), show_alert=True)
    # Добавляем кнопку "Назад"
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='personal_cabinet')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await query.edit_message_reply_markup(reply_markup=reply_markup)

# Обработчик для показа корзины пользователя
async def view_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    user = query.from_user
    user_id = str(user.id)
    user_info = user_data.get(user_id, None)

    if not user_info:
        await query.edit_message_text("Пользователь не найден.")
        return

    cart_items = user_info.get('cart', [])
    if not cart_items:
        cart_text = get_translation(user_id, 'cart_empty')
        keyboard = [
            [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='personal_cabinet')]
        ]
    else:
        cart_text = f"{get_translation(user_id, 'your_cart')}\n" + "\n".join([f"- {item}" for item in cart_items])
        # Кнопки для корзины
        keyboard = [
            [InlineKeyboardButton(get_translation(user_id, 'checkout'), callback_data='checkout')],
            [InlineKeyboardButton(get_translation(user_id, 'clear_cart'), callback_data='clear_cart')],
            [InlineKeyboardButton(get_translation(user_id, 'remove_item'), callback_data='remove_from_cart')],
            [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='personal_cabinet')]
        ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(cart_text, reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для очистки корзины
async def clear_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer(get_translation(user_id, 'cart_cleared'), show_alert=True)

    user_info = user_data.get(user_id)
    if user_info:
        user_info['cart'] = []
        save_user_data()

    # Возвращаемся к просмотру корзины
    await view_cart(update, context)

# Обработчик для удаления отдельного товара из корзины
async def remove_from_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    user_info = user_data.get(user_id)
    if not user_info or not user_info.get('cart'):
        await query.edit_message_text(get_translation(user_id, 'cart_empty'))
        return

    # Создаем список кнопок с товарами для удаления
    keyboard = []
    for item in user_info['cart']:
        keyboard.append([InlineKeyboardButton(f"❌ {item}", callback_data=f'delete_item_{item}')])

    keyboard.append([InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='view_cart')])
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(get_translation(user_id, 'select_item_to_remove'), reply_markup=reply_markup)

# Обработчик для удаления выбранного товара из корзины
async def delete_item_from_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)

    data = query.data
    parts = data.split('_')
    product_name = '_'.join(parts[2:])  # Извлекаем название товара

    user_info = user_data.get(user_id)
    if user_info and product_name in user_info.get('cart', []):
        user_info['cart'].remove(product_name)
        save_user_data()
        await query.answer(get_translation(user_id, 'item_removed_from_cart'), show_alert=True)
    else:
        await query.answer(get_translation(user_id, 'item_not_in_cart'), show_alert=True)

    # Возвращаемся к просмотру корзины
    await view_cart(update, context)

# Обработчик для оформления покупки (выводит сообщение об ошибке)
async def checkout(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user = query.from_user
    user_id = str(user.id)
    await query.answer(get_translation(user_id, 'function_not_implemented'), show_alert=True)
    # Добавляем кнопку "Назад"
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='view_cart')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await query.edit_message_reply_markup(reply_markup=reply_markup)

# Обработчик для показа списка товаров
async def show_products(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    user = query.from_user
    user_id = str(user.id)

    data = query.data
    page = 1

    data_parts = data.split('_')
    if len(data_parts) > 2:
        # Если в callback_data есть номер страницы
        page = int(data_parts[-1])
    else:
        page = 1  # Если номера страницы нет, устанавливаем 1

    await send_product_list(query, page)

# Функция для отправки списка товаров с учетом пагинации
async def send_product_list(query, page):
    user_id = str(query.from_user.id)

    products_per_page = 4  # Количество товаров на странице

    total_products = len(products)
    if total_products == 0:
        await query.edit_message_text(get_translation(user_id, 'all_products_sold'))
        return

    start_index = (page - 1) * products_per_page
    end_index = start_index + products_per_page

    page_products = products[start_index:end_index]

    keyboard = []

    # Добавляем кнопки товаров по две в ряд
    row = []
    for idx, product in enumerate(page_products):
        button = InlineKeyboardButton(
            product['name'],
            callback_data=f'product_{product["name"]}_{page}'
        )
        row.append(button)
        if (idx + 1) % 2 == 0:
            keyboard.append(row)
            row = []
    if row:
        keyboard.append(row)

    # Кнопки навигации
    nav_buttons = []

    if page > 1:
        nav_buttons.append(InlineKeyboardButton(
            get_translation(user_id, 'back'), callback_data=f'show_products_{page - 1}'
        ))

    if end_index < len(products):
        nav_buttons.append(InlineKeyboardButton(
            get_translation(user_id, 'forward'), callback_data=f'show_products_{page + 1}'
        ))
    else:
        if len(products) > products_per_page:
            nav_buttons.append(InlineKeyboardButton(
                get_translation(user_id, 'start_over'), callback_data='show_products_1'
            ))

    nav_buttons.append(InlineKeyboardButton(
        get_translation(user_id, 'main_menu'), callback_data='main_menu'
    ))

    keyboard.append(nav_buttons)

    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(
        text=get_translation(user_id, 'our_products'),
        reply_markup=reply_markup
    )

# Обработчик для показа деталей товара
async def show_product_detail(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)

    data = query.data
    parts = data.split('_')
    product_name = '_'.join(parts[1:-1])  # Собираем имя товара
    page = int(parts[-1])

    # Находим товар по имени
    product = next((p for p in products if p['name'] == product_name), None)

    if not product:
        await query.edit_message_text(get_translation(user_id, 'product_not_found'))
        return

    # Кнопки "Добавить в корзину" и "Назад"
    keyboard = [
        [
            InlineKeyboardButton(get_translation(user_id, 'add_to_cart'), callback_data=f'add_to_cart_{product_name}'),
            InlineKeyboardButton(get_translation(user_id, 'back'), callback_data=f'back_to_products_{page}')
        ]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    # Отправляем информацию о товаре
    message_text = f"📦 *{product['name']}*\n{product['description']}\n💰 Цена: {product['price']}₽"

    # Отправляем фото, если есть
    if product.get('image') and os.path.exists(product['image']):
        await query.delete_message()
        with open(product['image'], 'rb') as photo_file:
            await query.message.reply_photo(
                photo=photo_file,
                caption=message_text,
                reply_markup=reply_markup,
                parse_mode='Markdown'
            )
    else:
        await query.edit_message_text(text=message_text, reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для добавления товара в корзину
async def add_to_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    data = query.data
    parts = data.split('_')
    product_name = '_'.join(parts[3:])  # Извлекаем имя товара

    user = query.from_user
    user_id = str(user.id)

    # Проверяем, существует ли товар
    product_exists = any(p['name'] == product_name for p in products)
    if not product_exists:
        await query.answer(get_translation(user_id, 'product_not_found'), show_alert=True)
        return

    # Добавляем товар в корзину пользователя
    user_info = user_data.get(user_id)
    if user_info:
        if product_name not in user_info.get('cart', []):
            user_info.setdefault('cart', []).append(product_name)
            save_user_data()
            await query.answer(get_translation(user_id, 'product_added_to_cart'))
        else:
            await query.answer(get_translation(user_id, 'product_already_in_cart'), show_alert=True)
    else:
        await query.answer("Ошибка: пользователь не найден.", show_alert=True)

    # Возвращаем пользователя к сообщению с товаром
    await show_product_detail(update, context)

# Обработчик кнопки "Назад" в деталях товара
async def back_to_products(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query

    data = query.data
    data_parts = data.split('_')
    if len(data_parts) > 3:
        page = int(data_parts[-1])
    else:
        page = 1

    await send_product_list(query, page)

# Обработчик кнопки "В главное меню"
async def main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    # Возвращаемся к приветственному сообщению
    await send_welcome_message(update, context)

# Обработчик текстовых сообщений (например, для отзывов и входа в админ-панель)
async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    user_id = str(user.id)
    message = update.message.text.strip()

    if 'cancel_action' in context.user_data:
        # Если действие было отменено
        context.user_data.pop('cancel_action')
        await update.message.reply_text(get_translation(user_id, 'action_cancelled'))
        return

    if 'awaiting_admin_login' in context.user_data:
        # Пользователь вводит логин
        context.user_data['admin_login'] = message
        context.user_data.pop('awaiting_admin_login')
        context.user_data['awaiting_admin_password'] = True
        keyboard = [
            [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        await update.message.reply_text(get_translation(user_id, 'enter_password'), reply_markup=reply_markup)
    elif 'awaiting_admin_password' in context.user_data:
        # Пользователь вводит пароль
        login = context.user_data.pop('admin_login')
        password = message
        context.user_data.pop('awaiting_admin_password')

        # Проверяем логин и пароль
        admin_info = check_admin_credentials(login, password)
        if admin_info:
            # Привязываем админ-аккаунт к пользователю
            user_data[user_id]['is_admin'] = True
            user_data[user_id]['admin_login'] = login
            user_data[user_id]['admin'] = True
            user_data[user_id]['login'] = login
            user_data[user_id]['password'] = password
            save_user_data()
            await update.message.reply_text(get_translation(user_id, 'access_granted'))
            # Отображаем админ-панель
            await admin_panel(update, context)
        else:
            await update.message.reply_text(get_translation(user_id, 'access_denied'))
    elif 'awaiting_message_for_user' in context.user_data:
        target_user_id = context.user_data['awaiting_message_for_user']
        try:
            await context.bot.send_message(
                chat_id=target_user_id,
                text=f"✉️ Сообщение от администратора:\n\n{message}"
            )
            context.user_data.pop('awaiting_message_for_user')
            await update.message.reply_text(get_translation(user_id, 'message_sent'))
            # Возвращаемся к просмотру данных пользователя
            await admin_view_user(update, context, user_id=target_user_id)
        except Exception as e:
            await update.message.reply_text(f"Не удалось отправить сообщение пользователю: {e}")
    elif 'awaiting_balance_change' in context.user_data:
        target_user_id = context.user_data['awaiting_balance_change']
        try:
            new_balance = float(message)
            user_data[target_user_id]['balance'] = new_balance
            save_user_data()
            context.user_data.pop('awaiting_balance_change')
            await update.message.reply_text(get_translation(user_id, 'balance_updated'))
            # Возвращаемся к просмотру данных пользователя
            await admin_view_user(update, context, user_id=target_user_id)
        except ValueError:
            await update.message.reply_text("Пожалуйста, введите корректное число.")
    elif 'awaiting_note_for_user' in context.user_data:
        target_user_id = context.user_data['awaiting_note_for_user']
        user_data[target_user_id]['notes'] = message
        save_user_data()
        context.user_data.pop('awaiting_note_for_user')
        await update.message.reply_text(get_translation(user_id, 'note_saved'))
        # Возвращаемся к просмотру данных пользователя
        await admin_view_user(update, context, user_id=target_user_id)
    elif 'product_creation_step' in context.user_data:
        step = context.user_data['product_creation_step']
        if step == 1:
            # Сохраняем название товара
            context.user_data['new_product_name'] = message
            context.user_data['product_creation_step'] = 2
            keyboard = [
                [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
            ]
            reply_markup = InlineKeyboardMarkup(keyboard)
            await update.message.reply_text(get_translation(user_id, 'enter_product_description'), parse_mode='Markdown', reply_markup=reply_markup)
        elif step == 2:
            # Сохраняем описание товара
            context.user_data['new_product_description'] = message
            context.user_data['product_creation_step'] = 3
            keyboard = [
                [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
            ]
            reply_markup = InlineKeyboardMarkup(keyboard)
            await update.message.reply_text(get_translation(user_id, 'enter_price'), parse_mode='Markdown', reply_markup=reply_markup)
        elif step == 3:
            # Сохраняем цену товара
            try:
                price = float(message)
                context.user_data['new_product_price'] = price
                context.user_data['product_creation_step'] = 4
                keyboard = [
                    [InlineKeyboardButton(get_translation(user_id, 'skip_image'), callback_data='skip_image')],
                    [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
                ]
                reply_markup = InlineKeyboardMarkup(keyboard)
                await update.message.reply_text(get_translation(user_id, 'attach_product_image'), parse_mode='Markdown', reply_markup=reply_markup)
            except ValueError:
                await update.message.reply_text("Пожалуйста, введите корректную цену.")
        else:
            await update.message.reply_text(get_translation(user_id, 'unknown_command'))
    elif 'awaiting_product_update' in context.user_data:
        update_field = context.user_data['awaiting_product_update']
        product = context.user_data['editing_product']
        if update_field == 'name':
            # Обновляем название товара
            old_name = product['name']
            new_name = message
            # Проверяем, нет ли товара с таким именем
            if any(p['name'] == new_name for p in products if p != product):
                await update.message.reply_text("Товар с таким названием уже существует.")
                return
            # Переименовываем файл изображения, если он есть
            if product.get('image') and os.path.exists(product['image']):
                old_image_path = product['image']
                new_image_path = os.path.join(IMAGES_DIR, f"{new_name}.jpg")
                os.rename(old_image_path, new_image_path)
                product['image'] = new_image_path
            product['name'] = new_name
            save_products()
            context.user_data.pop('awaiting_product_update')
            await update.message.reply_text("Название товара обновлено.")
        elif update_field == 'description':
            # Обновляем описание товара
            product['description'] = message
            save_products()
            context.user_data.pop('awaiting_product_update')
            await update.message.reply_text("Описание товара обновлено.")
        elif update_field == 'price':
            try:
                price = float(message)
                product['price'] = price
                save_products()
                context.user_data.pop('awaiting_product_update')
                await update.message.reply_text("Цена товара обновлена.")
            except ValueError:
                await update.message.reply_text("Пожалуйста, введите корректную цену.")
        # Возвращаемся к подтверждению изменения товара
        await send_product_edit_confirmation(update, context)
    else:
        if message == '!admpanlog':
            # Начинаем процесс входа в админ-панель
            context.user_data['awaiting_admin_login'] = True
            keyboard = [
                [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
            ]
            reply_markup = InlineKeyboardMarkup(keyboard)
            await update.message.reply_text(get_translation(user_id, 'enter_login'), reply_markup=reply_markup)
        else:
            await update.message.reply_text(get_translation(user_id, 'unknown_command'))

# Обработчик для отмены действий
async def cancel_action(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer(get_translation(str(query.from_user.id), 'action_cancelled'), show_alert=True)
    user_id = str(query.from_user.id)

    # Очищаем все ожидания
    context.user_data.pop('awaiting_admin_login', None)
    context.user_data.pop('awaiting_admin_password', None)
    context.user_data.pop('awaiting_message_for_user', None)
    context.user_data.pop('awaiting_balance_change', None)
    context.user_data.pop('awaiting_note_for_user', None)
    context.user_data.pop('product_creation_step', None)
    context.user_data.pop('new_product', None)
    context.user_data.pop('new_product_name', None)
    context.user_data.pop('new_product_description', None)
    context.user_data.pop('new_product_price', None)
    context.user_data.pop('new_product_photo', None)
    context.user_data.pop('awaiting_product_update', None)
    context.user_data.pop('editing_product', None)
    context.user_data.pop('cancel_action', None)

    await query.message.reply_text(get_translation(user_id, 'action_cancelled'))

# Функция для отображения админ-панели
async def admin_panel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = str(update.effective_user.id)
    if not user_data[user_id].get('is_admin'):
        await update.message.reply_text(get_translation(user_id, 'access_denied'))
        return

    # Кнопки админ-панели
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'manage_users'), callback_data='admin_view_users')],
        [InlineKeyboardButton(get_translation(user_id, 'manage_products'), callback_data='admin_manage_products')],
        [InlineKeyboardButton(get_translation(user_id, 'main_menu'), callback_data='main_menu')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await update.message.reply_text(get_translation(user_id, 'admin_panel_welcome'), reply_markup=reply_markup)

# Обработчик для админ-панели (используя CallbackQuery)
async def admin_panel_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    if not user_data[user_id].get('is_admin'):
        await query.edit_message_text(get_translation(user_id, 'access_denied'))
        return

    # Кнопки админ-панели
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'manage_users'), callback_data='admin_view_users')],
        [InlineKeyboardButton(get_translation(user_id, 'manage_products'), callback_data='admin_manage_products')],
        [InlineKeyboardButton(get_translation(user_id, 'main_menu'), callback_data='main_menu')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(get_translation(user_id, 'admin_panel_welcome'), reply_markup=reply_markup)

# Обработчик для просмотра списка пользователей
async def admin_view_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    if not user_data[user_id].get('is_admin'):
        await query.edit_message_text(get_translation(user_id, 'access_denied'))
        return

    # Получаем список пользователей (исключаем админов)
    users = [(uid, info) for uid, info in user_data.items() if not info.get('is_admin')]

    if not users:
        await query.edit_message_text(get_translation(user_id, 'no_users'))
        return

    # Формируем кнопки с пользователями
    keyboard = []
    for uid, info in users[:6]:  # Берем первые 6 пользователей
        username_display = f"@{info.get('username', 'NoUsername')}/id:{uid}"
        keyboard.append([InlineKeyboardButton(username_display, callback_data=f'admin_view_user_{uid}')])

    # Добавляем кнопку "Назад"
    keyboard.append([InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='admin_panel')])

    reply_markup = InlineKeyboardMarkup(keyboard)
    await query.edit_message_text(get_translation(user_id, 'user_list'), reply_markup=reply_markup)

# Обработчик для просмотра данных конкретного пользователя
async def admin_view_user(update: Update, context: ContextTypes.DEFAULT_TYPE, user_id=None):
    query = update.callback_query if update.callback_query else None
    message = update.message if update.message else None
    admin_id = str(update.effective_user.id)

    if not user_id:
        data = query.data
        parts = data.split('_')
        user_id = parts[-1]

    user_info = user_data.get(user_id)
    if not user_info:
        if query:
            await query.edit_message_text(get_translation(admin_id, 'user_not_found'))
        else:
            await message.reply_text(get_translation(admin_id, 'user_not_found'))
        return

    is_blocked = user_info.get('blocked', False)
    block_unblock_text = get_translation(admin_id, 'unblock_user') if is_blocked else get_translation(admin_id, 'block_user')

    user_cart = user_info.get('cart', [])
    cart_text = ', '.join(user_cart) if user_cart else get_translation(admin_id, 'cart_empty')

    user_notes = user_info.get('notes', get_translation(admin_id, 'no_notes'))

    user_details = (
        f"👤 {get_translation(admin_id, 'username')}: {user_info.get('username', 'NoUsername')}\n"
        f"🆔 ID: {user_id}\n"
        f"💰 {get_translation(admin_id, 'balance')}: {user_info.get('balance', 0)}₽\n"
        f"🚫 {get_translation(admin_id, 'blocked')}: {get_translation(admin_id, 'blocked') if is_blocked else get_translation(admin_id, 'not_blocked')}\n"
        f"📝 {get_translation(admin_id, 'notes')}: {user_notes}\n"
        f"🛒 {get_translation(admin_id, 'cart')}: {cart_text}\n"
    )

    # Кнопки управления пользователем
    keyboard = [
        [InlineKeyboardButton(f"{block_unblock_text}", callback_data=f'admin_toggle_block_{user_id}')],
        [InlineKeyboardButton("💰 Изменить баланс", callback_data=f'admin_change_balance_{user_id}')],
        [InlineKeyboardButton("📝 Добавить заметку", callback_data=f'admin_add_note_{user_id}')],
        [InlineKeyboardButton("🛒 Просмотр/редактирование корзины", callback_data=f'admin_view_cart_{user_id}')],
        [InlineKeyboardButton("✉️ Отправить сообщение", callback_data=f'admin_send_message_{user_id}')],
        [InlineKeyboardButton("🔙 Назад", callback_data='admin_view_users')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    if query:
        await query.edit_message_text(user_details, reply_markup=reply_markup)
    else:
        await message.reply_text(user_details, reply_markup=reply_markup)

# Обработчик для блокировки/разблокировки пользователя
async def admin_toggle_block_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    admin_id = str(query.from_user.id)
    await query.answer()

    data = query.data
    parts = data.split('_')
    user_id = parts[-1]

    user_info = user_data.get(user_id)
    if not user_info:
        await query.edit_message_text(get_translation(admin_id, 'user_not_found'))
        return

    # Переключаем статус блокировки
    is_blocked = user_info.get('blocked', False)
    user_info['blocked'] = not is_blocked
    save_user_data()

    await admin_view_user(update, context, user_id=user_id)

# Обработчик для изменения баланса пользователя
async def admin_change_balance(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    admin_id = str(query.from_user.id)
    await query.answer()

    data = query.data
    parts = data.split('_')
    user_id = parts[-1]

    user_info = user_data.get(user_id)
    if not user_info:
        await query.edit_message_text(get_translation(admin_id, 'user_not_found'))
        return

    context.user_data['awaiting_balance_change'] = user_id

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(admin_id, 'enter_new_balance'), reply_markup=reply_markup)

# Обработчик для отправки сообщения пользователю
async def admin_send_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    admin_id = str(query.from_user.id)
    await query.answer()

    data = query.data
    parts = data.split('_')
    user_id = parts[-1]

    user_info = user_data.get(user_id)
    if not user_info:
        await query.edit_message_text(get_translation(admin_id, 'user_not_found'))
        return

    context.user_data['awaiting_message_for_user'] = user_id

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(admin_id, 'message_prompt'), reply_markup=reply_markup)

# Обработчик для добавления заметки к пользователю
async def admin_add_note_to_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    admin_id = str(query.from_user.id)
    await query.answer()

    data = query.data
    parts = data.split('_')
    user_id = parts[-1]

    user_info = user_data.get(user_id)
    if not user_info:
        await query.edit_message_text(get_translation(admin_id, 'user_not_found'))
        return

    context.user_data['awaiting_note_for_user'] = user_id

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(admin_id, 'enter_note'), reply_markup=reply_markup)

# Обработчик для просмотра и редактирования корзины пользователя
async def admin_view_cart_of_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    data = query.data
    parts = data.split('_')
    target_user_id = parts[-1]

    user_info = user_data.get(target_user_id)
    if not user_info:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'user_not_found'))
        return

    cart_items = user_info.get('cart', [])
    if not cart_items:
        cart_text = get_translation(str(query.from_user.id), 'cart_empty')
    else:
        cart_text = f"🛒 Корзина пользователя:\n" + "\n".join([f"- {item}" for item in cart_items])

    # Кнопки для корзины
    keyboard = []
    if cart_items:
        keyboard.append([InlineKeyboardButton("🗑️ Очистить корзину", callback_data=f'admin_clear_cart_{target_user_id}')])
        for item in cart_items:
            keyboard.append([InlineKeyboardButton(f"❌ {item}", callback_data=f'admin_delete_item_{target_user_id}_{item}')])
    keyboard.append([InlineKeyboardButton("🔙 Назад", callback_data=f'admin_view_user_{target_user_id}')])

    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(cart_text, reply_markup=reply_markup)

# Обработчик для очистки корзины пользователя
async def admin_clear_cart_of_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    data = query.data
    parts = data.split('_')
    target_user_id = parts[-1]

    user_info = user_data.get(target_user_id)
    if not user_info:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'user_not_found'))
        return

    user_info['cart'] = []
    save_user_data()

    await admin_view_cart_of_user(update, context)

# Обработчик для удаления отдельного товара из корзины пользователя
async def admin_delete_item_from_user_cart(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    data = query.data
    parts = data.split('_')
    target_user_id = parts[3]
    item_name = '_'.join(parts[4:])

    user_info = user_data.get(target_user_id)
    if not user_info:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'user_not_found'))
        return

    if item_name in user_info.get('cart', []):
        user_info['cart'].remove(item_name)
        save_user_data()

    await admin_view_cart_of_user(update, context)

# Обработчик для управления товарами
async def admin_manage_products(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    # Кнопки "Изменить существующие" и "Создать новый"
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'edit_existing_product'), callback_data='admin_edit_product')],
        [InlineKeyboardButton(get_translation(user_id, 'add_new_product'), callback_data='admin_create_product')],
        [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='admin_panel')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.edit_message_text(get_translation(user_id, 'manage_products_menu'), reply_markup=reply_markup)

# Обработчик для создания нового товара
async def admin_create_product(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    user_id = str(query.from_user.id)
    await query.answer()

    context.user_data['product_creation_step'] = 1
    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await query.message.reply_text(get_translation(user_id, 'enter_product_name'), parse_mode='Markdown', reply_markup=reply_markup)

# Обработчик для редактирования существующих товаров
async def admin_edit_product(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = str(query.from_user.id)

    # Просим администратора выбрать товар
    product_buttons = []
    for product in products:
        product_buttons.append([InlineKeyboardButton(product['name'], callback_data=f'admin_select_product_{product["name"]}')])

    # Добавляем кнопку "Назад"
    product_buttons.append([InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='admin_manage_products')])

    reply_markup = InlineKeyboardMarkup(product_buttons)

    await query.edit_message_text("Выберите товар для редактирования:", reply_markup=reply_markup)

# Обработчик для выбора товара для редактирования
async def admin_edit_selected_product(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.callback_query:
        query = update.callback_query
        await query.answer()
        user_id = str(query.from_user.id)

        data = query.data
        parts = data.split('_')
        product_name = '_'.join(parts[3:])  # Извлекаем имя товара
    else:
        user_id = str(update.effective_user.id)
        product_name = context.user_data['editing_product']['name']

    # Находим товар
    product = next((p for p in products if p['name'] == product_name), None)
    if not product:
        if update.callback_query:
            await query.edit_message_text(get_translation(user_id, 'product_not_found'))
        else:
            await update.message.reply_text(get_translation(user_id, 'product_not_found'))
        return

    # Сохраняем выбранный товар в контексте
    context.user_data['editing_product'] = product

    # Предлагаем опции для редактирования
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'admin_change_product_photo'), callback_data='admin_change_product_photo')],
        [InlineKeyboardButton(get_translation(user_id, 'admin_change_product_price'), callback_data='admin_change_product_price')],
        [InlineKeyboardButton(get_translation(user_id, 'admin_change_product_name'), callback_data='admin_change_product_name')],
        [InlineKeyboardButton(get_translation(user_id, 'admin_change_product_description'), callback_data='admin_change_product_description')],
        [InlineKeyboardButton("🗑️ Удалить товар", callback_data='admin_delete_product')],
        [InlineKeyboardButton(get_translation(user_id, 'back'), callback_data='admin_edit_product')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    if update.callback_query:
        await query.edit_message_text(get_translation(user_id, 'editing_product').format(product_name=product_name), reply_markup=reply_markup, parse_mode='Markdown')
    else:
        await update.message.reply_text(get_translation(user_id, 'editing_product').format(product_name=product_name), reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для удаления товара
async def admin_delete_product(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = str(query.from_user.id)

    product = context.user_data.get('editing_product')
    if not product:
        await query.edit_message_text(get_translation(user_id, 'product_not_selected'))
        return

    # Удаляем товар из списка
    products.remove(product)
    save_products()

    # Удаляем изображение товара, если есть
    if product.get('image') and os.path.exists(product['image']):
        os.remove(product['image'])

    context.user_data.pop('editing_product')
    await query.edit_message_text("✅ Товар успешно удален.")

# Обработчик для изменения цены товара
async def admin_change_product_price(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    product = context.user_data.get('editing_product')
    if not product:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'product_not_selected'))
        return

    context.user_data['awaiting_product_update'] = 'price'

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_price'), reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для изменения названия товара
async def admin_change_product_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    product = context.user_data.get('editing_product')
    if not product:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'product_not_selected'))
        return

    context.user_data['awaiting_product_update'] = 'name'

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_product_name'), reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для изменения описания товара
async def admin_change_product_description(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    product = context.user_data.get('editing_product')
    if not product:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'product_not_selected'))
        return

    context.user_data['awaiting_product_update'] = 'description'

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_product_description'), reply_markup=reply_markup, parse_mode='Markdown')

# Обработчик для изменения фото товара
async def admin_change_product_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    product = context.user_data.get('editing_product')
    if not product:
        await query.edit_message_text(get_translation(str(query.from_user.id), 'product_not_selected'))
        return

    context.user_data['awaiting_product_update'] = 'photo'

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text("Пожалуйста, отправьте новое фото товара:", reply_markup=reply_markup)

# Обработчик получения фото товара при редактировании или создании
async def handle_photo_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    user_id = str(user.id)

    if 'product_creation_step' in context.user_data and context.user_data['product_creation_step'] == 4:
        # Получаем фото для нового товара
        photo = update.message.photo[-1]
        photo_file = await photo.get_file()

        # Сохраняем фото
        file_path = os.path.join(IMAGES_DIR, f"{context.user_data['new_product_name']}.jpg")
        await photo_file.download_to_drive(custom_path=file_path)
        context.user_data['new_product_photo'] = file_path

        # Переходим к подтверждению создания товара
        await send_product_confirmation(update, context)
    elif context.user_data.get('awaiting_product_update') == 'photo':
        # Обновляем фото товара
        product = context.user_data.get('editing_product')
        photo = update.message.photo[-1]
        photo_file = await photo.get_file()

        # Сохраняем фото
        file_path = os.path.join(IMAGES_DIR, f"{product['name']}.jpg")
        await photo_file.download_to_drive(custom_path=file_path)
        product['image'] = file_path
        save_products()

        context.user_data.pop('awaiting_product_update')
        await update.message.reply_text(get_translation(user_id, 'photo_saved'))

        # Возвращаемся к подтверждению изменения товара
        await send_product_edit_confirmation(update, context)
    else:
        await update.message.reply_text(get_translation(user_id, 'unknown_command'))

# Обработчик для пропуска добавления изображения при создании товара
async def skip_image(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    user_id = str(query.from_user.id)

    # Переходим к подтверждению создания товара
    await send_product_confirmation(query, context)

# Функция для подтверждения создания товара
async def send_product_confirmation(update_or_query, context):
    if isinstance(update_or_query, Update):
        user_id = str(update_or_query.effective_user.id)
    elif isinstance(update_or_query, CallbackQuery):
        user_id = str(update_or_query.from_user.id)
        message = update_or_query.message
    else:
        return

    # Формируем информацию о новом товаре
    name = context.user_data['new_product_name']
    description = context.user_data['new_product_description']
    price = context.user_data['new_product_price']
    photo = context.user_data.get('new_product_photo')

    message_text = f"*Подтверждение создания товара*\n\nНазвание: *{name}*\nОписание: {description}\nЦена: *{price}* ₽"
    keyboard = [
        [InlineKeyboardButton(get_translation(user_id, 'confirm_product_creation'), callback_data='confirm_product_creation')],
        [InlineKeyboardButton(get_translation(user_id, 'edit_new_product_name'), callback_data='edit_new_product_name')],
        [InlineKeyboardButton(get_translation(user_id, 'edit_new_product_description'), callback_data='edit_new_product_description')],
        [InlineKeyboardButton(get_translation(user_id, 'edit_new_product_price'), callback_data='edit_new_product_price')],
        [InlineKeyboardButton(get_translation(user_id, 'edit_new_product_photo'), callback_data='edit_new_product_photo')],
        [InlineKeyboardButton(get_translation(user_id, 'restart_product_creation'), callback_data='restart_product_creation')],
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    # Отправляем сообщение с товаром
    if photo and os.path.exists(photo):
        try:
            if isinstance(update_or_query, Update):
                message = await update_or_query.message.reply_photo(
                    photo=open(photo, 'rb'),
                    caption=message_text,
                    reply_markup=reply_markup,
                    parse_mode='Markdown'
                )
            else:
                await update_or_query.message.reply_photo(
                    photo=open(photo, 'rb'),
                    caption=message_text,
                    reply_markup=reply_markup,
                    parse_mode='Markdown'
                )
        except BadRequest as e:
            await update_or_query.message.reply_text(
                text=message_text,
                reply_markup=reply_markup,
                parse_mode='Markdown'
            )
    else:
        if isinstance(update_or_query, Update):
            await update_or_query.message.reply_text(
                text=message_text,
                reply_markup=reply_markup,
                parse_mode='Markdown'
            )
        else:
            await update_or_query.message.reply_text(
                text=message_text,
                reply_markup=reply_markup,
                parse_mode='Markdown'
            )

# Обработчик подтверждения создания товара
async def confirm_product_creation(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    # Получаем данные нового товара из context.user_data
    name = context.user_data.get('new_product_name')
    description = context.user_data.get('new_product_description')
    price = context.user_data.get('new_product_price')
    photo = context.user_data.get('new_product_photo', '')

    # Проверяем, нет ли товара с таким названием
    if any(p['name'] == name for p in products):
        await query.edit_message_text("❌ Товар с таким названием уже существует.")
        return

    # Создаем новый товар и добавляем его в список товаров
    new_product = {
        'name': name,
        'description': description,
        'price': price,
        'image': photo
    }
    products.append(new_product)
    save_products()

    # Очищаем данные из context.user_data
    context.user_data.pop('product_creation_step', None)
    context.user_data.pop('new_product_name', None)
    context.user_data.pop('new_product_description', None)
    context.user_data.pop('new_product_price', None)
    context.user_data.pop('new_product_photo', None)

    await query.edit_message_text("✅ Новый товар успешно создан!")

# Обработчики для редактирования данных нового товара перед созданием
async def edit_new_product_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    context.user_data['product_creation_step'] = 1

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_product_name'), parse_mode='Markdown', reply_markup=reply_markup)

async def edit_new_product_description(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    context.user_data['product_creation_step'] = 2

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_product_description'), parse_mode='Markdown', reply_markup=reply_markup)

async def edit_new_product_price(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    context.user_data['product_creation_step'] = 3

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_price'), parse_mode='Markdown', reply_markup=reply_markup)

async def edit_new_product_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    context.user_data['product_creation_step'] = 4

    keyboard = [
        [InlineKeyboardButton(get_translation(str(query.from_user.id), 'skip_image'), callback_data='skip_image')],
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'attach_product_image'), parse_mode='Markdown', reply_markup=reply_markup)

async def restart_product_creation(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    # Сбрасываем данные
    context.user_data['new_product'] = {}
    context.user_data.pop('new_product_name', None)
    context.user_data.pop('new_product_description', None)
    context.user_data.pop('new_product_price', None)
    context.user_data.pop('new_product_photo', None)
    context.user_data['product_creation_step'] = 1

    keyboard = [
        [InlineKeyboardButton("❌ Отмена", callback_data='cancel_action')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await query.message.reply_text(get_translation(str(query.from_user.id), 'enter_product_name'), parse_mode='Markdown', reply_markup=reply_markup)

# Функция main
def main():
    # Загружаем данные пользователей
    load_user_data()
    # Инициализируем админ-аккаунты
    initialize_admin_accounts()
    # Загружаем товары из файла
    load_products()
    # Загружаем локализации
    load_locales()

    # Создаем приложение
    application = ApplicationBuilder().token('YOUR_TELEGRAM_BOT_TOKEN').build()

    # Регистрируем обработчики
    application.add_handler(CommandHandler('start', start))
    application.add_handler(CallbackQueryHandler(set_language, pattern='^set_language_'))
    application.add_handler(CallbackQueryHandler(change_language_menu, pattern='^change_language$'))
    application.add_handler(CallbackQueryHandler(show_products, pattern='^show_products'))
    application.add_handler(CallbackQueryHandler(show_product_detail, pattern='^product_'))
    application.add_handler(CallbackQueryHandler(add_to_cart, pattern='^add_to_cart_'))
    application.add_handler(CallbackQueryHandler(view_cart, pattern='^view_cart$'))
    application.add_handler(CallbackQueryHandler(clear_cart, pattern='^clear_cart$'))
    application.add_handler(CallbackQueryHandler(remove_from_cart, pattern='^remove_from_cart$'))
    application.add_handler(CallbackQueryHandler(delete_item_from_cart, pattern='^delete_item_'))
    application.add_handler(CallbackQueryHandler(checkout, pattern='^checkout$'))
    application.add_handler(CallbackQueryHandler(personal_cabinet, pattern='^personal_cabinet$'))
    application.add_handler(CallbackQueryHandler(top_up_balance, pattern='^top_up_balance$'))
    application.add_handler(CallbackQueryHandler(back_to_products, pattern='^back_to_products_'))
    application.add_handler(CallbackQueryHandler(main_menu, pattern='^main_menu$'))

    # Обработчики для админ-панели
    application.add_handler(CallbackQueryHandler(admin_panel_callback, pattern='^admin_panel$'))
    application.add_handler(CallbackQueryHandler(admin_view_users, pattern='^admin_view_users$'))
    application.add_handler(CallbackQueryHandler(admin_view_user, pattern='^admin_view_user_'))
    application.add_handler(CallbackQueryHandler(admin_toggle_block_user, pattern='^admin_toggle_block_'))
    application.add_handler(CallbackQueryHandler(admin_change_balance, pattern='^admin_change_balance_'))
    application.add_handler(CallbackQueryHandler(admin_send_message, pattern='^admin_send_message_'))
    application.add_handler(CallbackQueryHandler(admin_add_note_to_user, pattern='^admin_add_note_'))
    application.add_handler(CallbackQueryHandler(admin_view_cart_of_user, pattern='^admin_view_cart_'))
    application.add_handler(CallbackQueryHandler(admin_clear_cart_of_user, pattern='^admin_clear_cart_'))
    application.add_handler(CallbackQueryHandler(admin_delete_item_from_user_cart, pattern='^admin_delete_item_'))
    application.add_handler(CallbackQueryHandler(admin_manage_products, pattern='^admin_manage_products$'))
    application.add_handler(CallbackQueryHandler(admin_edit_product, pattern='^admin_edit_product$'))
    application.add_handler(CallbackQueryHandler(admin_edit_selected_product, pattern='^admin_select_product_'))
    application.add_handler(CallbackQueryHandler(admin_change_product_price, pattern='^admin_change_product_price$'))
    application.add_handler(CallbackQueryHandler(admin_change_product_name, pattern='^admin_change_product_name$'))
    application.add_handler(CallbackQueryHandler(admin_change_product_description, pattern='^admin_change_product_description$'))
    application.add_handler(CallbackQueryHandler(admin_change_product_photo, pattern='^admin_change_product_photo$'))
    application.add_handler(CallbackQueryHandler(admin_delete_product, pattern='^admin_delete_product$'))
    application.add_handler(CallbackQueryHandler(admin_create_product, pattern='^admin_create_product$'))
    application.add_handler(CallbackQueryHandler(skip_image, pattern='^skip_image$'))
    application.add_handler(CallbackQueryHandler(confirm_product_creation, pattern='^confirm_product_creation$'))
    application.add_handler(CallbackQueryHandler(confirm_product_edit, pattern='^confirm_product_edit$'))
    application.add_handler(CallbackQueryHandler(edit_new_product_name, pattern='^edit_new_product_name$'))
    application.add_handler(CallbackQueryHandler(edit_new_product_description, pattern='^edit_new_product_description$'))
    application.add_handler(CallbackQueryHandler(edit_new_product_price, pattern='^edit_new_product_price$'))
    application.add_handler(CallbackQueryHandler(edit_new_product_photo, pattern='^edit_new_product_photo$'))
    application.add_handler(CallbackQueryHandler(restart_product_creation, pattern='^restart_product_creation$'))
    application.add_handler(CallbackQueryHandler(cancel_action, pattern='^cancel_action$'))

    application.add_handler(MessageHandler(filters.PHOTO & (~filters.COMMAND), handle_photo_message))
    application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_text_message))

    # Запускаем бота
    application.run_polling()

if __name__ == '__main__':
    main()