@php
    use App\Modules\Inventory\Stock\Support\DecimalQuantity;
    use App\Modules\Sales\Services\SalesLineRemainingCalculator;
    use App\Modules\Sales\Support\SalesOrderLineUiLabels;
@endphp

<h5 class="h6">{{ __('sales.orders.lines.title') }}</h5>
<x-ui.table.table :columns="[
    ['label' => __('sales.orders.lines.item')],
    ['label' => __('sales.orders.lines.warehouse')],
    ['label' => __('sales.orders.columns.ordered')],
    ['label' => __('sales.orders.columns.reserved')],
    ['label' => __('sales.orders.columns.fulfilled')],
    ['label' => __('sales.orders.columns.remaining')],
    ['label' => __('sales.orders.lines.available_hint')],
    ['label' => __('sales.orders.lines.reservation_id')],
    ['label' => __('sales.orders.lines.allocation_state')],
    ['label' => __('sales.orders.lines.fulfillment_state')],
]">
    @foreach ($order->lines as $line)
        @php
            $ordered = trim((string) $line->quantity_ordered);
            $reserved = trim((string) $line->quantity_reserved);
            $fulfilled = trim((string) $line->quantity_fulfilled);
            $remaining = SalesLineRemainingCalculator::allocatableRemaining($line);
            $hintKey = (int) $line->warehouse_id.'_'.(int) $line->item_id;
            $avail = $stockHints[$hintKey] ?? null;
            $allocKey = SalesOrderLineUiLabels::allocationStateKey($line);
            $fulKey = SalesOrderLineUiLabels::fulfillmentStateKey($line);
            $stockWarn = DecimalQuantity::gtZero($remaining) && ($avail === null || ! DecimalQuantity::gte((string) $avail, $remaining));
        @endphp
        <x-ui.table.row @class(['table-warning' => $stockWarn])>
            <td>
                <strong>{{ $line->inventoryItem?->sku ?? '—' }}</strong>
                <div class="small text-muted">{{ $line->inventoryItem?->name ?? '' }}</div>
            </td>
            <td class="small">{{ $line->warehouse?->code ?? '—' }}</td>
            <td>{{ $ordered }}</td>
            <td>{{ $reserved }}</td>
            <td>{{ $fulfilled }}</td>
            <td><strong>{{ $remaining }}</strong></td>
            <td class="small">
                @if ($avail !== null)
                    {{ $avail }}
                @else
                    <span class="text-muted">—</span>
                @endif
                @if ($stockWarn)
                    <div class="text-danger mt-1">{{ __('sales.orders.lines.insufficient_hint') }}</div>
                @endif
            </td>
            <td class="small font-monospace">{{ $line->reservation_public_id ?? '—' }}</td>
            <td class="small">{{ __('sales.orders.states.allocation.'.$allocKey) }}</td>
            <td class="small">{{ __('sales.orders.states.fulfillment.'.$fulKey) }}</td>
        </x-ui.table.row>
    @endforeach
</x-ui.table.table>
