@extends('layouts.app')

@section('title', 'Orders')

@push('styles')
<style>
    /* Make Platform dropdown scrollable with max height */
    select[name="store_id"] {
        max-height: 400px;
        overflow-y: auto;
    }

    /* Style optgroups */
    select[name="store_id"] optgroup {
        font-weight: 600;
        color: #374151;
    }

    .dark select[name="store_id"] optgroup {
        color: #9CA3AF;
    }
</style>
@endpush

@section('content')
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Orders Management</h1>
    </div>

    <!-- Status Tabs Navigation -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow mb-4 overflow-hidden">
        <nav class="flex border-b border-gray-200 dark:border-gray-700" aria-label="Order Status Tabs">
            @php
                $tabs = [
                    'all' => 'All',
                    'processing' => 'Processing',
                    'approval' => 'Approval',
                    'printed' => 'Printed',
                    'completed' => 'Completed',
                    'failed' => 'Failed',
                ];
            @endphp

            @foreach($tabs as $status => $label)
                @php
                    $isActive = $currentStatus === $status;
                    $count = $statusCounts[$status] ?? 0;

                    // Build URL with current filters preserved
                    $queryParams = request()->except('status', 'page');
                    $queryParams['status'] = $status;
                    $tabUrl = route('orders.index', $queryParams);

                    // Status-specific styles
                    if ($isActive) {
                        if ($status === 'processing') {
                            $tabClass = 'bg-yellow-50 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-400 border-b-2 border-yellow-500';
                            $badgeClass = 'bg-yellow-600 text-white';
                        } elseif ($status === 'approval') {
                            $tabClass = 'bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-400 border-b-2 border-purple-500';
                            $badgeClass = 'bg-purple-600 text-white';
                        } elseif ($status === 'printed') {
                            $tabClass = 'bg-indigo-50 dark:bg-indigo-900/20 text-indigo-700 dark:text-indigo-400 border-b-2 border-indigo-500';
                            $badgeClass = 'bg-indigo-600 text-white';
                        } elseif ($status === 'completed') {
                            $tabClass = 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border-b-2 border-green-500';
                            $badgeClass = 'bg-green-600 text-white';
                        } elseif ($status === 'failed') {
                            $tabClass = 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 border-b-2 border-red-500';
                            $badgeClass = 'bg-red-600 text-white';
                        } else {
                            $tabClass = 'bg-gray-50 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-b-2 border-gray-500';
                            $badgeClass = 'bg-gray-600 text-white';
                        }
                    } else {
                        $tabClass = 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50';
                        $badgeClass = 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400';
                    }
                @endphp

                <a href="{{ $tabUrl }}"
                   class="relative group flex-1 px-6 py-4 text-center font-medium text-sm transition-all duration-200 {{ $tabClass }}">
                    <span class="flex items-center justify-center gap-2">
                        {{ $label }}
                        <span class="inline-flex items-center justify-center min-w-[24px] h-6 px-2 text-xs font-semibold rounded-full {{ $badgeClass }}">
                            {{ number_format($count) }}
                        </span>
                    </span>
                </a>
            @endforeach
        </nav>
    </div>

    <!-- Filters - Horizontal Bar -->
    <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow mb-6">
        <form method="GET" action="{{ route('orders.index') }}">
            <!-- Preserve current status tab when using filters -->
            <input type="hidden" name="status" value="{{ $currentStatus }}">

            <div class="flex flex-wrap items-end gap-3">
                <!-- Search -->
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-xs font-medium mb-1">Search</label>
                    <input type="text" name="search" value="{{ request('search') }}"
                           placeholder="Order #, email, phone"
                           class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                </div>

                <!-- Platform -->
                <div class="w-44">
                    <label class="block text-xs font-medium mb-1">Platform</label>
                    <select name="store_id" class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                        <option value="">All</option>

                        @php
                            $currentUser = auth()->user();

                            // Get stores based on role
                            if ($currentUser->isAdmin()) {
                                $stores = \App\Models\Store::where('is_active', true)->get();
                            } elseif ($currentUser->isManager()) {
                                $storeIds = $currentUser->getStoreIds();
                                $sellerIds = $currentUser->getManagedSellerIds();
                                $sellerStoreIds = \App\Models\User::whereIn('id', $sellerIds)
                                    ->with('stores')
                                    ->get()
                                    ->pluck('stores')
                                    ->flatten()
                                    ->pluck('id')
                                    ->unique()
                                    ->toArray();
                                $allStoreIds = array_unique(array_merge($storeIds, $sellerStoreIds));
                                $stores = \App\Models\Store::where('is_active', true)->whereIn('id', $allStoreIds)->get();
                            } else {
                                $storeIds = $currentUser->getStoreIds();
                                $stores = \App\Models\Store::where('is_active', true)->whereIn('id', $storeIds)->get();
                            }

                            // Get channels (webhooks) - Admin only
                            $channels = collect();
                            if ($currentUser->isAdmin()) {
                                $channels = \App\Models\WebhookSource::where('is_active', true)->get();
                            }

                            // Get sales pages based on role
                            if ($currentUser->isAdmin()) {
                                $salesPages = \App\Models\SalesPage::all();
                            } elseif ($currentUser->isManager()) {
                                $sellerIds = $currentUser->getManagedSellerIds();
                                $managerSalesPages = $currentUser->salesPages;
                                $sellerSalesPages = \App\Models\SalesPage::whereIn('user_id', $sellerIds)->get();
                                $salesPages = $managerSalesPages->merge($sellerSalesPages);
                            } else {
                                $salesPages = $currentUser->salesPages;
                            }

                            // Get checkout users based on role
                            if ($currentUser->isAdmin()) {
                                $checkoutUsers = \App\Models\User::whereHas('createdOrders', function($q) {
                                    $q->where('is_manual', true);
                                })->get();
                            } elseif ($currentUser->isManager()) {
                                $sellerIds = $currentUser->getManagedSellerIds();
                                $checkoutUsers = \App\Models\User::whereHas('createdOrders', function($q) {
                                    $q->where('is_manual', true);
                                })->whereIn('id', array_merge([$currentUser->id], $sellerIds))->get();
                            } else {
                                $checkoutUsers = collect([$currentUser]);
                            }
                        @endphp

                        <!-- Store -->
                        @if($stores->isNotEmpty())
                        <optgroup label="Store">
                            @foreach($stores as $store)
                                <option value="store_{{ $store->id }}" {{ request('store_id') == 'store_'.$store->id ? 'selected' : '' }}>
                                    {{ $store->name }}
                                </option>
                            @endforeach
                        </optgroup>
                        @endif

                        <!-- Channel (Admin only) -->
                        @if($channels->isNotEmpty())
                        <optgroup label="Channel">
                            @foreach($channels as $channel)
                                <option value="webhook_{{ $channel->id }}" {{ request('store_id') == 'webhook_'.$channel->id ? 'selected' : '' }}>
                                    {{ $channel->name }}
                                </option>
                            @endforeach
                        </optgroup>
                        @endif

                        <!-- Page -->
                        @if($salesPages->isNotEmpty())
                        <optgroup label="Page">
                            @foreach($salesPages as $page)
                                <option value="salespage_{{ $page->id }}" {{ request('store_id') == 'salespage_'.$page->id ? 'selected' : '' }}>
                                    {{ $page->name }}
                                </option>
                            @endforeach
                        </optgroup>
                        @endif

                        <!-- Checkout -->
                        <optgroup label="Checkout">
                            <option value="checkout" {{ request('store_id') == 'checkout' ? 'selected' : '' }}>All Checkout Orders</option>
                            @foreach($checkoutUsers as $user)
                                <option value="checkout_user_{{ $user->id }}" {{ request('store_id') == 'checkout_user_'.$user->id ? 'selected' : '' }}>
                                    {{ $user->name }}
                                </option>
                            @endforeach
                        </optgroup>
                    </select>
                </div>

                <!-- Payment Method -->
                <div class="w-40">
                    <label class="block text-xs font-medium mb-1">Payment</label>
                    <select name="payment_method" class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                        <option value="">All</option>
                        <option value="cod" {{ request('payment_method') == 'cod' ? 'selected' : '' }}>COD</option>
                        <option value="bayarcash-wc" {{ request('payment_method') == 'bayarcash-wc' ? 'selected' : '' }}>Online Banking</option>
                        <option value="duitnowqr-wc" {{ request('payment_method') == 'duitnowqr-wc' ? 'selected' : '' }}>DuitNow QR</option>
                        <option value="linecredit-wc" {{ request('payment_method') == 'linecredit-wc' ? 'selected' : '' }}>Line Credit</option>
                    </select>
                </div>

                <!-- Per Page -->
                <div class="w-24">
                    <label class="block text-xs font-medium mb-1">Show</label>
                    <select name="per_page" class="w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-1.5">
                        <option value="25" {{ request('per_page') == 25 ? 'selected' : '' }}>25</option>
                        <option value="50" {{ request('per_page') == 50 ? 'selected' : '' }}>50</option>
                        <option value="100" {{ request('per_page') == 100 ? 'selected' : '' }}>100</option>
                        <option value="200" {{ request('per_page') == 200 ? 'selected' : '' }}>200</option>
                    </select>
                </div>

                <!-- Action Buttons -->
                <div class="flex gap-2">
                    <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-sm hover:shadow-md transition-all text-sm font-medium whitespace-nowrap">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"/>
                        </svg>
                        Filter
                    </button>
                    <a href="{{ route('orders.index') }}" class="inline-flex items-center gap-1.5 px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-400 dark:hover:bg-gray-700 shadow-sm hover:shadow-md transition-all text-sm font-medium whitespace-nowrap">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                        </svg>
                        Reset
                    </a>
                </div>
            </div>
        </form>
    </div>

    <!-- Bulk Actions Bar -->
    <div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow mb-4">
        <div class="flex items-center gap-4">
            <!-- Select All Checkbox -->
            <div class="flex items-center">
                <input type="checkbox" id="select-all-orders"
                       class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                <label for="select-all-orders" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">
                    Select All
                </label>
            </div>

            <!-- Selected Count -->
            <div id="selected-count" class="text-sm text-gray-600 dark:text-gray-400">
                <span id="selected-count-number">0</span> selected
            </div>

            <!-- Bulk Action Dropdown -->
            <div class="flex-1">
                <select id="bulk-action"
                        class="rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 text-sm py-2 px-3">
                    <option value="">-- Select Bulk Action --</option>
                    <option value="bulk_push_awb">Bulk Push AWB</option>
                    <option value="bulk_download_awb">Bulk Download AWB (Merged PDF)</option>
                    <option value="bulk_download_invoice">Bulk Download Invoice (Merged PDF)</option>
                    <option value="bulk_completed">Bulk Mark as Completed</option>
                </select>
            </div>

            <!-- Submit Button -->
            <button type="button" id="bulk-action-submit"
                    class="inline-flex items-center gap-2 px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 shadow-sm hover:shadow-md transition-all text-sm font-medium whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                </svg>
                Execute Action
            </button>
        </div>
    </div>

    <!-- Orders Display - Table for desktop, Cards for mobile -->
    <div class="bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden">

        <!-- Desktop Table View (hidden on mobile) -->
        <div class="hidden lg:block overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead class="bg-gray-50 dark:bg-gray-700">
                    <tr>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider w-10">
                            <input type="checkbox" id="select-all-table"
                                   class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500">
                        </th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">ID</th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">Order</th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">Customer Info</th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">Products</th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">Payment Info</th>
                        <th class="px-2 py-2 text-left text-xs font-medium uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @forelse($orders as $order)
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <!-- Checkbox Column -->
                        <td class="px-2 py-2 text-sm align-top">
                            <input type="checkbox" class="order-checkbox w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
                                   data-order-id="{{ $order->id }}"
                                   data-order-number="{{ $order->order_number }}"
                                   data-tracking="{{ $order->tracking_number }}"
                                   data-status="{{ $order->status }}">
                        </td>
                        <!-- ID Column -->
                        <td class="px-2 py-2 text-sm align-top">
                            <a href="{{ route('orders.show', $order) }}" class="font-mono text-xs text-blue-600 dark:text-blue-400 hover:underline" title="{{ $order->global_order_id }}">
                                {{ Str::limit($order->global_order_id, 12) }}
                            </a>
                        </td>

                        <!-- Order Column -->
                        <td class="px-2 py-2 text-sm align-top">
                            <div class="space-y-0.5">
                                <!-- Order Number -->
                                <div class="font-semibold text-xs">#{{ $order->order_number }}</div>

                                <!-- Store/Source Info -->
                                @if($order->is_manual)
                                    @if($order->creator)
                                        <div class="text-xs text-gray-600 dark:text-gray-400" title="{{ $order->creator->name }}">
                                            {{ Str::limit($order->creator->name, 20) }}
                                        </div>
                                        @if(Str::startsWith($order->order_number, 'CK-'))
                                            @php
                                                // Extract shortname from order number (CK-XXX-nnn → XXX)
                                                $shortName = $order->creator->short_name ?? (explode('-', $order->order_number)[1] ?? 'N/A');
                                            @endphp
                                            <div class="text-xs text-purple-500 dark:text-purple-400">
                                                {{ $shortName }} • Checkout
                                            </div>
                                        @elseif(Str::startsWith($order->order_number, 'SP-'))
                                            @php
                                                // Extract shortname from order number (SP-XXX-nnn → XXX)
                                                $shortName = $order->creator->short_name ?? (explode('-', $order->order_number)[1] ?? 'N/A');
                                            @endphp
                                            <div class="text-xs text-green-500 dark:text-green-400">
                                                {{ $shortName }} • Sales-pages
                                            </div>
                                        @else
                                            <div class="text-xs text-gray-500 dark:text-gray-400">
                                                Manual Order
                                            </div>
                                        @endif
                                    @else
                                        <div class="text-xs text-gray-600 dark:text-gray-400">
                                            Manual Order
                                        </div>
                                    @endif
                                @elseif($order->store)
                                    <div class="text-xs text-gray-600 dark:text-gray-400" title="{{ $order->store->name }}">
                                        {{ Str::limit($order->store->name, 20) }}
                                    </div>
                                    <div class="text-xs text-gray-500 dark:text-gray-500">
                                        {{ $order->store->store_prefix }} • WooCommerce
                                    </div>
                                @elseif($order->webhookSource)
                                    <div class="text-xs text-gray-600 dark:text-gray-400" title="{{ $order->webhookSource->name }}">
                                        {{ Str::limit($order->webhookSource->name, 20) }}
                                    </div>
                                    <div class="text-xs text-blue-500 dark:text-blue-400">
                                        {{ ucfirst($order->webhookSource->type) }} Webhook
                                    </div>
                                @endif

                                @if($order->woo_order_id)
                                    <div class="text-gray-500 dark:text-gray-400 text-xs">WOO: {{ $order->woo_order_id }}</div>
                                @endif

                                <!-- Status Badge -->
                                @php
                                    $statusColors = [
                                        'processing' => 'yellow',
                                        'approval' => 'purple',
                                        'printed' => 'indigo',
                                        'completed' => 'green',
                                        'on-hold' => 'orange',
                                        'cancelled' => 'red',
                                        'refunded' => 'blue',
                                        'failed' => 'red'
                                    ];
                                    $color = $statusColors[$order->status] ?? 'gray';
                                @endphp
                                <div>
                                    <span class="px-1.5 py-0.5 inline-flex text-xs font-medium rounded
                                        bg-{{ $color }}-100 text-{{ $color }}-800
                                        dark:bg-{{ $color }}-900 dark:text-{{ $color }}-200">
                                        {{ ucfirst($order->status) }}
                                    </span>
                                </div>
                            </div>
                        </td>

                        <!-- Customer Info Column -->
                        <td class="px-2 py-2 text-xs align-top" style="min-width: 200px; max-width: 250px;">
                            <div class="space-y-0.5">
                                <!-- Name -->
                                <div class="font-semibold text-gray-900 dark:text-white leading-tight uppercase">
                                    @php
                                        // Support both WooCommerce format (first_name/last_name) and sales page format (name)
                                        $customerName = $order->billing['name'] ?? trim(($order->billing['first_name'] ?? '') . ' ' . ($order->billing['last_name'] ?? ''));
                                    @endphp
                                    {{ $customerName }}
                                </div>
                                <!-- Full Address with word wrap -->
                                <div class="text-gray-600 dark:text-gray-400 leading-tight uppercase" style="word-wrap: break-word; overflow-wrap: break-word;">
                                    @php
                                        // Support both WooCommerce format (address_1) and sales page format (address)
                                        $address1 = $order->shipping['address_1'] ?? $order->shipping['address'] ?? $order->billing['address_1'] ?? $order->billing['address'] ?? '';
                                        $address2 = $order->shipping['address_2'] ?? $order->billing['address_2'] ?? '';
                                    @endphp
                                    {{ $address1 }}@if($address2), {{ $address2 }}@endif
                                </div>
                                <!-- City, State, Postcode -->
                                <div class="text-gray-600 dark:text-gray-400 leading-tight uppercase">
                                    {{ ($order->shipping['postcode'] ?? $order->billing['postcode'] ?? '') }} {{ ($order->shipping['city'] ?? $order->billing['city'] ?? '') }}, {{ ($order->shipping['state'] ?? $order->billing['state'] ?? '') }}
                                </div>
                                <!-- Email -->
                                <div class="text-gray-600 dark:text-gray-400 leading-tight truncate" title="{{ $order->billing['email'] ?? '' }}">
                                    {{ $order->billing['email'] ?? '-' }}
                                </div>
                                <!-- Phone with WhatsApp -->
                                @if(isset($order->billing['phone']))
                                <div class="flex items-center gap-1">
                                    <span class="text-gray-600 dark:text-gray-400">
                                        {{ App\Helpers\PhoneHelper::display($order->billing['phone']) }}
                                    </span>
                                    <a href="{{ App\Helpers\PhoneHelper::getWhatsAppUrl($order->billing['phone']) }}"
                                       target="_blank"
                                       class="inline-flex items-center px-1 py-0.5 bg-green-500 hover:bg-green-600 text-white rounded"
                                       title="WhatsApp">
                                        <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                                            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.890-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                                        </svg>
                                    </a>
                                </div>
                                @endif
                            </div>
                        </td>

                        <!-- Products Column -->
                        <td class="px-2 py-2 text-xs align-top" style="min-width: 180px;">
                            @php
                                $expandedItems = $order->getExpandedLineItems();
                            @endphp
                            @if($expandedItems)
                                <div class="space-y-1">
                                    @foreach($expandedItems as $index => $expandedItem)
                                        @if($index < 3)
                                        @php
                                            $item = $expandedItem['item'];
                                            $isBundle = $expandedItem['is_bundle'];
                                            $bundleDetails = $expandedItem['bundle_details'];
                                        @endphp
                                        <div>
                                            <div class="text-gray-700 dark:text-gray-300 font-medium">
                                                <span class="font-bold">{{ $item['quantity'] ?? 1 }}x {{ Str::limit($item['name'] ?? 'Item', 30) }}</span>
                                            </div>
                                            @if($isBundle && $bundleDetails)
                                                @foreach($bundleDetails['items'] as $bundleItem)
                                                    <div class="ml-2 text-gray-600 dark:text-gray-400 text-xs">
                                                        - {{ $bundleItem['name'] ?? $bundleItem['sku'] }} x{{ $bundleItem['quantity'] }}
                                                    </div>
                                                @endforeach
                                            @endif
                                        </div>
                                        @endif
                                    @endforeach
                                    @if(count($expandedItems) > 3)
                                        <div class="text-gray-500 dark:text-gray-400 italic text-xs">
                                            +{{ count($expandedItems) - 3 }} more
                                        </div>
                                    @endif
                                </div>
                            @else
                                <span class="text-gray-400">-</span>
                            @endif
                        </td>

                        <!-- Payment Info Column -->
                        <td class="px-2 py-2 text-xs align-top">
                            <div class="space-y-0.5">
                                <!-- Payment Status Badge -->
                                @php
                                    $paymentColors = [
                                        'cod' => 'amber',
                                        'bacs' => 'blue',
                                        'stripe' => 'indigo',
                                        'paypal' => 'yellow',
                                        'bayarcash-wc' => 'green',
                                        'duitnowqr-wc' => 'sky',
                                        'linecredit-wc' => 'purple'
                                    ];
                                    $pColor = $paymentColors[$order->payment_method] ?? 'gray';
                                @endphp
                                <div>
                                    <span class="px-1.5 py-0.5 inline-flex text-xs font-medium rounded
                                        bg-{{ $pColor }}-100 text-{{ $pColor }}-800
                                        dark:bg-{{ $pColor }}-900 dark:text-{{ $pColor }}-200">
                                        {{ $order->payment_method_title }}
                                    </span>
                                </div>
                                <!-- Total Amount -->
                                <div class="font-bold text-gray-900 dark:text-white text-sm">
                                    {{ $order->formatCurrency() }}
                                </div>
                                <!-- Payment Date & Time -->
                                <div class="text-gray-500 dark:text-gray-400">
                                    @if($order->date_created)
                                        <div>{{ $order->date_created->format('M d, Y') }}</div>
                                        <div class="text-xs">{{ $order->date_created->format('H:i:s') }}</div>
                                    @else
                                        N/A
                                    @endif
                                </div>
                                <!-- Payment Status Text -->
                                @php
                                    // COD = Unpaid unless status is completed
                                    // Online Banking = Paid if status is processing or completed
                                    $isPaid = $order->isCOD()
                                        ? ($order->status === 'completed')
                                        : in_array($order->status, ['processing', 'completed']);
                                @endphp
                                <div class="text-gray-600 dark:text-gray-400">
                                    Status: <span class="font-medium {{ $isPaid ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400' }}">
                                        {{ $isPaid ? 'Paid' : 'Unpaid' }}
                                    </span>
                                </div>
                            </div>
                        </td>

                        <!-- Actions Column -->
                        <td class="px-2 py-2 text-xs align-top">
                            <div class="space-y-1.5">
                                <!-- Edit -->
                                <div>
                                    <a href="{{ route('orders.edit', $order) }}"
                                       class="inline-flex items-center gap-1 px-2 py-1 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 rounded transition-colors text-sm font-medium">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                                        </svg>
                                        Edit
                                    </a>
                                </div>

                                <!-- Delete -->
                                <div>
                                    <form action="{{ route('orders.destroy', $order) }}" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete Order #{{ $order->order_number }}? This action cannot be undone.');">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit"
                                                class="inline-flex items-center gap-1 px-2 py-1 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors text-sm font-medium">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                                            </svg>
                                            Delete
                                        </button>
                                    </form>
                                </div>

                                <!-- Invoice -->
                                <div class="flex items-center gap-1">
                                    <a href="{{ route('invoices.show', $order) }}"
                                       target="_blank"
                                       class="inline-flex items-center gap-1 px-2 py-1 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors text-sm font-medium">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                                        </svg>
                                        Invoice
                                    </a>
                                    <a href="{{ route('invoices.download', $order) }}"
                                       class="inline-flex items-center p-1 text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20 rounded transition-colors"
                                       title="Download">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                                        </svg>
                                    </a>
                                </div>

                                <!-- AWB Actions -->
                                @if($order->tracking_number)
                                    <div class="flex items-center gap-1">
                                        <a href="{{ route('orders.awb.print', $order) }}"
                                           target="_blank"
                                           class="inline-flex items-center gap-1 px-2 py-1 text-purple-600 dark:text-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded transition-colors text-sm font-medium">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                                            </svg>
                                            AWB
                                        </a>
                                        <a href="{{ route('orders.awb.download', $order) }}"
                                           class="inline-flex items-center p-1 text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20 rounded transition-colors"
                                           title="Download">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                                            </svg>
                                        </a>
                                    </div>

                                    <!-- Tracking Number (Bottom) -->
                                    <div class="pt-1 border-t border-gray-200 dark:border-gray-600">
                                        <a href="https://tracking.pos.com.my/tracking/{{ $order->tracking_number }}"
                                           target="_blank"
                                           class="inline-flex items-center gap-1 px-2 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-md shadow-sm hover:shadow transition-all text-xs font-medium font-mono">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                                            </svg>
                                            {{ $order->tracking_number }}
                                        </a>
                                    </div>

                                    <!-- WhatsApp Notification -->
                                    <div class="pt-1">
                                        @if($order->whatsapp_sent_at)
                                            <div class="inline-flex items-center gap-1 px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded text-xs">
                                                <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                                                    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
                                                </svg>
                                                Tracking Sent
                                            </div>
                                        @else
                                            <form action="{{ route('orders.send-whatsapp', $order) }}" method="POST" class="inline" onsubmit="return confirm('Send AWB tracking to customer via WhatsApp?');">
                                                @csrf
                                                <button type="submit"
                                                        class="inline-flex items-center gap-1 px-2 py-1 bg-green-600 hover:bg-green-700 text-white rounded-md shadow-sm hover:shadow transition-all text-xs font-medium">
                                                    <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                                                        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.890-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                                                    </svg>
                                                    Send Tracking
                                                </button>
                                            </form>
                                        @endif
                                    </div>

                                    <!-- Mark as Completed Button -->
                                    <div class="pt-1">
                                        @if($order->status !== 'completed')
                                            <form action="{{ route('orders.mark-completed', $order) }}" method="POST" class="inline" onsubmit="return confirm('Mark order #{{ $order->order_number }} as completed? This will update the status in WooCommerce/webhook source if applicable.');">
                                                @csrf
                                                <button type="submit"
                                                        class="inline-flex items-center gap-1 px-2 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-md shadow-sm hover:shadow transition-all text-xs font-medium">
                                                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                                    </svg>
                                                    Mark to Complete
                                                </button>
                                            </form>
                                        @else
                                            <div class="inline-flex items-center gap-1 px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded text-xs">
                                                <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                                                    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
                                                </svg>
                                                Completed
                                            </div>
                                        @endif
                                    </div>
                                @else
                                    <!-- Generate AWB Button -->
                                    <div>
                                        <form action="{{ route('orders.generate-awb', $order) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit"
                                                    class="inline-flex items-center gap-1 px-2 py-1 text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20 rounded transition-colors text-sm font-medium">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                                                </svg>
                                                Push AWB
                                            </button>
                                        </form>
                                    </div>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="7" class="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
                            No orders found.
                            @if(request()->hasAny(['search', 'status', 'payment_method', 'store_id']))
                                <a href="{{ route('orders.index') }}" class="text-blue-600 hover:text-blue-800">Clear filters</a>
                            @endif
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Mobile Card View (visible on mobile and tablet) -->
        <div class="lg:hidden">
            @forelse($orders as $order)
            <div class="border-b border-gray-200 dark:border-gray-700 p-4 hover:bg-gray-50 dark:hover:bg-gray-700">
                <div class="flex justify-between items-start mb-3">
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center space-x-2 mb-1">
                            <div class="font-medium text-blue-600 dark:text-blue-400 text-sm">
                                {{ $order->global_order_id }}
                            </div>
                            @php
                                $statusColors = [
                                    'processing' => 'yellow',
                                    'approval' => 'purple',
                                    'printed' => 'indigo',
                                    'completed' => 'green',
                                    'on-hold' => 'orange',
                                    'cancelled' => 'red',
                                    'refunded' => 'blue',
                                    'failed' => 'red'
                                ];
                                $color = $statusColors[$order->status] ?? 'gray';
                            @endphp
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                bg-{{ $color }}-100 text-{{ $color }}-800
                                dark:bg-{{ $color }}-900 dark:text-{{ $color }}-200">
                                {{ ucfirst($order->status) }}
                            </span>
                        </div>
                        <div class="text-sm text-gray-900 dark:text-gray-100 font-medium">
                            Order #{{ $order->order_number }}
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                            @if($order->is_manual)
                                @if($order->creator)
                                    {{ $order->creator->name }} •
                                    @if(Str::startsWith($order->order_number, 'CK-'))
                                        @php
                                            // Extract shortname from order number (CK-XXX-nnn → XXX)
                                            $shortName = $order->creator->short_name ?? (explode('-', $order->order_number)[1] ?? 'N/A');
                                        @endphp
                                        {{ $shortName }} • Checkout
                                    @elseif(Str::startsWith($order->order_number, 'SP-'))
                                        @php
                                            // Extract shortname from order number (SP-XXX-nnn → XXX)
                                            $shortName = $order->creator->short_name ?? (explode('-', $order->order_number)[1] ?? 'N/A');
                                        @endphp
                                        {{ $shortName }} • Sales-pages
                                    @else
                                        Manual Order
                                    @endif
                                @else
                                    Manual Order
                                @endif
                            @elseif($order->store)
                                {{ $order->store->name }} • WOO ID: {{ $order->woo_order_id }}
                            @elseif($order->webhookSource)
                                {{ $order->webhookSource->name }} • Webhook Order
                            @else
                                Unknown Source
                            @endif
                        </div>
                    </div>
                    <div class="text-right">
                        <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {{ $order->formatCurrency() }}
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                            @if($order->date_created)
                                {{ $order->date_created->format('M d, Y') }}
                                <div class="text-[10px]">{{ $order->date_created->format('H:i:s') }}</div>
                            @else
                                N/A
                            @endif
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 gap-2 mb-3">
                    <div>
                        <div class="text-sm text-gray-900 dark:text-gray-100 uppercase">
                            @php
                                // Support both WooCommerce format (first_name/last_name) and sales page format (name)
                                $customerName = $order->billing['name'] ?? trim(($order->billing['first_name'] ?? '') . ' ' . ($order->billing['last_name'] ?? ''));
                            @endphp
                            {{ $customerName }}
                        </div>
                        <div class="text-xs text-gray-500 dark:text-gray-400">
                            {{ $order->billing['email'] ?? '' }}
                        </div>
                        @if(isset($order->billing['phone']))
                            <div class="flex items-center space-x-1 text-xs">
                                <span class="text-gray-500 dark:text-gray-400">
                                    {{ App\Helpers\PhoneHelper::display($order->billing['phone']) }}
                                </span>
                                <a href="{{ App\Helpers\PhoneHelper::getWhatsAppUrl($order->billing['phone']) }}"
                                   target="_blank"
                                   class="inline-flex items-center px-1.5 py-0.5 bg-green-500 hover:bg-green-600 text-white rounded text-xs"
                                   title="WhatsApp">
                                    <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                                        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.890-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                                    </svg>
                                </a>
                            </div>
                        @endif
                    </div>
                </div>

                <div class="flex justify-between items-center">
                    <div class="flex items-center space-x-2">
                        @php
                            $paymentColors = [
                                'cod' => 'amber',
                                'bacs' => 'blue',
                                'stripe' => 'indigo',
                                'paypal' => 'yellow',
                                'bayarcash-wc' => 'green',
                                'duitnowqr-wc' => 'sky',
                                'linecredit-wc' => 'purple'
                            ];
                            $pColor = $paymentColors[$order->payment_method] ?? 'gray';
                        @endphp
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                            bg-{{ $pColor }}-100 text-{{ $pColor }}-800
                            dark:bg-{{ $pColor }}-900 dark:text-{{ $pColor }}-200">
                            {{ $order->payment_method_title }}
                        </span>
                        @if($order->isLocalPickup())
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
                                Pickup
                            </span>
                        @endif
                    </div>
                    <div class="flex space-x-3">
                        <a href="{{ route('invoices.download', $order) }}"
                           class="text-green-600 dark:text-green-400 hover:text-green-900 text-sm font-medium">
                            PDF
                        </a>
                        <a href="{{ route('orders.edit', $order) }}"
                           class="text-indigo-600 dark:text-indigo-400 hover:text-indigo-900 text-sm font-medium">
                            Edit
                        </a>
                        <a href="{{ route('orders.show', $order) }}"
                           class="text-gray-600 dark:text-gray-400 hover:text-gray-900 text-sm font-medium">
                            View
                        </a>
                        <form action="{{ route('orders.destroy', $order) }}" method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete Order #{{ $order->order_number }}?');">
                            @csrf
                            @method('DELETE')
                            <button type="submit" class="text-red-600 dark:text-red-400 hover:text-red-900 text-sm font-medium">
                                Delete
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            @empty
            <div class="p-8 text-center text-gray-500 dark:text-gray-400">
                No orders found.
                @if(request()->hasAny(['search', 'status', 'payment_method', 'store_id']))
                    <a href="{{ route('orders.index') }}" class="text-blue-600 hover:text-blue-800">Clear filters</a>
                @endif
            </div>
            @endforelse
        </div>

        <!-- Pagination -->
        @if($orders->hasPages())
        <div class="bg-white dark:bg-gray-800 px-4 py-3 border-t border-gray-200 dark:border-gray-700 sm:px-6">
            {{ $orders->withQueryString()->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Confirmation Modal -->
<div id="bulk-action-modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white dark:bg-gray-800">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-medium leading-6 text-gray-900 dark:text-white" id="modal-title">
                    Confirm Bulk Action
                </h3>
                <button type="button" onclick="closeBulkModal()" class="text-gray-400 hover:text-gray-500">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <div class="mt-2 px-7 py-3">
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-4" id="modal-description">
                    You are about to perform this action on the following orders:
                </p>

                <div class="bg-gray-50 dark:bg-gray-700 rounded p-4 max-h-60 overflow-y-auto mb-4">
                    <ul id="selected-orders-list" class="text-sm text-gray-700 dark:text-gray-300 space-y-1">
                        <!-- Orders will be populated here by JavaScript -->
                    </ul>
                </div>

                <div id="error-message" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                    <!-- Error messages will appear here -->
                </div>
            </div>

            <div class="flex items-center justify-end px-4 py-3 gap-3">
                <button type="button" onclick="closeBulkModal()"
                        class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 transition-colors">
                    Cancel
                </button>
                <button type="button" id="confirm-bulk-action"
                        class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
                    Confirm
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loading-overlay" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 z-50 flex items-center justify-center">
    <div class="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-sm w-full mx-4">
        <div class="flex items-center justify-center mb-4">
            <svg class="animate-spin h-10 w-10 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
        </div>
        <p class="text-center text-gray-700 dark:text-gray-300" id="loading-message">Processing bulk action...</p>
        <p class="text-center text-sm text-gray-500 dark:text-gray-400 mt-2">Please wait, this may take a moment.</p>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllTop = document.getElementById('select-all-orders');
    const selectAllTable = document.getElementById('select-all-table');
    const orderCheckboxes = document.querySelectorAll('.order-checkbox');
    const selectedCountEl = document.getElementById('selected-count-number');
    const bulkActionSelect = document.getElementById('bulk-action');
    const bulkActionSubmit = document.getElementById('bulk-action-submit');
    const MAX_ORDERS = 50;

    // Sync both "Select All" checkboxes
    function syncSelectAll() {
        const allChecked = Array.from(orderCheckboxes).every(cb => cb.checked);
        const someChecked = Array.from(orderCheckboxes).some(cb => cb.checked);

        selectAllTop.checked = allChecked;
        selectAllTable.checked = allChecked;
        selectAllTop.indeterminate = someChecked && !allChecked;
        selectAllTable.indeterminate = someChecked && !allChecked;
    }

    // Update selected count
    function updateSelectedCount() {
        const count = document.querySelectorAll('.order-checkbox:checked').length;
        selectedCountEl.textContent = count;
        syncSelectAll();
    }

    // Select/Deselect all
    function toggleAllCheckboxes(checked) {
        orderCheckboxes.forEach(cb => {
            cb.checked = checked;
        });
        updateSelectedCount();
    }

    selectAllTop.addEventListener('change', function() {
        toggleAllCheckboxes(this.checked);
    });

    selectAllTable.addEventListener('change', function() {
        toggleAllCheckboxes(this.checked);
    });

    orderCheckboxes.forEach(cb => {
        cb.addEventListener('change', updateSelectedCount);
    });

    // Bulk action submit
    bulkActionSubmit.addEventListener('click', function() {
        const selectedOrders = Array.from(document.querySelectorAll('.order-checkbox:checked'));
        const action = bulkActionSelect.value;

        // Validation
        if (!action) {
            alert('Please select a bulk action.');
            return;
        }

        if (selectedOrders.length === 0) {
            alert('Please select at least one order.');
            return;
        }

        if (selectedOrders.length > MAX_ORDERS) {
            alert(`You can only process up to ${MAX_ORDERS} orders at a time. You have selected ${selectedOrders.length} orders.`);
            return;
        }

        // Additional validation for specific actions
        if (action === 'bulk_push_awb') {
            const ordersWithTracking = selectedOrders.filter(cb => cb.dataset.tracking);
            if (ordersWithTracking.length > 0) {
                const orderNumbers = ordersWithTracking.map(cb => cb.dataset.orderNumber).join(', ');
                alert(`The following orders already have tracking numbers and will be skipped: ${orderNumbers}`);
            }
        }

        if (action === 'bulk_download_awb') {
            const ordersWithoutTracking = selectedOrders.filter(cb => !cb.dataset.tracking);
            if (ordersWithoutTracking.length > 0) {
                const orderNumbers = ordersWithoutTracking.map(cb => cb.dataset.orderNumber).join(', ');
                alert(`The following orders don't have tracking numbers and cannot be included: ${orderNumbers}`);
                return;
            }
        }

        // Show confirmation modal
        showBulkModal(action, selectedOrders);
    });
});

function showBulkModal(action, selectedOrders) {
    const modal = document.getElementById('bulk-action-modal');
    const modalTitle = document.getElementById('modal-title');
    const modalDescription = document.getElementById('modal-description');
    const ordersList = document.getElementById('selected-orders-list');

    // Set title and description based on action
    const actionTitles = {
        'bulk_push_awb': 'Push AWB for Multiple Orders',
        'bulk_download_awb': 'Download Merged AWB PDF',
        'bulk_download_invoice': 'Download Merged Invoice PDF',
        'bulk_completed': 'Mark Multiple Orders as Completed'
    };

    const actionDescriptions = {
        'bulk_push_awb': 'Generate AWB tracking numbers for the following orders:',
        'bulk_download_awb': 'Download a single PDF containing all AWB labels for:',
        'bulk_download_invoice': 'Download a single PDF containing all invoices for:',
        'bulk_completed': 'Mark the following orders as completed:'
    };

    modalTitle.textContent = actionTitles[action] || 'Confirm Bulk Action';
    modalDescription.textContent = actionDescriptions[action] || 'You are about to perform this action on the following orders:';

    // Populate orders list
    ordersList.innerHTML = '';
    selectedOrders.forEach(cb => {
        const li = document.createElement('li');
        li.innerHTML = `<strong>${cb.dataset.orderNumber}</strong> - ${cb.dataset.status}` +
                      (cb.dataset.tracking ? ` (Tracking: ${cb.dataset.tracking})` : '');
        ordersList.appendChild(li);
    });

    // Show modal
    modal.classList.remove('hidden');

    // Set confirm button action
    const confirmBtn = document.getElementById('confirm-bulk-action');
    confirmBtn.onclick = function() {
        executeBulkAction(action, selectedOrders);
    };
}

function closeBulkModal() {
    const modal = document.getElementById('bulk-action-modal');
    modal.classList.add('hidden');

    // Clear error message
    const errorDiv = document.getElementById('error-message');
    errorDiv.classList.add('hidden');
    errorDiv.innerHTML = '';
}

function executeBulkAction(action, selectedOrders) {
    // Close modal
    closeBulkModal();

    // Show loading overlay
    const loadingOverlay = document.getElementById('loading-overlay');
    const loadingMessage = document.getElementById('loading-message');

    const loadingMessages = {
        'bulk_push_awb': 'Generating AWB tracking numbers...',
        'bulk_download_awb': 'Merging AWB PDFs...',
        'bulk_download_invoice': 'Merging Invoice PDFs...',
        'bulk_completed': 'Marking orders as completed...'
    };

    loadingMessage.textContent = loadingMessages[action] || 'Processing bulk action...';
    loadingOverlay.classList.remove('hidden');

    // Prepare order IDs
    const orderIds = selectedOrders.map(cb => cb.dataset.orderId);

    // Create form and submit
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = `/orders/bulk-action/${action}`;

    // Add CSRF token
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = '_token';
    csrfInput.value = csrfToken;
    form.appendChild(csrfInput);

    // Add order IDs
    orderIds.forEach(id => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'order_ids[]';
        input.value = id;
        form.appendChild(input);
    });

    // For download actions, we need to handle differently
    if (action === 'bulk_download_awb' || action === 'bulk_download_invoice') {
        form.target = '_blank';
    }

    document.body.appendChild(form);
    form.submit();

    // Hide loading overlay after a delay (for non-download actions)
    if (action !== 'bulk_download_awb' && action !== 'bulk_download_invoice') {
        // The page will reload, so no need to hide
    } else {
        setTimeout(() => {
            loadingOverlay.classList.add('hidden');
        }, 2000);
    }
}
</script>

@endsection