@php
    use App\Modules\Inventory\Stock\Support\DecimalQuantity;
    use App\Modules\Sales\Support\SalesOrderLifecycleStatus;

    $breadcrumbs = [
        ['label' => __('common.home'), 'url' => route('dashboard.index')],
        ['label' => __('sales.breadcrumb_root')],
        ['label' => __('sales.orders.title')],
    ];
    $showBulk = in_array($viewFocus, ['allocation', 'fulfillment'], true);
    $emptyTitle = request()->hasAny(['status', 'sort', 'dir'])
        ? __('common.no_matching_records')
        : __('operational_ui.index.empty_default');
@endphp

<x-ui.layout.page
    :title="__('sales.orders.title')"
    :subtitle="__('sales.orders.subtitle')"
    page-icon="fe fe-shopping-cart"
    :breadcrumbs="$breadcrumbs"
>
    @if ($showBulk)
        <form id="so-bulk-form" method="post" class="visually-hidden erp-bulk-form" autocomplete="off">
            @csrf
            <input type="hidden" name="confirmation" id="so-bulk-confirm" value="" required>
        </form>
    @endif

    <x-ui.operational.index-shell>
        <x-slot:toolbar>
            <x-ui.operational.action-bar>
                <x-slot:filters>
                    <x-ui.operational.index-filters
                        :hidden="['view' => $viewFocus]"
                        :fields="[
                            [
                                'type' => 'select',
                                'name' => 'status',
                                'label' => __('sales.orders.filters.status'),
                                'options' => collect($statusChoices)->mapWithKeys(fn ($st) => [$st->value => $st->value])->prepend(__('sales.orders.filters.all_statuses'), '')->all(),
                                'width' => '12rem',
                            ],
                        ]"
                    />
                </x-slot:filters>
                <x-slot:secondary>
                    @if ($showBulk)
                        <span class="small text-muted">{{ __('operational_ui.speed.bulk.toolbar_hint') }}</span>
                    @endif
                </x-slot:secondary>
                <x-slot:primary>
                    @if ($showBulk && Gate::check('viewAny', App\Modules\Sales\Models\SalesOrder::class))
                        <button type="button" class="btn btn-sm btn-outline-secondary" data-erp-select-page="#so-bulk-form">
                            {{ __('procurement.bulk.select_all') }}
                        </button>
                        @if ($viewFocus === 'allocation')
                            <button
                                type="submit"
                                form="so-bulk-form"
                                formaction="{{ route('sales.orders.bulk.allocate-max') }}"
                                class="btn btn-sm btn-primary"
                                data-bulk-confirm="{{ __('sales.bulk.confirm_allocate', ['count' => '__COUNT__']) }}"
                                data-bulk-confirm-value="ALLOCATE_MAX"
                            >{{ __('sales.bulk.allocate_max') }}</button>
                        @else
                            <button
                                type="submit"
                                form="so-bulk-form"
                                formaction="{{ route('sales.orders.bulk.fulfill-max') }}"
                                class="btn btn-sm btn-primary"
                                data-bulk-confirm="{{ __('sales.bulk.confirm_fulfill', ['count' => '__COUNT__']) }}"
                                data-bulk-confirm-value="FULFILL_MAX"
                            >{{ __('sales.bulk.fulfill_max') }}</button>
                        @endif
                    @endif
                </x-slot:primary>
            </x-ui.operational.action-bar>
        </x-slot:toolbar>

        @if ($viewFocus === 'allocation')
            <div class="alert alert-secondary py-2 small mb-3">{{ __('sales.orders.view_badge.allocation') }}</div>
        @elseif ($viewFocus === 'fulfillment')
            <div class="alert alert-secondary py-2 small mb-3">{{ __('sales.orders.view_badge.fulfillment') }}</div>
        @endif

        @php
            $cols = $showBulk
                ? [
                    ['label' => '', 'align' => 'center'],
                    ['label' => __('sales.orders.columns.number'), 'sort' => 'order_number'],
                    ['label' => __('sales.orders.columns.status'), 'sort' => 'status'],
                    ['label' => __('sales.orders.columns.ordered')],
                    ['label' => __('sales.orders.columns.reserved')],
                    ['label' => __('sales.orders.columns.fulfilled')],
                    ['label' => __('sales.orders.columns.remaining')],
                    ['label' => __('sales.orders.columns.created'), 'sort' => 'created_at'],
                    ['label' => __('common.view'), 'align' => 'end'],
                ]
                : [
                    ['label' => __('sales.orders.columns.number'), 'sort' => 'order_number'],
                    ['label' => __('sales.orders.columns.status'), 'sort' => 'status'],
                    ['label' => __('sales.orders.columns.ordered')],
                    ['label' => __('sales.orders.columns.reserved')],
                    ['label' => __('sales.orders.columns.fulfilled')],
                    ['label' => __('sales.orders.columns.remaining')],
                    ['label' => __('sales.orders.columns.created'), 'sort' => 'created_at'],
                    ['label' => __('common.view'), 'align' => 'end'],
                ];
        @endphp

        <x-ui.table.table :columns="$cols">
            @forelse ($orders as $order)
                @php
                    $st = SalesOrderLifecycleStatus::tryFrom((string) $order->status);
                    $variant = match ($st) {
                        SalesOrderLifecycleStatus::Fulfilled => 'success',
                        SalesOrderLifecycleStatus::Cancelled => 'neutral',
                        SalesOrderLifecycleStatus::Draft => 'muted',
                        SalesOrderLifecycleStatus::Confirmed,
                        SalesOrderLifecycleStatus::Allocated => 'info',
                        SalesOrderLifecycleStatus::PartiallyAllocated,
                        SalesOrderLifecycleStatus::PartiallyFulfilled => 'warning',
                        default => 'neutral',
                    };
                    $ord = trim((string) ($order->ordered_qty_sum ?? '0'));
                    $res = trim((string) ($order->reserved_qty_sum ?? '0'));
                    $ful = trim((string) ($order->fulfilled_qty_sum ?? '0'));
                    $remaining = DecimalQuantity::add($ord, DecimalQuantity::negate(DecimalQuantity::add($res, $ful)));
                @endphp
                <x-ui.table.row>
                    @if ($showBulk)
                        <td class="text-center">
                            @if ($viewFocus === 'allocation' && Gate::allows('allocate', $order))
                                <input class="form-check-input erp-bulk-row" type="checkbox" form="so-bulk-form" name="order_ids[]" value="{{ $order->id }}">
                            @elseif ($viewFocus === 'fulfillment' && Gate::allows('fulfill', $order))
                                <input class="form-check-input erp-bulk-row" type="checkbox" form="so-bulk-form" name="order_ids[]" value="{{ $order->id }}">
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                    @endif
                    <td><strong>{{ $order->displayOrderNumber() }}</strong></td>
                    <td>
                        <x-ui.operational.status-badge :label="$order->status" :variant="$variant" />
                    </td>
                    <td>{{ $ord }}</td>
                    <td>{{ $res }}</td>
                    <td>{{ $ful }}</td>
                    <td>{{ $remaining }}</td>
                    <td class="small text-muted">{{ $order->created_at?->format('Y-m-d H:i') ?? '—' }}</td>
                    <td class="text-end">
                        <x-ui.buttons.secondary :href="route('sales.orders.show', $order)">{{ __('common.view') }}</x-ui.buttons.secondary>
                    </td>
                </x-ui.table.row>
            @empty
                <x-ui.table.row>
                    <td colspan="{{ $showBulk ? 9 : 8 }}" class="p-0">
                        <x-ui.operational.empty-state :title="$emptyTitle" />
                    </td>
                </x-ui.table.row>
            @endforelse
        </x-ui.table.table>

        <x-slot:pagination>
            <x-ui.operational.pagination :paginator="$orders" />
        </x-slot:pagination>
    </x-ui.operational.index-shell>
</x-ui.layout.page>
