<?php

namespace Modules\Whatsapp\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Models\Kot;
use App\Models\Role;
use Modules\Whatsapp\Entities\WhatsAppNotificationPreference;
use Modules\Whatsapp\Services\WhatsAppNotificationService;
use Modules\Whatsapp\Services\WhatsAppHelperService;

class SendKotNotificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $kotId;

    /**
     * Create a new job instance.
     */
    public function __construct($kotId)
    {
        $this->kotId = $kotId;
    }

    /**
     * Execute the job.
     */
    public function handle(WhatsAppNotificationService $notificationService, WhatsAppHelperService $helperService)
    {
        try {
            // Wait 8 seconds for all items to be saved (increased from 5 to 8)
            // This is inside the job, so it won't block the POS
            // Some items might be added to the order after the initial KOT is created
            sleep(8);
            
            Log::info('WhatsApp KOT Notification Job: After 8 second sleep, loading KOT', [
                'kot_id' => $this->kotId,
            ]);
            
            // Load KOT first to get order ID
            $kot = \App\Models\Kot::find($this->kotId);
            if (!$kot) {
                Log::warning('WhatsApp KOT Notification Job: KOT not found', [
                    'kot_id' => $this->kotId,
                ]);
                return;
            }
            
            $order = $kot->order;
            if (!$order) {
                Log::warning('WhatsApp KOT Notification Job: Order not found for KOT', [
                    'kot_id' => $this->kotId,
                ]);
                return;
            }
            
            // Retry mechanism: Check if more items are being added
            // If we find new items, wait a bit more and check again
            $maxRetries = 3; // Increased from 2 to 3
            $retryDelay = 3; // Increased from 2 to 3 seconds
            $previousItemCount = 0;
            $previousKotCount = 0;
            
            for ($retry = 0; $retry < $maxRetries; $retry++) {
                // Reload order to get current KOT count
                $order->refresh();
                
                // Query DIRECTLY from database tables (not through relationships) to get accurate counts
                $currentKotIds = \App\Models\Kot::where('order_id', $order->id)->pluck('id')->toArray();
                $currentKotCount = count($currentKotIds);
                $currentItemCount = \App\Models\KotItem::whereIn('kot_id', $currentKotIds)->count();
                
                Log::info('WhatsApp KOT Notification Job: Retry check', [
                    'retry' => $retry + 1,
                    'max_retries' => $maxRetries,
                    'current_kot_count' => $currentKotCount,
                    'current_kot_ids' => $currentKotIds,
                    'current_item_count' => $currentItemCount,
                    'previous_item_count' => $previousItemCount,
                    'previous_kot_count' => $previousKotCount,
                ]);
                
                // If KOT count or item count increased, wait a bit more
                if (($currentKotCount > $previousKotCount || $currentItemCount > $previousItemCount) && $retry < $maxRetries - 1) {
                    Log::info('WhatsApp KOT Notification Job: Items still being added, waiting more', [
                        'retry' => $retry + 1,
                        'kot_count_increased' => $currentKotCount > $previousKotCount,
                        'item_count_increased' => $currentItemCount > $previousItemCount,
                        'new_kot_ids' => array_diff($currentKotIds, $previousKotCount > 0 ? [] : $currentKotIds),
                    ]);
                    sleep($retryDelay);
                    $previousItemCount = $currentItemCount;
                    $previousKotCount = $currentKotCount;
                } else {
                    // No new items or max retries reached, proceed
                    break;
                }
            }
            
            // Load KOT with all items (3 seconds have passed, all items should be saved)
            // Load modifierOptions with their names to ensure we get all modifiers including extra toppings, dips & sauces
            $kot = Kot::with([
                'order.table', 
                'order.orderType', 
                'order.branch',
                'order.kot' => function($query) {
                    // Load all KOTs for this order to get all items
                    $query->with([
                        'items.menuItem',
                        'items.modifierOptions' => function($modifierQuery) {
                            // Ensure we load the modifier option name properly
                            $modifierQuery->select('modifier_options.id', 'modifier_options.name', 'modifier_options.modifier_group_id');
                        }
                    ]);
                },
                'items.menuItem', 
                'items.modifierOptions' => function($query) {
                    // Ensure we load the modifier option name properly
                    $query->select('modifier_options.id', 'modifier_options.name', 'modifier_options.modifier_group_id');
                }
            ])->find($this->kotId);
            
            if (!$kot) {
                Log::error('WhatsApp KOT Notification Job: KOT not found', [
                    'kot_id' => $this->kotId,
                ]);
                return;
            }
            
            // Check if already sent
            $sentKey = 'kot_notification_sent_' . $kot->id;
            if (cache()->has($sentKey)) {
                Log::info('WhatsApp KOT Notification Job: Already sent, skipping', [
                    'kot_id' => $kot->id,
                ]);
                return;
            }
            
            // Mark as sent immediately
            cache()->put($sentKey, true, 3600);
            
            $order = $kot->order;
            if (!$order) {
                Log::info('WhatsApp KOT Notification Job: Order not found', [
                    'kot_id' => $kot->id,
                ]);
                return;
            }

            $restaurantId = $order->branch->restaurant_id ?? null;
            if (!$restaurantId) {
                Log::info('WhatsApp KOT Notification Job: Restaurant ID not found', [
                    'kot_id' => $kot->id,
                ]);
                return;
            }

            // Check if WhatsApp module is in restaurant's package
            if (function_exists('restaurant_modules')) {
                $restaurant = \App\Models\Restaurant::find($restaurantId);
                if ($restaurant) {
                    $restaurantModules = restaurant_modules($restaurant);
                    if (!in_array('Whatsapp', $restaurantModules)) {
                        Log::info('WhatsApp KOT Notification Job: Skipping - WhatsApp module not in restaurant package', [
                            'kot_id' => $kot->id,
                            'restaurant_id' => $restaurantId,
                        ]);
                        return;
                    }
                }
            }

            // Check if notification is enabled
            $preference = WhatsAppNotificationPreference::where('restaurant_id', $restaurantId)
                ->where('notification_type', 'kitchen_notification')
                ->where('recipient_type', 'staff')
                ->where('is_enabled', true)
                ->first();

            if (!$preference) {
                Log::info('WhatsApp KOT Notification Job: Preference not enabled', [
                    'restaurant_id' => $restaurantId,
                ]);
                return;
            }

            // Get Chef role for this restaurant
            $chefRole = Role::where('restaurant_id', $restaurantId)
                ->where('display_name', 'Chef')
                ->first();

            $kitchenStaff = collect();
            
            if ($chefRole) {
                // Get all chefs with mobile numbers
                $kitchenStaff = $helperService->getUsersByRoles($restaurantId, [$chefRole->id]);
            }
            
            // If no chefs found, try to get staff/waiter roles as fallback
            if ($kitchenStaff->isEmpty()) {
                Log::info('WhatsApp KOT Notification Job: No chefs found, trying staff/waiter roles', [
                    'restaurant_id' => $restaurantId,
                ]);
                
                // Try to find Staff or Waiter roles
                $staffRoles = Role::where('restaurant_id', $restaurantId)
                    ->whereIn('display_name', ['Staff', 'Waiter', 'Kitchen Staff'])
                    ->pluck('id')
                    ->toArray();
                
                if (!empty($staffRoles)) {
                    $kitchenStaff = $helperService->getUsersByRoles($restaurantId, $staffRoles);
                }
            }
            
            // If still no staff found, get all users with staff-related roles
            if ($kitchenStaff->isEmpty()) {
                Log::info('WhatsApp KOT Notification Job: No staff roles found, trying all users with phone numbers', [
                    'restaurant_id' => $restaurantId,
                ]);
                
                // Get all users with phone numbers (excluding admin roles)
                $kitchenStaff = \App\Models\User::where('restaurant_id', $restaurantId)
                    ->whereNotNull('phone_number')
                    ->whereHas('roles', function($q) {
                        $q->where('display_name', '!=', 'Admin');
                    })
                    ->get();
            }

            if ($kitchenStaff->isEmpty()) {
                Log::info('WhatsApp KOT Notification Job: No kitchen staff with phone numbers found', [
                    'restaurant_id' => $restaurantId,
                ]);
                return;
            }
            
            // CRITICAL: Get ALL items from ALL KOTs in this order
            // Multiple KOTs can be created for the same order (one per kitchen place)
            // We need to wait and retry to ensure ALL KOTs are created before collecting items
            // Query DIRECTLY from kot_items table to ensure we get everything
            
            // First, get all KOT IDs for this order
            $allKotIds = \App\Models\Kot::where('order_id', $order->id)->pluck('id')->toArray();
            
            Log::info('WhatsApp KOT Notification Job: Found KOTs for order (initial check)', [
                'order_id' => $order->id,
                'kot_ids' => $allKotIds,
                'kot_count' => count($allKotIds),
                'triggering_kot_id' => $kot->id,
            ]);
            
            // If we only have 1 KOT but there might be more being created, wait a bit
            // This handles the case where multiple KOTs are created in a loop
            if (count($allKotIds) == 1) {
                // Wait 2 more seconds to see if more KOTs are created
                sleep(2);
                $allKotIds = \App\Models\Kot::where('order_id', $order->id)->pluck('id')->toArray();
                Log::info('WhatsApp KOT Notification Job: Re-checked KOTs after 2 second wait', [
                    'order_id' => $order->id,
                    'kot_ids' => $allKotIds,
                    'kot_count' => count($allKotIds),
                ]);
            }
            
            // Now query ALL kot_items DIRECTLY from database for ALL KOTs
            // Use fresh() to bypass any query cache and get the latest data
            $allKotItems = \App\Models\KotItem::whereIn('kot_id', $allKotIds)
                ->with([
                    'menuItem',
                    'modifierOptions' => function($modifierQuery) {
                        $modifierQuery->select('modifier_options.id', 'modifier_options.name', 'modifier_options.modifier_group_id');
                    }
                ])
                ->get();
            
            // Log detailed information about what we found
            $itemsByKot = [];
            foreach ($allKotItems as $item) {
                $kotId = $item->kot_id;
                if (!isset($itemsByKot[$kotId])) {
                    $itemsByKot[$kotId] = [];
                }
                $itemsByKot[$kotId][] = [
                    'id' => $item->id,
                    'menu_item_id' => $item->menu_item_id,
                    'quantity' => $item->quantity,
                ];
            }
            
            Log::info('WhatsApp KOT Notification Job: Loaded ALL items directly from database', [
                'order_id' => $order->id,
                'all_kot_ids' => $allKotIds,
                'total_kots' => count($allKotIds),
                'total_items_found' => $allKotItems->count(),
                'items_by_kot' => $itemsByKot,
                'all_item_ids' => $allKotItems->pluck('id')->toArray(),
            ]);
            
            // ALWAYS check OrderItems - items might be in order but not yet in KOTs
            // This can happen if items are added after KOT creation or if there's a delay
            // Also, OrderItems are created when order status is 'billed', so they might exist even if KOT items don't
            $orderItems = \App\Models\OrderItem::where('order_id', $order->id)
                ->with([
                    'menuItem',
                    'modifierOptions' => function($modifierQuery) {
                        $modifierQuery->select('modifier_options.id', 'modifier_options.name', 'modifier_options.modifier_group_id');
                    }
                ])
                ->get();
            
            // Also check CartItems - items might be in cart session but not yet converted to KOT items
            // CartSession has order_id, so we can find cart items for this order
            $cartItems = collect();
            $cartSessions = \App\Models\CartSession::where('order_id', $order->id)
                ->with([
                    'cartItems.menuItem',
                    'cartItems.menuItemVariation',
                    'cartItems.modifiers' => function($modifierQuery) {
                        $modifierQuery->select('modifier_options.id', 'modifier_options.name', 'modifier_options.modifier_group_id');
                    }
                ])
                ->get();
            
            foreach ($cartSessions as $cartSession) {
                if ($cartSession->cartItems && $cartSession->cartItems->isNotEmpty()) {
                    $cartItems = $cartItems->merge($cartSession->cartItems);
                }
            }
            
            $orderItemsCount = $orderItems->count();
            $cartItemsCount = $cartItems->count();
            Log::info('WhatsApp KOT Notification Job: Checking OrderItems and CartItems', [
                'order_id' => $order->id,
                'order_items_count' => $orderItemsCount,
                'cart_items_count' => $cartItemsCount,
                'kot_items_count' => $allKotItems->count(),
                'order_item_ids' => $orderItems->pluck('id')->toArray(),
                'cart_item_ids' => $cartItems->pluck('id')->toArray(),
            ]);
            
            // ALWAYS merge OrderItems with KOT items to ensure we get everything
            // Create a collection that combines both sources
            $allItems = collect();
            
            // First, add all KOT items
            foreach ($allKotItems as $kotItem) {
                $allItems->push((object)[
                    'id' => $kotItem->id,
                    'menu_item_id' => $kotItem->menu_item_id,
                    'menu_item_variation_id' => $kotItem->menu_item_variation_id ?? null,
                    'quantity' => $kotItem->quantity,
                    'note' => $kotItem->note ?? null,
                    'menuItem' => $kotItem->menuItem,
                    'modifierOptions' => $kotItem->modifierOptions ?? collect(),
                ]);
            }
            
            // Then add OrderItems that aren't already in KOTs
            // Match by menu_item_id, variation_id, and quantity to avoid duplicates
            foreach ($orderItems as $orderItem) {
                // Check if this item already exists in KOT items
                $exists = $allKotItems->contains(function($kotItem) use ($orderItem) {
                    return $kotItem->menu_item_id == $orderItem->menu_item_id 
                        && ($kotItem->menu_item_variation_id ?? null) == ($orderItem->menu_item_variation_id ?? null)
                        && $kotItem->quantity == $orderItem->quantity;
                });
                
                if (!$exists) {
                    Log::info('WhatsApp KOT Notification Job: Adding OrderItem not in KOT', [
                        'order_item_id' => $orderItem->id,
                        'menu_item_id' => $orderItem->menu_item_id,
                        'menu_item_variation_id' => $orderItem->menu_item_variation_id,
                        'quantity' => $orderItem->quantity,
                    ]);
                    
                    $allItems->push((object)[
                        'id' => $orderItem->id,
                        'menu_item_id' => $orderItem->menu_item_id,
                        'menu_item_variation_id' => $orderItem->menu_item_variation_id ?? null,
                        'quantity' => $orderItem->quantity,
                        'note' => $orderItem->note ?? null,
                        'menuItem' => $orderItem->menuItem,
                        'modifierOptions' => $orderItem->modifierOptions ?? collect(),
                    ]);
                }
            }
            
            // Also add CartItems that aren't already in KOTs or OrderItems
            // These are items that might be in the cart but not yet converted to KOT items
            foreach ($cartItems as $cartItem) {
                // Check if this item already exists in KOT items or OrderItems
                $existsInKot = $allKotItems->contains(function($kotItem) use ($cartItem) {
                    return $kotItem->menu_item_id == $cartItem->menu_item_id 
                        && ($kotItem->menu_item_variation_id ?? null) == ($cartItem->menu_item_variation_id ?? null)
                        && $kotItem->quantity == $cartItem->quantity;
                });
                
                $existsInOrder = $orderItems->contains(function($orderItem) use ($cartItem) {
                    return $orderItem->menu_item_id == $cartItem->menu_item_id 
                        && ($orderItem->menu_item_variation_id ?? null) == ($cartItem->menu_item_variation_id ?? null)
                        && $orderItem->quantity == $cartItem->quantity;
                });
                
                if (!$existsInKot && !$existsInOrder) {
                    Log::info('WhatsApp KOT Notification Job: Adding CartItem not in KOT or OrderItems', [
                        'cart_item_id' => $cartItem->id,
                        'menu_item_id' => $cartItem->menu_item_id,
                        'menu_item_variation_id' => $cartItem->menu_item_variation_id,
                        'quantity' => $cartItem->quantity,
                    ]);
                    
                    // Get modifiers from cart item
                    $cartItemModifiers = collect();
                    if ($cartItem->modifiers && $cartItem->modifiers->isNotEmpty()) {
                        $cartItemModifiers = $cartItem->modifiers;
                    }
                    
                    $allItems->push((object)[
                        'id' => $cartItem->id,
                        'menu_item_id' => $cartItem->menu_item_id,
                        'menu_item_variation_id' => $cartItem->menu_item_variation_id ?? null,
                        'quantity' => $cartItem->quantity,
                        'note' => null, // CartItems don't have notes
                        'menuItem' => $cartItem->menuItem,
                        'modifierOptions' => $cartItemModifiers,
                    ]);
                }
            }
            
            // Use the combined collection
            $allKotItems = $allItems;
            
            // Log the final count
            Log::info('WhatsApp KOT Notification Job: Combined items from KOTs, OrderItems, and CartItems', [
                'order_id' => $order->id,
                'final_items_count' => $allKotItems->count(),
                'kot_items_original_count' => $allKotItems->count(),
                'order_items_count' => $orderItemsCount,
                'cart_items_count' => $cartItemsCount,
            ]);
            
            // Final fallback to current KOT items if still empty
            if ($allKotItems->isEmpty()) {
                Log::warning('WhatsApp KOT Notification Job: No items found in any KOT or OrderItems, using current KOT items', [
                    'order_id' => $order->id,
                    'kot_id' => $kot->id,
                ]);
                $allKotItems = $kot->items;
            }
            
            $totalItemsCount = $allKotItems->count();
            
            Log::info('WhatsApp KOT Notification Job: Processing notification', [
                'kot_id' => $kot->id,
                'order_id' => $order->id,
                'order_number' => $order->show_formatted_order_number ?? 'N/A',
                'total_kots' => $order->kot ? $order->kot->count() : 1,
                'kitchen_staff_count' => $kitchenStaff->count(),
                'kitchen_staff_ids' => $kitchenStaff->pluck('id')->toArray(),
                'total_items' => $totalItemsCount,
                'item_ids' => $allKotItems->pluck('id')->toArray(),
            ]);

            // Prepare variables
            $tableNumber = $order->table->table_code ?? 'N/A';
            $orderType = $order->orderType->order_type_name ?? 'N/A';
            
            // Get ALL items from ALL KOTs with menu item names, modifiers (including extra toppings, dips & sauces), and notes
            // Use filter to remove any null/empty items, then map
            $itemsListArray = [];
            foreach ($allKotItems as $item) {
                // Handle both KotItem models and stdClass objects (from OrderItems/CartItems)
                // KotItem is an Eloquent model, so access properties directly
                $menuItem = null;
                $menuItemId = null;
                $quantity = null;
                $note = null;
                $modifierOptions = collect();
                
                // Check if it's a KotItem model (has menuItem relationship)
                if ($item instanceof \App\Models\KotItem) {
                    $menuItem = $item->menuItem;
                    $menuItemId = $item->menu_item_id;
                    $quantity = $item->quantity;
                    $note = $item->note;
                    $modifierOptions = $item->modifierOptions ?? collect();
                } else {
                    // Handle stdClass objects (from OrderItems/CartItems merge)
                    $menuItem = isset($item->menuItem) ? $item->menuItem : null;
                    $menuItemId = isset($item->menu_item_id) ? $item->menu_item_id : null;
                    $quantity = isset($item->quantity) ? $item->quantity : null;
                    $note = isset($item->note) ? $item->note : null;
                    $modifierOptions = isset($item->modifierOptions) ? $item->modifierOptions : collect();
                }
                
                // If menuItem is not loaded, try to load it
                if (!$menuItem && $menuItemId) {
                    $menuItem = \App\Models\MenuItem::find($menuItemId);
                }
                
                // Skip if no menu item
                if (!$menuItem) {
                    Log::warning('WhatsApp KOT Notification Job: Skipping item with no menuItem', [
                        'item_id' => is_object($item) && isset($item->id) ? $item->id : 'unknown',
                        'menu_item_id' => $menuItemId,
                    ]);
                    continue;
                }
                
                $itemName = $menuItem->item_name ?? 'Unknown Item';
                $itemText = $itemName . ' x' . $quantity;
                
                Log::info('WhatsApp KOT Notification Job: Processing item', [
                    'item_id' => is_object($item) && isset($item->id) ? $item->id : 'unknown',
                    'menu_item_id' => $menuItemId,
                    'item_name' => $itemName,
                    'quantity' => $quantity,
                ]);
                
                // Collect all modifiers (including extra toppings, dips & sauces)
                $modifiersList = [];
                if ($modifierOptions && (is_countable($modifierOptions) ? $modifierOptions->count() : 0) > 0) {
                    // Use pivot modifier_option_name if available, otherwise use name from ModifierOption
                    foreach ($modifierOptions as $modifier) {
                        $modifierName = null;
                        // Check if it's a KotItemModifierOption or OrderItemModifierOption pivot
                        if (is_object($modifier) && isset($modifier->pivot)) {
                            $modifierName = $modifier->pivot->modifier_option_name ?? $modifier->name ?? 'Unknown Modifier';
                        } else {
                            $modifierName = is_object($modifier) && isset($modifier->name) ? $modifier->name : 'Unknown Modifier';
                        }
                        
                        // Handle translation arrays
                        if (is_array($modifierName)) {
                            $modifierName = $modifierName[app()->getLocale()] ?? reset($modifierName);
                        }
                        $modifiersList[] = $modifierName;
                    }
                }
                
                // Add modifiers to item text if any
                if (!empty($modifiersList)) {
                    $modifiersText = implode(', ', $modifiersList);
                    $itemText .= ' (' . $modifiersText . ')';
                }
                
                // Add item note if available (might contain extra instructions)
                if (!empty($note)) {
                    $itemText .= ' [Note: ' . $note . ']';
                }
                
                // Add to array instead of returning
                $itemsListArray[] = $itemText;
            }
            
            // Join all items with comma and space
            $itemsList = !empty($itemsListArray) ? implode(', ', $itemsListArray) : 'No items';
            
            Log::info('WhatsApp KOT Notification Job: Items list array built', [
                'items_count' => count($itemsListArray),
                'items_array' => $itemsListArray,
            ]);
            
            if (empty($itemsList)) {
                $itemsList = 'No items';
            }
            
            Log::info('WhatsApp KOT Notification Job: Items list prepared', [
                'kot_id' => $kot->id,
                'order_id' => $order->id,
                'items_count' => $totalItemsCount,
                'items_list_length' => strlen($itemsList),
                'items_list_preview' => substr($itemsList, 0, 200), // First 200 chars for preview
                'items_list' => $itemsList,
            ]);

            $priority = $kot->priority ?? 'Normal';
            if ($order->order_type === 'delivery' || $order->order_type === 'pickup') {
                $priority = 'High';
            }

            // Determine if this is a new KOT or regenerated/updated KOT
            $timeDiff = $kot->created_at->diffInSeconds($kot->updated_at);
            $kotStatus = ($timeDiff <= 5) ? 'New KOT' : 'KOT Updated';

            // Ensure itemsList is a string and not empty
            if (empty($itemsList) || !is_string($itemsList)) {
                $itemsList = 'No items';
            }
            
            // Log the final items list before sending
            Log::info('WhatsApp KOT Notification Job: Final variables before sending', [
                'kot_id' => $kot->id,
                'order_id' => $order->id,
                'items_list_index_4' => $itemsList,
                'items_list_length' => strlen($itemsList),
                'items_list_word_count' => str_word_count($itemsList),
            ]);
            
            $variables = [
                $kot->kot_number ?? 'N/A',                    // [0] - KOT number
                $order->show_formatted_order_number ?? 'N/A', // [1] - Order number
                $tableNumber,                                 // [2] - Table number
                $orderType,                                   // [3] - Order type
                $itemsList,                                   // [4] - Items list (THIS IS THE KEY ONE)
                $kot->created_at->format('d M, Y H:i'),       // [5] - Time
                $priority,                                    // [6] - Priority
                $kotStatus,                                   // [7] - Status: "New KOT" or "KOT Updated"
                $order->id ?? null,                           // [8] - Order ID for button URL
                $order->branch->restaurant->hash ?? null,     // [9] - Restaurant hash for URL (if needed)
            ];
            
            // Log each variable to ensure they're correct
            Log::info('WhatsApp KOT Notification Job: Variables array', [
                'variable_0' => $variables[0] ?? 'N/A',
                'variable_1' => $variables[1] ?? 'N/A',
                'variable_2' => $variables[2] ?? 'N/A',
                'variable_3' => $variables[3] ?? 'N/A',
                'variable_4' => substr($variables[4] ?? 'N/A', 0, 500), // First 500 chars of items list
                'variable_4_full_length' => strlen($variables[4] ?? ''),
                'variable_5' => $variables[5] ?? 'N/A',
                'variable_6' => $variables[6] ?? 'N/A',
                'variable_7' => $variables[7] ?? 'N/A',
            ]);

            // Send notification to all kitchen staff
            foreach ($kitchenStaff as $staff) {
                $phoneNumber = $staff->mobile ?? $staff->phone_number;
                if ($phoneNumber) {
                    // Format phone number with country code
                    $phoneCode = $staff->phone_code ?? '91';
                    $formattedPhone = $phoneCode . $phoneNumber;
                    
                    Log::info('WhatsApp KOT Notification Job: Sending to kitchen staff', [
                        'staff_id' => $staff->id,
                        'staff_name' => $staff->name,
                        'phone' => $formattedPhone,
                    ]);
                    
                    $notificationService->send(
                        $restaurantId,
                        'kitchen_notification',
                        $formattedPhone,
                        $variables,
                        'en',
                        'staff'
                    );
                } else {
                    Log::warning('WhatsApp KOT Notification Job: Kitchen staff has no phone number', [
                        'staff_id' => $staff->id,
                        'staff_name' => $staff->name,
                    ]);
                }
            }
            
            Log::info('WhatsApp KOT Notification Job: Notifications sent successfully', [
                'kot_id' => $kot->id,
                'kitchen_staff_count' => $kitchenStaff->count(),
            ]);

        } catch (\Exception $e) {
            Log::error('WhatsApp KOT Notification Job Error: ' . $e->getMessage(), [
                'kot_id' => $this->kotId,
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}


