@extends('layouts.admin')
@section('title', 'Order Allocation Rules')
@section('content')
@php
    $ruleMeta = [
        \App\Models\AllocationRule::TYPE_STORE_PREFERENCE => [
            'label' => 'Store preference',
            'icon' => 'bi-shop',
            'blurb' => 'Prefer configured store preferences when choosing a fulfillment location.',
            'tone' => 'primary',
        ],
        \App\Models\AllocationRule::TYPE_NEAREST_STORE => [
            'label' => 'Nearest store',
            'icon' => 'bi-pin-map',
            'blurb' => 'Prefer the closest store when latitude/longitude is available.',
            'tone' => 'info',
        ],
        \App\Models\AllocationRule::TYPE_HIGHEST_STOCK => [
            'label' => 'Highest stock',
            'icon' => 'bi-boxes',
            'blurb' => 'Prefer the location with the most available inventory for the order lines.',
            'tone' => 'warning',
        ],
        \App\Models\AllocationRule::TYPE_PRIORITY_STORE => [
            'label' => 'Priority store',
            'icon' => 'bi-sort-numeric-down',
            'blurb' => 'Prefer locations with a better location priority setting.',
            'tone' => 'primary',
        ],
        \App\Models\AllocationRule::TYPE_WAREHOUSE_FALLBACK => [
            'label' => 'Warehouse fallback',
            'icon' => 'bi-building',
            'blurb' => 'If no store can fulfill, fall back to the central warehouse when stock allows.',
            'tone' => 'secondary',
        ],
        \App\Models\AllocationRule::TYPE_SPLIT_ORDERS => [
            'label' => 'Split orders',
            'icon' => 'bi-subtract',
            'blurb' => 'Allow one online order to be fulfilled from multiple locations when a single shop cannot cover all lines.',
            'tone' => 'success',
        ],
        \App\Models\AllocationRule::TYPE_BACKORDERS => [
            'label' => 'Backorders',
            'icon' => 'bi-hourglass-split',
            'blurb' => 'Allow accepting orders when stock is short. Keep off unless you intentionally support backorders.',
            'tone' => 'danger',
        ],
    ];

    $activeCount = $rules->where('is_active', true)->count();
    $splitRule = $rules->firstWhere('rule_type', \App\Models\AllocationRule::TYPE_SPLIT_ORDERS);
@endphp

<div class="tw-migrated space-y-4">
    <x-ui.page-header
        title="Order Allocation Rules"
        subtitle="Control how online orders pick fulfillment stores and warehouses"
    >
        <x-slot:actions>
            <a href="{{ route('admin.locations.index') }}" class="tw-btn-outline">
                <i class="bi bi-shop me-1"></i> Locations
            </a>
        </x-slot:actions>
    </x-ui.page-header>

    @if(session('success'))
        <x-ui.alert type="success">{{ session('success') }}</x-ui.alert>
    @endif
    @if($errors->any())
        <x-ui.alert type="danger">
            <ul class="mb-0">@foreach($errors->all() as $e)<li>{{ $e }}</li>@endforeach</ul>
        </x-ui.alert>
    @endif

    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
        <x-ui.card>
            <div class="d-flex align-items-center justify-content-between gap-2">
                <div>
                    <div class="text-muted small text-uppercase tracking-wide">Active rules</div>
                    <div class="fs-4 fw-semibold lh-1 mt-1">{{ $activeCount }}<span class="text-muted fs-6 fw-normal"> / {{ $rules->count() }}</span></div>
                </div>
                <span class="rounded-3 p-2 bg-[color-mix(in_srgb,var(--color-success)_12%,transparent)] text-[var(--color-success)]">
                    <i class="bi bi-toggles2 fs-5"></i>
                </span>
            </div>
        </x-ui.card>
        <x-ui.card>
            <div class="d-flex align-items-center justify-content-between gap-2">
                <div>
                    <div class="text-muted small text-uppercase tracking-wide">Split orders</div>
                    <div class="mt-1">
                        <x-ui.badge :variant="$splitRule?->is_active ? 'success' : 'secondary'">
                            {{ $splitRule?->is_active ? 'Enabled' : 'Disabled' }}
                        </x-ui.badge>
                    </div>
                </div>
                <span class="rounded-3 p-2 bg-[color-mix(in_srgb,var(--color-primary)_12%,transparent)] text-[var(--color-primary)]">
                    <i class="bi bi-subtract fs-5"></i>
                </span>
            </div>
        </x-ui.card>
        <x-ui.card>
            <div class="d-flex align-items-center justify-content-between gap-2">
                <div>
                    <div class="text-muted small text-uppercase tracking-wide">Company</div>
                    <div class="fw-semibold mt-1 text-truncate" style="max-width: 11rem;">{{ $company->name ?? '—' }}</div>
                </div>
                <span class="rounded-3 p-2 bg-[var(--color-bg)] text-[var(--color-text-muted)]">
                    <i class="bi bi-building fs-5"></i>
                </span>
            </div>
        </x-ui.card>
    </div>

    <x-ui.alert type="info">
        <div class="fw-semibold mb-1">How allocation works</div>
        <ol class="mb-0 ps-3 small">
            <li>Lower <strong>priority</strong> numbers are considered first.</li>
            <li>Only <strong>active</strong> rules apply. Toggle a rule off to skip it.</li>
            <li>Split / Backorder stay off unless you enable them deliberately.</li>
            <li>Delivery coverage uses enabled Countries / States / Cities. Each store is a carrier pickup point.</li>
        </ol>
    </x-ui.alert>

    @if($rules->isEmpty())
        <x-ui.card>
            <x-ui.empty-state
                title="No allocation rules"
                description="Rules will appear here after company defaults are seeded."
            />
        </x-ui.card>
    @else
        <div class="space-y-3">
            @foreach($rules as $rule)
                @php
                    $meta = $ruleMeta[$rule->rule_type] ?? [
                        'label' => str_replace('_', ' ', $rule->rule_type),
                        'icon' => 'bi-sliders',
                        'blurb' => 'Custom allocation rule.',
                        'tone' => 'secondary',
                    ];
                @endphp
                <x-ui.card>
                    <div class="d-flex flex-column flex-lg-row gap-3 gap-lg-4">
                        <div class="d-flex gap-3 flex-grow-1 min-w-0">
                            <div class="flex-shrink-0 text-center" style="width: 3rem;">
                                <div class="rounded-3 border d-flex align-items-center justify-content-center mx-auto"
                                     style="width: 2.75rem; height: 2.75rem; border-color: var(--color-border) !important; background: color-mix(in srgb, var(--color-bg) 70%, transparent);">
                                    <span class="fw-bold" style="color: var(--color-primary);">{{ $rule->priority }}</span>
                                </div>
                                <div class="text-muted" style="font-size: 0.65rem; letter-spacing: 0.04em; margin-top: 0.35rem;">PRIORITY</div>
                            </div>

                            <div class="min-w-0 flex-grow-1">
                                <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                    <i class="bi {{ $meta['icon'] }} text-[var(--color-text-muted)]"></i>
                                    <h3 class="h6 mb-0 fw-semibold">{{ $rule->name }}</h3>
                                    <x-ui.badge :variant="$meta['tone']">{{ $meta['label'] }}</x-ui.badge>
                                    <x-ui.badge :variant="$rule->is_active ? 'success' : 'secondary'">
                                        <span class="d-inline-flex align-items-center gap-1">
                                            <x-ui.status-dot :color="$rule->is_active ? 'success' : 'secondary'" />
                                            {{ $rule->is_active ? 'Active' : 'Off' }}
                                        </span>
                                    </x-ui.badge>
                                </div>
                                <p class="text-muted small mb-2 mb-lg-3">{{ $meta['blurb'] }}</p>
                                <div class="small text-muted font-monospace">{{ $rule->rule_type }}</div>
                                @if(!empty($meta['link']))
                                    <a href="{{ $meta['link'] }}" class="small d-inline-flex align-items-center gap-1 mt-2">
                                        <i class="bi bi-box-arrow-up-right"></i> {{ $meta['link_label'] ?? 'Open' }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="flex-shrink-0" style="min-width: min(100%, 18rem);">
                            <form method="post" action="{{ route('admin.allocation-rules.update', $rule) }}" class="row g-2 align-items-end">
                                @csrf
                                @method('PUT')
                                <div class="col-8">
                                    <label class="admin-form-label" for="name-{{ $rule->id }}">Display name</label>
                                    <input
                                        id="name-{{ $rule->id }}"
                                        name="name"
                                        class="form-control admin-form-control"
                                        value="{{ old('name', $rule->name) }}"
                                        required
                                    >
                                </div>
                                <div class="col-4">
                                    <label class="admin-form-label" for="priority-{{ $rule->id }}">Priority</label>
                                    <input
                                        id="priority-{{ $rule->id }}"
                                        type="number"
                                        name="priority"
                                        class="form-control admin-form-control"
                                        value="{{ old('priority', $rule->priority) }}"
                                        min="1"
                                        max="999"
                                        required
                                    >
                                </div>
                                <div class="col-12">
                                    <div class="form-check mb-2">
                                        <input
                                            type="checkbox"
                                            name="is_active"
                                            value="1"
                                            class="form-check-input"
                                            id="active-{{ $rule->id }}"
                                            @checked(old('is_active', $rule->is_active))
                                        >
                                        <label class="form-check-label" for="active-{{ $rule->id }}">Rule is active</label>
                                    </div>
                                </div>
                                <div class="col-12 d-flex flex-wrap gap-2">
                                    <button type="submit" class="tw-btn-primary">
                                        <i class="bi bi-check2 me-1"></i> Save
                                    </button>
                                    <button
                                        type="submit"
                                        form="toggle-rule-{{ $rule->id }}"
                                        class="{{ $rule->is_active ? 'tw-btn-outline' : 'tw-btn-secondary' }}"
                                    >
                                        <i class="bi {{ $rule->is_active ? 'bi-pause-circle' : 'bi-play-circle' }} me-1"></i>
                                        {{ $rule->is_active ? 'Disable' : 'Enable' }}
                                    </button>
                                </div>
                            </form>
                            <form id="toggle-rule-{{ $rule->id }}" method="post" action="{{ route('admin.allocation-rules.toggle', $rule) }}" class="d-none">
                                @csrf
                            </form>
                        </div>
                    </div>
                </x-ui.card>
            @endforeach
        </div>
    @endif
</div>
@endsection
