<x-admin-layout
    active="purchases"
    :title="__('purchases.title')"
    :crumbs="[
        ['label' => __('admin.shell.brand_sub')],
        ['label' => __('purchases.crumb_parent')],
        ['label' => __('purchases.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">{{ __('purchases.title') }}</h1>
                <p class="page-sub">{{ __('purchases.sub') }}</p>
            </div>
            <div class="flex items-center gap-2">
                <div class="dropdown" x-data="dropdown">
                    <button type="button"
                            class="pos-btn pos-btn-sm pos-btn-ghost"
                            @click="toggle()"
                            :aria-expanded="open">
                        <x-icon name="download" class="w-4 h-4" />
                        {{ __('purchases.actions.export') }}
                        <x-icon name="chevron" class="w-4 h-4" />
                    </button>
                    <div class="dropdown-panel"
                         x-show="open"
                         x-cloak
                         @click.outside="close()"
                         @keydown.escape.window="close()">
                        <a href="{{ route('admin.purchases.export', ['format' => 'csv']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('purchases.actions.export_csv') }}</span>
                        </a>
                        <a href="{{ route('admin.purchases.export', ['format' => 'xlsx']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('purchases.actions.export_xlsx') }}</span>
                        </a>
                    </div>
                </div>

                @can('create', App\Models\Purchase::class)
                    <a href="{{ route('admin.purchases.create') }}" class="pos-btn pos-btn-sm pos-btn-primary">
                        <x-icon name="plus" class="w-4 h-4" />
                        {{ __('purchases.new') }}
                    </a>
                @endcan
            </div>
        </div>

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

        <div class="card card-pad-0">
            <div class="dt-toolbar">
                <div class="dt-toolbar-title">{{ __('purchases.list.title', ['count' => $purchases->count()]) }}</div>
                <x-admin.dt-toolbar-actions />
            </div>
            <form method="GET" action="{{ route('admin.purchases.index') }}" class="inv-filter">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('purchases.columns.status') }}</span>
                    <select name="status" class="pos-input" x-data="enhancedSelect()" onchange="this.form.submit()">
                        <option value="all"             @selected($filters['status'] === 'all')>{{ __('purchases.filter.status_all') }}</option>
                        <option value="draft"           @selected($filters['status'] === 'draft')>{{ __('purchases.status.draft') }}</option>
                        <option value="submitted"       @selected($filters['status'] === 'submitted')>{{ __('purchases.status.submitted') }}</option>
                        <option value="received"        @selected($filters['status'] === 'received')>{{ __('purchases.status.received') }}</option>
                        <option value="partially_paid"  @selected($filters['status'] === 'partially_paid')>{{ __('purchases.status.partially_paid') }}</option>
                        <option value="paid"            @selected($filters['status'] === 'paid')>{{ __('purchases.status.paid') }}</option>
                        <option value="cancelled"       @selected($filters['status'] === 'cancelled')>{{ __('purchases.status.cancelled') }}</option>
                    </select>
                </label>
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('purchases.columns.supplier') }}</span>
                    <select name="supplier_id" class="pos-input" x-data="enhancedSelect()" onchange="this.form.submit()">
                        <option value="">{{ __('purchases.filter.supplier_all') }}</option>
                        @foreach ($suppliers as $supplier)
                            <option value="{{ $supplier->id }}" @selected($filters['supplierId'] === $supplier->id)>{{ $supplier->name }}</option>
                        @endforeach
                    </select>
                </label>
                <label class="field inv-filter-date">
                    <span class="field-label">{{ __('purchases.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">{{ __('purchases.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="{{ __('purchases.filter.search') }}">
                    </span>
                </label>
                <x-admin.filter-reset route="admin.purchases.index" />
            </form>

            @if ($purchases->isEmpty())
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="truck" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('purchases.empty_state.title') }}</div>
                    <div class="dt-empty-sub">{{ __('purchases.empty_state.sub') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('purchases.columns.number') }}</th>
                            <th>{{ __('purchases.columns.supplier') }}</th>
                            <th>{{ __('purchases.columns.store') }}</th>
                            <th>{{ __('purchases.columns.date') }}</th>
                            <th>{{ __('purchases.columns.due_date') }}</th>
                            <th class="num">{{ __('purchases.columns.grand_total') }}</th>
                            <th class="num">{{ __('purchases.columns.balance') }}</th>
                            <th>{{ __('purchases.columns.status') }}</th>
                            <th class="dt-actions-col"><span class="sr-only">{{ __('purchases.columns.actions') }}</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($purchases as $p)
                            @php
                                $statusBadge = match ($p->status) {
                                    'draft'           => 'prod-badge-muted',
                                    'submitted'       => 'prod-badge-muted',
                                    'received'        => 'prod-badge-positive',
                                    'partially_paid'  => 'prod-badge-positive',
                                    'paid'            => 'prod-badge-positive',
                                    'cancelled'       => 'prod-badge-muted',
                                    default           => 'prod-badge-muted',
                                };
                            @endphp
                            <tr class="prod-row" data-dt-row
                                data-dt-name="{{ $p->number ?? '' }}"
                                data-dt-id="{{ $p->id }}"
                                @click="window.location.href = {{ \Illuminate\Support\Js::from(route('admin.purchases.show', $p)) }}">
                                <td class="mono">
                                    {{ $p->number }}
                                    @if (($p->attachments_count ?? 0) > 0)
                                        <span class="fg-tertiary inline-flex align-middle ms-1" title="{{ __('purchases.sections.attachment') }}">
                                            <x-icon name="note" class="w-3.5 h-3.5" />
                                        </span>
                                    @endif
                                </td>
                                <td>{{ $p->supplier?->name ?: '—' }}</td>
                                <td>{{ $p->store?->name ?: '—' }}</td>
                                <td>{{ format_date($p->purchase_date) }}</td>
                                <td>{{ $p->due_date ? format_date($p->due_date) : '—' }}</td>
                                <td class="num tnum">{{ format_money($p->grand_total, null, $p->currency_code) }}</td>
                                <td class="num tnum">{{ format_money($p->balance_due, null, $p->currency_code) }}</td>
                                <td>
                                    <span class="prod-badge {{ $statusBadge }}">{{ __('purchases.status.'.$p->status) }}</span>
                                </td>
                                <td>
                                    <x-admin.row-actions>
                                        @can('view', $p)
                                            <x-admin.row-action :href="route('admin.purchases.show', $p)" icon="eye" :label="__('purchases.actions.view')" />
                                        @endcan

                                        {{-- Post-receive actions — mirror the purchase show page CTAs. --}}
                                        @if (in_array($p->status, ['received', 'partially_paid', 'paid'], true))
                                            @can('update', $p)
                                                <x-admin.row-action :href="route('admin.purchase-returns.create', $p)" icon="refund" :label="__('purchases.actions.create_return')" />
                                            @endcan
                                            @can('create', App\Models\PurchasePayment::class)
                                                <x-admin.row-action :href="route('admin.supplier-payments.create', [
                                                        'supplier_id' => $p->supplier_id,
                                                        'store_id'    => $p->store_id,
                                                        'from'        => 'purchase',
                                                    ])" icon="cash" :label="__('purchases.actions.record_payment')" />
                                            @endcan
                                        @endif

                                        @if ($p->status === 'draft')
                                            @can('delete', $p)
                                                <div class="row-action-sep"></div>
                                                <x-admin.row-action icon="trash" variant="danger" :label="__('purchases.actions.delete')"
                                                    @click="
                                                        const btn = $event.currentTarget;
                                                        $store.confirm.show({
                                                            title: {{ \Illuminate\Support\Js::from(__('purchases.confirm_delete.title', ['number' => $p->number])) }},
                                                            message: {{ \Illuminate\Support\Js::from(__('purchases.confirm_delete.message')) }},
                                                            intent: 'danger',
                                                            confirmLabel: {{ \Illuminate\Support\Js::from(__('purchases.confirm_delete.confirm')) }},
                                                            onConfirm: () => $deleteRow({{ \Illuminate\Support\Js::from(route('admin.purchases.destroy', $p)) }}, btn),
                                                        })
                                                    " />
                                            @endcan
                                        @endif
                                    </x-admin.row-actions>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>

                <x-admin.dt-pager />
            @endif
        </div>
    </div>
</x-admin-layout>
