<x-admin-layout
    active="sales"
    :title="__('sales.title')"
    :crumbs="[
        ['label' => __('admin.shell.brand_sub')],
        ['label' => __('sales.title')],
    ]">

    <div class="page-wide"
         x-data="dataTable({ rowsSelector: 'tbody > tr[data-dt-row]' })">

        <div class="page-header mb-6">
            <div>
                <h1 class="page-title">{{ __('sales.title') }}</h1>
                <p class="page-sub">{{ __('sales.sub') }}</p>
            </div>
            @can('create', App\Models\Sale::class)
                <a href="{{ route('cashier.index') }}" class="pos-btn pos-btn-sm pos-btn-primary">
                    <x-icon name="pos" class="w-4 h-4" />
                    {{ __('sales.actions.open_cashier') }}
                </a>
            @endcan
        </div>

        <x-admin.summary-cards :cards="$summaryCards" />

        <div class="card card-pad-0">
            <div class="dt-toolbar">
                <div class="dt-toolbar-title">{{ __('sales.list.title', ['count' => $sales->count()]) }}</div>
                <x-admin.dt-toolbar-actions />
            </div>
            {{-- Search / filter / reset run over AJAX via the shared
                 `.inv-filter` handler (lib/inv-filter-ajax.js): it swaps
                 just the table rows instead of reloading the page. --}}
            <form method="GET" action="{{ route('admin.sales.index') }}" class="inv-filter">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('sales.columns.status') }}</span>
                    <select name="status" class="pos-input" x-data="enhancedSelect()">
                        <option value="all" @selected($filters['status'] === 'all')>{{ __('sales.filter.status_all') }}</option>
                        @foreach (['completed', 'held', 'voided', 'partially_refunded', 'refunded'] as $s)
                            <option value="{{ $s }}" @selected($filters['status'] === $s)>{{ __('sales.statuses.'.$s) }}</option>
                        @endforeach
                    </select>
                </label>
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('sales.columns.method') }}</span>
                    <select name="payment_method_id" class="pos-input" x-data="enhancedSelect()">
                        <option value="">{{ __('sales.filter.method_all') }}</option>
                        @foreach ($methods as $m)
                            <option value="{{ $m->id }}" @selected($filters['paymentMethodId'] === $m->id)>{{ $m->name }}</option>
                        @endforeach
                    </select>
                </label>
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('sales.filter.customer') }}</span>
                    {{-- Remote customer picker (server-side search) — never
                         preloads the full customer list. The current value's
                         label is seeded so it shows correctly on load. --}}
                    <select x-data="remoteSelect({
                                url: @js(route('admin.customers.search')),
                                value: @js($filters['customerId']),
                                label: @js($filters['customerLabel']),
                                placeholder: @js(__('sales.filter.customer_all')),
                            })"
                            name="customer_id"
                            class="pos-input"></select>
                </label>
                <label class="field inv-filter-date">
                    <span class="field-label">{{ __('sales.filter.from') }}</span>
                    <input type="text" name="from" value="{{ $filters['from'] }}"
                           class="pos-input js-datepicker" data-fp-submit-on-change="1"
                           placeholder="{{ __('table.filter_date_from_placeholder') }}">
                </label>
                <label class="field inv-filter-date">
                    <span class="field-label">{{ __('sales.filter.to') }}</span>
                    <input type="text" name="to" value="{{ $filters['to'] }}"
                           class="pos-input js-datepicker" data-fp-submit-on-change="1"
                           placeholder="{{ __('table.filter_date_to_placeholder') }}">
                </label>
                <label class="field inv-filter-search">
                    <span class="field-label">&nbsp;</span>
                    <span class="inv-search">
                        <span class="inv-search-icon"><x-icon name="search" class="w-4 h-4" /></span>
                        <input type="search" name="q" value="{{ $filters['q'] }}" class="pos-input"
                               placeholder="{{ __('sales.filter.search') }}">
                    </span>
                </label>
                <x-admin.filter-reset route="admin.sales.index" />
            </form>

            @if ($sales->isEmpty())
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="cart" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('sales.empty.title') }}</div>
                    <div class="dt-empty-sub">{{ __('sales.empty.sub') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('sales.columns.number') }}</th>
                            <th>{{ __('sales.columns.date') }}</th>
                            <th>{{ __('sales.columns.store') }}</th>
                            <th>{{ __('sales.columns.customer') }}</th>
                            <th>{{ __('sales.columns.cashier') }}</th>
                            <th>{{ __('sales.columns.method') }}</th>
                            <th>{{ __('sales.columns.status') }}</th>
                            <th class="num">{{ __('sales.columns.grand_total') }}</th>
                            <th class="dt-actions-col"><span class="sr-only">{{ __('sales.columns.actions') ?? 'Actions' }}</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($sales as $sale)
                            @php
                                // Payment method summary — first row's method name plus
                                // "+N" when the sale was split-tendered across multiple
                                // methods. Held / pure-credit sales have no payments → "—".
                                $methodNames = $sale->payments
                                    ->map(fn ($p) => $p->paymentMethod?->name)
                                    ->filter()
                                    ->unique()
                                    ->values();
                                $methodLabel = $methodNames->isEmpty()
                                    ? '—'
                                    : ($methodNames->count() === 1
                                        ? $methodNames->first()
                                        : $methodNames->first().' +'.($methodNames->count() - 1));
                            @endphp
                            <tr class="prod-row" data-dt-row
                                data-dt-name="{{ $sale->number ?? '' }}"
                                data-dt-id="{{ $sale->id }}"
                                @click="window.location.href = {{ \Illuminate\Support\Js::from(route('admin.sales.show', $sale)) }}">
                                <td class="mono">{{ $sale->number }}</td>
                                <td>{{ format_datetime($sale->sale_datetime) }}</td>
                                <td>{{ $sale->store?->name ?: '—' }}</td>
                                <td>{{ $sale->customer?->name ?: __('sales.walk_in') }}</td>
                                <td>{{ $sale->cashier?->name ?: '—' }}</td>
                                <td>{{ $methodLabel }}</td>
                                <td>
                                    @php
                                        $badge = match ($sale->status) {
                                            'completed'           => 'positive',
                                            'held'                => 'info',
                                            'voided'              => 'muted',
                                            'partially_refunded',
                                            'refunded'            => 'warning',
                                            default               => 'muted',
                                        };
                                    @endphp
                                    <span class="prod-badge prod-badge-{{ $badge }}">
                                        {{ __('sales.statuses.'.$sale->status) }}
                                    </span>
                                    @php
                                        $gwRev = $sale->returns->contains('gateway_refund_status', \App\Models\SaleReturn::GATEWAY_REFUND_SUCCEEDED)
                                            ? 'succeeded'
                                            : ($sale->returns->contains('gateway_refund_status', \App\Models\SaleReturn::GATEWAY_REFUND_FAILED) ? 'failed' : null);
                                    @endphp
                                    @if ($gwRev === 'succeeded')
                                        <span class="prod-badge prod-badge-positive" title="{{ __('sales.gateway_refund.reversed') }}">{{ __('sales.gateway_refund.reversed_short') }}</span>
                                    @elseif ($gwRev === 'failed')
                                        <span class="prod-badge prod-badge-negative" title="{{ __('sales.gateway_refund.failed') }}">{{ __('sales.gateway_refund.failed_short') }}</span>
                                    @endif
                                </td>
                                <td class="num tnum">{{ format_money($sale->grand_total) }}</td>
                                <td>
                                    @php
                                        $shiftOpen = $sale->shift_id ? (\App\Models\Shift::query()->find($sale->shift_id)?->isOpen() ?? false) : true;
                                        $voidable  = $sale->status === \App\Models\Sale::STATUS_COMPLETED
                                            && $sale->returns->isEmpty()
                                            && $shiftOpen;
                                    @endphp
                                    <x-admin.row-actions>
                                        <x-admin.row-action :href="route('admin.sales.show', $sale)" icon="eye" :label="__('table.action.view')" />
                                        <x-admin.row-action :href="route('admin.sales.receipt', $sale)" target="_blank" icon="receipt" :label="__('sales.actions.print')" />

                                        @can ('refund', $sale)
                                            @if (in_array($sale->status, [\App\Models\Sale::STATUS_COMPLETED, \App\Models\Sale::STATUS_PARTIALLY_REFUNDED], true))
                                                <x-admin.row-action :href="route('admin.sales.refund.form', $sale)" icon="refund" :label="__('sales.actions.refund')" />
                                            @endif
                                        @endcan

                                        @can ('void', $sale)
                                            @if ($voidable)
                                                <div class="row-action-sep"></div>
                                                <x-admin.row-action icon="x" variant="danger" :label="__('sales.actions.void')"
                                                    @click="$store.confirm.show({
                                                        title:        {{ \Illuminate\Support\Js::from(__('sales.confirm_void.title', ['number' => $sale->number])) }},
                                                        message:      {{ \Illuminate\Support\Js::from(__('sales.confirm_void.message')) }},
                                                        intent:       'danger',
                                                        confirmLabel: {{ \Illuminate\Support\Js::from(__('sales.confirm_void.confirm')) }},
                                                        cancelLabel:  {{ \Illuminate\Support\Js::from(__('sales.confirm_void.cancel')) }},
                                                        onConfirm:    () => $submitForm({{ \Illuminate\Support\Js::from(route('admin.sales.void', $sale)) }}),
                                                    })" />
                                            @endif
                                        @endcan
                                    </x-admin.row-actions>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>
                <x-admin.dt-pager />
            @endif
        </div>
    </div>
</x-admin-layout>
