<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

require_once __DIR__ . '/../Database/SettingQueries.php';
require_once __DIR__ . '/../Modules/Admin/Attribute/ManageAttributes.php';
require_once __DIR__ . '/../Modules/Admin/Attribute/ManageValues.php';
require_once __DIR__ . '/../Modules/Admin/Settings/ManageGateways.php';

global $update, $user, $user_id, $platform;

$admin_chat_id = $update['message']['chat']['id'] ?? $update['callback_query']['message']['chat']['id'] ?? 0;
if ($admin_chat_id === 0) {
    if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error: Could not determine admin chat ID in AdminHandler.\nUpdate: " . json_encode($update) . "\n", FILE_APPEND); }
    http_response_code(200);
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}

$message_text_raw = $update['message']['text'] ?? null;
$message_text = $message_text_raw ? trim(convertPersianToEnglishDigits($message_text_raw)) : '';
$callback_data_str = $update['callback_query']['data'] ?? null;
$session_data = $user['session'] ? json_decode($user['session'], true) : [];
if (!is_array($session_data)) { $session_data = ['state' => 'idle']; }
$admin_state = $session_data['state'] ?? 'idle';


if ($callback_data_str !== null) {
    
    $callback_query_id = $update['callback_query']['id'] ?? null;
    $message_id = $update['callback_query']['message']['message_id'] ?? null;
    $callback_params = parseCallbackData($callback_data_str);
    $action = $callback_params['action'] ?? 'noop';

    if ($callback_query_id) {
        apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id], $platform);
    }

    
   switch ($action) {
        
        case 'adminPage':
            $session_data['last_product_offset'] = (int)($callback_params['offset'] ?? 0);
            updateUserField($user_id, 'session', json_encode($session_data));
           showProductList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data);
            break;
        case 'editProd': showEditOptions($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'editProdPhoto': askForNewPhoto($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'editField': askForFieldValue($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setProductMode': handleProductModeSelection($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
        case 'deleteProd': confirmDeleteProduct($callback_params, $admin_chat_id, $message_id, $platform); break;
        case 'confirmDelete': handleDeleteProduct($callback_params, $admin_chat_id, $message_id, $platform); break;
        
        case 'manageProdDiscount': showProductDiscountOptions($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setProdDiscountType': askProductDiscountType($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'selectProdDiscountType': askProductDiscountValue($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'removeProdDiscount': removeProductDiscount($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;

        case 'setSteward': showStewardSelectionList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'confirmSteward': handleStewardSelection($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;

        
      case 'adminOrderPage':
       case 'filterOrderStatus':
        case 'adminOrderReferralPage':
      
      
      case 'filterOrderReferralStatus':
           $session_data['last_order_offset'] = (int)($callback_params['offset'] ?? 0);
            updateUserField($user_id, 'session', json_encode($session_data));
            showOrderList($callback_params + ['action' => $action], $admin_chat_id, $message_id, $user_id, $platform, $session_data);
            break;
            
        case 'viewOrder': showOrderDetails($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setStatus': handleSetStatus($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setTrackingCode': askForTrackingCode($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setShippingFee': askForShippingFee($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;

        
        
        case 'manageUsers':
        case 'viewUserLevel':
            $session_data['last_user_offset'] = (int)($callback_params['offset'] ?? 0);
            updateUserField($user_id, 'session', json_encode($session_data));
           showUserList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data);
            break;
            
      
      case 'viewUser': showUserDetails($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'messageUser': askForMessageToUser($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
      case 'toggleUserStatus': handleToggleUserStatus($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'viewLogs': showUserLogs($callback_params, $admin_chat_id, $message_id, $platform, $session_data); break;
        case 'viewUserFile': showUserFile($callback_params, $admin_chat_id, $message_id, $platform, $callback_query_id); break;
        
      case 'viewUserCardsAdmin': showUserCardsForAdmin($callback_params, $admin_chat_id, $message_id, $platform, $session_data); break;
    
    case 'approveSelfie': handleApproveSelfie($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $callback_query_id, $session_data); break;
         case 'rejectSelfie': askForRejectionReason($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
        
        
        case 'manageCat': showCategoryTree($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'addNestedCat': askForCategoryName($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'setCat': handleCategoryNavigation($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'confirmCat': confirmCategoryAndProceed($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
            
        
        
        
        
        case 'viewDiscounts': showDiscountList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'addDiscountStart': askForDiscountCodeName($admin_chat_id, $user_id, $platform, $session_data); break;
        case 'toggleDiscount': handleToggleDiscount($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'discountSetYear':
        case 'discountSetMonth':
       case 'discountSetDay':
        
        
        case 'discountConfirmDate': handleAddDiscountCallback($action, $callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;

        
        
        
        case 'confirmBroadcast': handleConfirmBroadcast($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
      case 'cancelBroadcast': handleCancelBroadcast($admin_chat_id, $message_id, $user_id, $platform, $session_data); break;

        
        case 'adminSearchUser': askForUserSearchTerm($admin_chat_id, $user_id, $platform, $session_data); break;
        case 'adminSearchOrder': askForOrderSearchTerm($admin_chat_id, $user_id, $platform, $session_data); break;

        
        
      case 'viewPendingRequests': showPendingRequestsList($callback_params, $admin_chat_id, $message_id, $platform, $session_data); break;
      case 'viewRequest': showRequestDetails($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
      
         case 'viewPayouts':
            $session_data['last_payout_offset'] = (int)($callback_params['offset'] ?? 0);
            updateUserField($user_id, 'session', json_encode($session_data));
            showPendingPayoutsList($callback_params, $admin_chat_id, $message_id, $platform, $session_data);
            break;
        case 'viewPayout': showPayoutDetails($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'approvePayout': handleApprovePayout($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'rejectPayout': handleRejectPayout($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
      
    
      
     case 'createInvoiceStart': startCreateInvoice($admin_chat_id, $user_id, $platform, $session_data); break;

        
        
        case 'manageAttributes': showAttributeList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'addAttrStart': askForNewAttributeName($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'deleteAttrConfirm': confirmDeleteAttribute($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'deleteAttrExecute': handleExecuteDeleteAttribute($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'manageAttrValues': showValueList($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'addAttrValueStart': askForNewValueName($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'deleteAttrValueConfirm': confirmDeleteAttributeValue($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'deleteAttrValueExecute': handleExecuteDeleteAttributeValue($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
        
    case 'backToProductType': handleBackToProductType($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'toggleAttr': handleToggleAttribute($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'confirmAttributes': handleConfirmAttributes($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'toggleAttrValue': handleToggleValue($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'confirmAttrValues': handleConfirmValues($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        case 'backToAttrSelection': handleBackToAttrSelection($callback_params, $admin_chat_id, $message_id, $user_id, $platform, $session_data); break;
        
      
        case 'editProdAttributes': 
            $session_data['add_product_data'] = ['attributes' => [], 'selected_values' => []];
            updateUserField($user_id, 'session', json_encode($session_data));
            askForProductAttributes($admin_chat_id, $user_id, $platform, $session_data, $message_id); 
            break;
        case 'listVariations': 
            showPartnerVariationList(['pid' => $callback_params['id'], 'offset' => $callback_params['offset']], $admin_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            break;

        
        case 'adminSettings':
            showGatewaySettings($admin_chat_id, $message_id, $platform);
            break;
        case 'setGateway':
            handleGatewaySwitch($callback_params, $admin_chat_id, $message_id, $platform);
            break;
        
        case 'adminMainMenu': showAdminMainMenu($admin_chat_id, $user_id, $platform, $message_id); break;
        case 'noop': break;
        default:
           
      
     if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Unknown admin callback action '{$action}'\n", FILE_APPEND); }
            
        break;
    }
    
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
}


elseif (isset($update['message'])) {

    
    $mainMenuCommands = ['/start', '/admin', 'انصراف و بازگشت به منو', 'بازگشت 🔙', '/info'];
    
    
    $mainKeyboardButtons = [
        '➕ افزودن محصول', '📝 مدیریت محصولات', '🗂 مدیریت دسته‌بندی‌ها', '🎁 مدیریت تخفیف‌ها',
        '👥 مدیریت کاربران', '📢 پیام‌رسانی', '📊 داشبورد مدیریتی', '📈 گزارشات',
        '🔎 جستجوی پیشرفته', '🛎 درخواست‌های در انتظار', '🧾 ایجاد فاکتور آزاد',
        '📋 سفارشات عادی', '📈 سفارشات ارجاعی', '💳 درخواست‌های تسویه',
        'مدیریت ویژگی‌ها', '⚙️ تنظیمات فروشگاه'
    ];

    $resetCommands = array_merge($mainMenuCommands, $mainKeyboardButtons);
    
    
    if (($message_text_raw === 'انصراف و بازگشت به منو' || $message_text_raw === 'انصراف') && $admin_state !== 'idle') {
        sendMessage($admin_chat_id, "عملیات لغو شد. به منوی اصلی بازگشتید.", ['remove_keyboard' => true], $platform);
        updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
        showAdminMainMenu($admin_chat_id, $user_id, $platform);
      
    
 
       if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    }
    
    $non_interrupt_states = [
     
   'awaiting_product_type', 'awaiting_category_selection', 'adding_product_photo', 'awaiting_product_name',
        'awaiting_product_description', 'awaiting_product_price', 'awaiting_product_stock',
        'awaiting_product_unit', 'awaiting_product_weight', 'awaiting_product_weight_unit',
        'editing_product_photo', 'admin_editing_field',
        'awaiting_category_name', 'awaiting_prod_discount_value', 'awaiting_tracking_code',
        'awaiting_shipping_fee_amount', 'awaiting_shipping_fee_note',
        'awaiting_admin_rejection_reason',
        
        'awaiting_direct_message', 'awaiting_broadcast_message', 'awaiting_discount_code_name',
      'awaiting_discount_type', 'awaiting_discount_value', 'awaiting_discount_max_uses',
        'awaiting_user_search_term', 'awaiting_order_search_term',
        'awaiting_invoice_user_id', 'awaiting_invoice_amount', 'awaiting_invoice_description',
           'awaiting_payout_rejection_reason',
           
        'awaiting_new_attribute_name', 'awaiting_new_value_name',
        'awaiting_attribute_selection', 'awaiting_value_selection',
        'awaiting_variation_price', 'awaiting_variation_stock',
        'awaiting_variation_weight', 'awaiting_variation_weight_unit',
     'awaiting_variation_photo', 'awaiting_variation_field_value',
        'editing_variation_photo'
    ];

    if ($admin_state !== 'idle' && in_array($message_text_raw, $resetCommands, true)) {
        
        if (in_array($admin_state, $non_interrupt_states)) {
             
            sendMessage($admin_chat_id, "⚠️ شما در حال انجام یک عملیات هستید. لطفا ابتدا آن را تکمیل کرده یا از دکمه 'انصراف و بازگشت به منو' استفاده کنید.", null, $platform);
          
            if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
            
            
        } else {
      
      
 
       sendMessage($admin_chat_id, "عملیات فعلی لغو شد.", null, $platform);
            
            updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
            $admin_state = 'idle';
        }
     }
    
  
    
    
    
    
    if ($admin_state !== 'idle') {
         switch ($admin_state) {
            
          
     
     case 'awaiting_product_type': handleProductType($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
      case 'adding_product_photo': handleProductPhoto($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_product_name': handleProductName($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_product_description': handleProductDescription($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
        
            case 'awaiting_product_price': handleProductPrice($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;

            
            
case 'awaiting_product_stock': handleProductStock($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_product_unit': handleProductUnit($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_product_weight': handleProductWeight($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_product_weight_unit': handleProductWeightUnitAndSave($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            
            
        
    
       
     case 'editing_product_photo': handleNewPhoto($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'admin_editing_field': handleFieldValueInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
             case 'awaiting_category_name': handleCategoryNameInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            case 'awaiting_prod_discount_value': handleProductDiscountValue($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            
            case 'awaiting_tracking_code': handleTrackingCodeInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
          
        
    
            case 'awaiting_shipping_fee_amount': handleShippingFeeInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_shipping_fee_note': handleShippingFeeNoteInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            
        
         case 'awaiting_admin_rejection_reason': handleRejectionReasonInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_payout_rejection_reason': handlePayoutRejectionReasonInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
 
  
            
            case 'awaiting_direct_message': handleDirectMessageInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            case 'awaiting_broadcast_message': handleBroadcastMessageInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
           
 

            
            
            case 'awaiting_discount_code_name': handleCodeNameInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_discount_type': handleDiscountTypeInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_discount_value': handleDiscountValueInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_discount_max_uses': handleMaxUsesInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
 
            
        
  
            case 'awaiting_user_search_term': handleUserSearchTerm($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_order_search_term': handleOrderSearchTerm($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;

            
            
 
            
            
            case 'awaiting_invoice_user_id': handleInvoiceUserIdInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_invoice_amount': handleInvoiceAmountInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_invoice_description': handleInvoiceDescriptionInput($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;

            
           
 
            case 'awaiting_new_attribute_name': handleNewAttributeName($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_new_value_name': handleNewValueName($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            
            case 'awaiting_variation_price': handleVariationPrice($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_variation_stock': handleVariationStock($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_variation_weight': handleVariationWeight($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_variation_weight_unit': handleVariationWeightUnit($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;
            case 'awaiting_variation_photo': handleVariationPhoto($update['message'], $admin_chat_id, $user_id, $platform, $session_data); break;

            
            case 'awaiting_category_selection':
            case 'awaiting_attribute_selection':
            case 'awaiting_value_selection':
              sendMessage($admin_chat_id, "لطفا از دکمه‌های شیشه‌ای برای انتخاب استفاده کنید.", null, $platform);
                 break;
                
            default:
            
      
                
                
if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Unknown admin state '{$admin_state}' for user {$user_id}.\n", FILE_APPEND); }
                
            sendMessage($admin_chat_id, "مشکلی پیش آمد. به منوی اصلی بازگشتید.", null, $platform);
 
    
                updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
                showAdminMainMenu($admin_chat_id, $user_id, $platform);
         
       break;
        }

        if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return;
}
        
    }
    
    
    
  
 
    elseif ($admin_state === 'idle') {
        switch ($message_text_raw) {
            case '➕ افزودن محصول': 
            startAddProductFlow($admin_chat_id, $user_id, $platform); break;
            case '📝 مدیریت محصولات': showProductList(['offset' => 0], $admin_chat_id, null, $user_id, $platform, $session_data); break;
            
         case '🗂 مدیریت دسته‌بندی‌ها': showCategoryTree(['id' => null], $admin_chat_id, null, $user_id, $platform, $session_data); break;
 
         
         case 'مدیریت ویژگی‌ها': showAttributeList(['offset' => 0], $admin_chat_id, null, $user_id, $platform, $session_data); break;
            
            case '🎁 مدیریت تخفیف‌ها': showDiscountList(['offset' => 0], $admin_chat_id, null, $user_id, $platform, $session_data); break;
            
case '👥 مدیریت کاربران': showUserList(['level' => 'root'], $admin_chat_id, null, $user_id, $platform, $session_data); break;
            case '📢 پیام‌رسانی': askForBroadcastMessage($admin_chat_id, $user_id, $platform, $session_data); break;
            
            case '📋 سفارشات عادی':
            
                $session_data['order_filter'] = 'all';
                  $session_data['order_view_type'] = 'normal';
                 $session_data['last_order_offset'] = 0;
          updateUserField($user_id, 'session', json_encode($session_data));
                showOrderList(['action' => 'filterOrderStatus', 'offset' => 0, 'status' => 'all'], $admin_chat_id, null, $user_id, $platform, $session_data);
                break;

   
            case '📈 سفارشات ارجاعی':
                $session_data['order_filter'] = 'all';
            $session_data['order_view_type'] = 'referral';
                $session_data['last_order_offset'] = 0;
                updateUserField($user_id, 'session', json_encode($session_data));
                showOrderList(['action' => 'filterOrderReferralStatus', 'offset' => 0, 'status' => 'all'], $admin_chat_id, null, $user_id, $platform, $session_data);
                break;
            
     case '🔎 جستجوی پیشرفته': showSearchOptions($admin_chat_id, $platform); break;
            
          
        
      case '🛎 درخواست‌های در انتظار': showPendingRequestsList(['offset' => 0], $admin_chat_id, null, $platform, $session_data); break;
            case '💳 درخواست‌های تسویه': showPendingPayoutsList(['offset' => 0], $admin_chat_id, null, $platform, $session_data); break;
             
         case '🧾 ایجاد فاکتور آزاد': startCreateInvoice($admin_chat_id, $user_id, $platform, $session_data); break;

            
      
  
            
            case '📊 داشبورد مدیریتی':
 
           case '📈 گزارشات': sendMessage($admin_chat_id, $message_text_raw . "\n\nدر حال توسعه...", null, $platform); break;
     
   
            case '/info':
 
 
                $user_info_json = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                sendMessage($admin_chat_id, "```json\n" . $user_info_json . "\n```", null, $platform);
                break;
            
    
            case '/start':
            case '/admin':
            
            case 'انصراف و بازگشت به منو':
            
          
  case 'بازگشت 🔙': showAdminMainMenu($admin_chat_id, $user_id, $platform); break;

            case '⚙️ تنظیمات فروشگاه':
                showGatewaySettings($admin_chat_id, null, $platform);
                break;

            default: break;
        }
        
   
        
        if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
    
    
 
      }
}


function showAdminMainMenu(int $chat_id, int $user_id, string $platform, ?int $message_id = null): void {
    
    $keyboard_markup = getAdminMainMenuKeyboard();

    if ($message_id) {
         @apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);

    }

   sendMessage($chat_id, "⚙️ پنل مدیریت", $keyboard_markup, $platform);
    $user_data = getUserById($user_id);
    $current_session_data = $user_data ? json_decode($user_data['session'] ?? '{}', true) : ['state' => 'idle'];
    if(($current_session_data['state'] ?? 'idle') !== 'idle') {
         updateUserField($user_id, 'session', json_encode(['state'=>'idle']));
    }

}


function showSearchOptions(int $chat_id, string $platform): void {
    $buttons = [
 
        [['text' => '🔍 جستجوی کاربر', 'callback_data' => buildCallbackData('adminSearchUser')]],
        [['text' => '🔍 جستجوی سفارش', 'callback_data' => buildCallbackData('adminSearchOrder')]]
   ];
    sendMessage($chat_id, "نوع جستجو را انتخاب کنید:", ['inline_keyboard' => $buttons], $platform);
}

?>