<?php

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

require_once __DIR__ . '/../Modules/Customer/Product/HandleVariationSelection.php';

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

$customer_chat_id = $update['message']['chat']['id'] ?? $update['callback_query']['message']['chat']['id'] ?? 0;
if ($customer_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 customer chat ID in CustomerHandler.\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']; }

$customer_state = $session_data['state'] ?? 'idle';

if ($message_text_raw !== null) {
    logUserActivity($user_id, 'message', ['text' => $message_text_raw]);
} elseif ($callback_data_str !== null) {
    logUserActivity($user_id, 'callback', ['data' => $callback_data_str]);
}


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);
    }

    $is_partner = (($user['is_admin'] ?? false) == false && $user['referred_by_user_id'] === null);

    switch ($action) {

         case 'custProdOrderPage':
             showCustomerProductOrderList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
        case 'viewCustProdOrder':
             showCustomerOrderDetails($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
        case 'custInvoicePage':
            showCustomerInvoiceOrderList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
            break;
        case 'viewCustInvoiceOrder':
             showCustomerOrderDetails($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
         
         case 'viewCart':
             showCart($customer_chat_id, $user_id, $message_id, $platform, $user);
           
           break;
 
       case 'updateCartQty':
             handleUpdateQuantity($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
         case 'removeCartItem':
             handleRemoveItem($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
       
      break;
        case 'clearCartConfirm':
             confirmClearCart($callback_params, $customer_chat_id, $message_id, $user_id, $platform);
             break;
         case 'clearCartExecute':
             handleClearCart($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
     
        break;

        case 'checkoutStart':
             startCheckout($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
            break;
        case 'selectCardForCheckout':
             handleCardSelection($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);

           break;
        case 'backToProvinceSelection':
        case 'selectProvincePage':
             showProvinceSelector($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user); 
             break;
        case 'selectProvince':

             handleProvinceSelection($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
             break;
        case 'selectCityPage':
             showCitySelector($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user); 
             break;
     
          case 'selectCity':
         
    handleCitySelection($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user); 
             break;
        case 'applyDiscount':
             askForDiscountCode($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user); 
             break;
        case 'removeDiscount':
             handleRemoveDiscount($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
             break;
        case 'confirmOrderBeforePayment':
             handleConfirmation($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
         
        break;

        case 'manageCards':
             showCardList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
         case 'addCard':
             askForCardNumber($callback_params, $customer_chat_id, $message_id, $user_id, $platform);

             break;
        case 'deleteCardPrompt':
             confirmDeleteCard($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
             break;
         case 'deleteCardExecute':
             handleDeleteCard($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);

             break;

         case 'viewCat':
             showCategoryOrProducts($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            break;
        case 'addToCart':
             askForQuantity($callback_params, $customer_chat_id, $message_id, $user_id, $platform);
             break;

        case 'selectAttributeValue':
        case 'backToAttribute':
            handleVariationSelection($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data);
            break;

        case 'searchNav':
             showSearchResult($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
             break;

        case 'manageShop':
           
            if ($is_partner) {
                 showPartnerShopMenu($customer_chat_id, $user_id, $platform, $user, $message_id);
            }
          break;
        case 'managePartnerProds':
            if ($is_partner) {
                showPartnerProductList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            }
            break;
        case 'managePartnerVariations':
            if ($is_partner) {
                showPartnerVariationList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            }
            break;
        case 'setPartnerPrice':
             if ($is_partner) {
               
 askPartnerForPrice($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data);
            }
            break;
        case 'deactPartnerProd':
             if ($is_partner) {
                handlePartnerProductDeactivate($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
  
          }
            break;


        case 'listPartnerOrders':
           case 'listCustomerOrders':
            if ($is_partner) {
                showPartnerOrderList($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);

            }
          
          break;
        case 'viewPartnerCustomerOrder':
             if ($is_partner) {
                showPartnerCustomerOrderDetails($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $user);
            }

             break;

        case 'partnerPayout':
            if ($is_partner) {
                showPayoutMenu($customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            }
           
         break;
        case 'partnerSelectPayoutCard':
            if ($is_partner) {
                confirmPayoutRequest($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data);
            }
            break;
 
       case 'partnerConfirmPayout':
            if ($is_partner) {
                handleCreatePayoutRequest($callback_params, $customer_chat_id, $message_id, $user_id, $platform, $session_data, $user);
            }
            break;

        case 'mainMenu':
              showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user, $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 customer callback action '{$action}'\n", FILE_APPEND); }
             break;
     }
    
    if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return;
}
    
}

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


    $is_partner = (($user['is_admin'] ?? false) == false && $user['referred_by_user_id'] === null);

    $mainMenuCommands = ['/start', 'بازگشت به منو اصلی 🔙', '🛍 مشاهده فروشگاه', '🛒 سبد خرید', '💳 مدیریت کارت‌ها', '🔎 جستجوی محصول'];
    if ($is_partner) 
{
        $mainMenuCommands[] = '🛍️ فروشگاه من';
        $mainMenuCommands[] = '📦 سفارشات محصول';
         $mainMenuCommands[] = '🧾 فاکتورهای آزاد';
        $mainMenuCommands[] = '📈 سفارشات مشتریانم';
        $mainMenuCommands[] = '💰 نقد کردن درآمد';
    } else {
        $mainMenuCommands[] = '📦 سفارشات محصول';
        $mainMenuCommands[] = '🧾 فاکتورهای آزاد';
    }

    $cancellable_states = ['awaiting_quantity', 'awaiting_search_query'];
    $non_interrupt_states = [
        'awaiting_new_card_number', 'awaiting_checkout_address', 'awaiting_checkout_postalcode', 
        'awaiting_order_note', 'awaiting_discount_code', 'awaiting_partner_price'
    ];

    if ($customer_state !== 'idle' && in_array($message_text_raw, $mainMenuCommands)) {

          if (in_array($customer_state, $non_interrupt_states)) {
             sendMessage($customer_chat_id, "⚠️ شما در حال انجام یک عملیات هستید. لطفا ابتدا آن را تکمیل کرده یا از دکمه 'انصراف' (پایین صفحه کلید) استفاده کنید.", null, $platform);
             
             if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
              
    
 
          } elseif (in_array($customer_state, $cancellable_states)) {
             sendMessage($customer_chat_id, "عملیات فعلی لغو شد.", ['remove_keyboard' => true], $platform);
             updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
             showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user);
            

             if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
             
         } else {
             sendMessage($customer_chat_id, "عملیات فعلی لغو شد.", ['remove_keyboard' => true], $platform);
          
   

             updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
             showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user);
             
             if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
             
    
      }
    }

    if ($message_text_raw === 'انصراف' || $message_text_raw === 'Cancel') {
          sendMessage($customer_chat_id, "عملیات لغو شد. به منوی اصلی بازگشتید.", ['remove_keyboard' => true], $platform);
          updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
          showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user);
     
    

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

    if ($customer_state !== 'idle') {
        switch ($customer_state) {
     
        
             case 'awaiting_quantity':
                 handleQuantityInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user);
                 break;
             case 'awaiting_new_card_number':
              
                 handleCardNumberInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user);
                 break;
 
             case 'awaiting_checkout_address':
                 handleAddressInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user); 
                 break;
 
 
             case 'awaiting_checkout_postalcode':
 
                handlePostalCodeInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user); 
                 break;
        
     case 'awaiting_order_note':
              
                handleNoteInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user); 
                 break;
             case 'awaiting_discount_code':
                 handleDiscountCodeInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user);
                 break;
      
        
            case 'awaiting_payment_confirmation':
                 break;
            
            case 'awaiting_search_query':
                 handleSearchQuery($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user);

                 break;
            
            case 'awaiting_partner_price':
                if ($is_partner) {
                    handlePartnerPriceInput($update['message'], $customer_chat_id, $user_id, $platform, $session_data, $user);

               }
                break;
            
            case 'product_variation_selection':
                sendMessage($customer_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 customer state '{$customer_state}' for user {$user_id}.\n", FILE_APPEND); }
       
       sendMessage($customer_chat_id, "مشکلی پیش آمد. به منوی اصلی بازگشتید.", null, $platform);
                  updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
                  showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user);
                  break;
     
     
        }
         
         if (!defined('IS_BRIDGE_CALL') || IS_BRIDGE_CALL !== true) { exit(); } else { return; }
         
     }

 
  
   
 
    elseif ($customer_state === 'idle') {
     
     switch ($message_text_raw) {
             case '/start':
             case 'بازگشت به منو اصلی 🔙':
                  showCustomerMainMenu($customer_chat_id, $user_id, $platform, $user);
                 break;
           
  
             case '/info':
                  $user_info_json = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                  sendMessage($customer_chat_id, "```json\n" . $user_info_json . "\n```", null, $platform);
                  break;

             case '🛍 مشاهده فروشگاه':
                  showCategoryOrProducts(['id' => null, 'offset' => 0], $customer_chat_id, null, $user_id, $platform, $session_data, $user);
                  break;
  
           case '🛒 سبد خرید':
                 showCart($customer_chat_id, $user_id, null, $platform, $user);
                  break;
             case '📦 سفارشات محصول':
                  if ($is_partner) {
                      showPartnerOrderList(['offset' => 0, 'type' => 'self'], $customer_chat_id, null, $user_id, $platform, $user);
                  } else {
                      showCustomerProductOrderList(['offset' => 0], $customer_chat_id, null, $user_id, $platform, $user);
                  }
                 break;
  
             case '🧾 فاکتورهای آزاد':
                 showCustomerInvoiceOrderList(['offset' => 0], $customer_chat_id, null, $user_id, $platform, $user);
                 break;
         
            case '📈 سفارشات مشتریانم':
                 if ($is_partner) {
                     showPartnerOrderList(['offset' => 0, 'type' => 'customer'], $customer_chat_id, null, $user_id, $platform, $user);
                 }
                 break;
 
             case '💰 نقد کردن درآمد':
                 if ($is_partner) {
                     showPayoutMenu($customer_chat_id, null, $user_id, $platform, $session_data, $user);
                 }
                 break;

             case '💳 مدیریت کارت‌ها':
                 showCardList([], $customer_chat_id, null, $user_id, $platform, $user);
                  break;
             case '🔎 جستجوی محصول':
                 
                 askForSearchQuery($customer_chat_id, $user_id, $platform);
                 break;
             case '🛍️ فروشگاه من':
                 if ($is_partner) {
                    showPartnerShopMenu($customer_chat_id, $user_id, $platform, $user, null);
        
                 }

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

}

?>