@extends('layouts.admin')
@section('title', 'Replenishment')
@section('content')
<div class="tw-migrated space-y-4">
    <x-ui.page-header title="Store Replenishment" />

    @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

    <x-ui.card>
        <form method="get" class="row g-2 align-items-end justify-content-end">
            <div class="col-md-4 col-lg-3">
                <label class="admin-form-label">Filter by store</label>
                <select name="store_location_id" class="form-select admin-form-control">
                    <option value="">All stores</option>
                    @foreach($stores as $s)
                        <option value="{{ $s->id }}" @selected(request('store_location_id')==$s->id)>{{ $s->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-auto">
                <label class="admin-form-label">&nbsp;</label>
                <x-ui.button type="submit" variant="outline">Apply</x-ui.button>
            </div>
        </form>
    </x-ui.card>

    <div class="grid gap-4 lg:grid-cols-12">
        <div class="lg:col-span-4">
            <x-ui.card title="Add Rule">
                <form method="post" action="{{ route('admin.replenishment.store') }}">
                    @csrf
                    <div class="mb-2">
                        <label class="admin-form-label">Store *</label>
                        <select name="store_location_id" class="form-select admin-form-control" required>
                            @foreach($stores as $s)<option value="{{ $s->id }}">{{ $s->name }}</option>@endforeach
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="admin-form-label">From Warehouse *</label>
                        <select name="warehouse_location_id" class="form-select admin-form-control" required>
                            @foreach($warehouses as $w)<option value="{{ $w->id }}">{{ $w->name }}</option>@endforeach
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="admin-form-label">Product (optional = all tracked)</label>
                        <select name="product_id" class="form-select admin-form-control">
                            <option value="">All products at store</option>
                            @foreach($products as $p)
                                <option value="{{ $p->id }}">{{ $p->name }} @if($p->sku)({{ $p->sku }})@endif</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="row g-2 mb-2">
                        <div class="col-4"><label class="admin-form-label">Min</label><input type="number" name="min_qty" class="form-control" value="5" min="0" required></div>
                        <div class="col-4"><label class="admin-form-label">Max</label><input type="number" name="max_qty" class="form-control" value="20" min="0" required></div>
                        <div class="col-4"><label class="admin-form-label">Reorder</label><input type="number" name="reorder_qty" class="form-control" value="10" min="0" required></div>
                    </div>
                    <button type="submit" class="tw-btn-primary w-100">Save Rule</button>
                </form>
            </x-ui.card>
        </div>

        <div class="lg:col-span-8 space-y-4">
            <x-ui.card title="Suggestions">
                @if($suggestions->isEmpty())
                    <p class="text-muted mb-0">No replenishment needed right now (or no active rules).</p>
                @else
                <form method="post" action="{{ route('admin.replenishment.create-transfer') }}" id="replenish-transfer-form">
                    @csrf
                    @php $first = $suggestions->first(); @endphp
                    <input type="hidden" name="warehouse_location_id" value="{{ $first['warehouse_location_id'] }}">
                    <input type="hidden" name="store_location_id" value="{{ $first['store_location_id'] }}">
                    <div class="tw-table-wrap">
                        <table class="tw-table align-middle">
                            <thead>
                                <tr>
                                    <th style="width:40px"><input type="checkbox" id="select-all-sug" checked></th>
                                    <th>Product</th>
                                    <th>On hand</th>
                                    <th>WH avail</th>
                                    <th>Qty</th>
                                </tr>
                            </thead>
                            <tbody>
                            @foreach($suggestions as $i => $sug)
                                <tr data-sug-row>
                                    <td>
                                        <input type="checkbox" class="sug-check" data-index="{{ $i }}" checked>
                                        <input type="hidden" name="items[{{ $i }}][product_id]" value="{{ $sug['product_id'] }}" class="sug-product" disabled>
                                        <input type="hidden" name="items[{{ $i }}][quantity]" value="{{ $sug['suggested_qty'] }}" class="sug-qty" disabled>
                                    </td>
                                    <td>
                                        <strong>{{ $sug['product_name'] }}</strong>
                                        @if(!empty($sug['product_sku']))
                                            <div class="small text-muted">{{ $sug['product_sku'] }}</div>
                                        @endif
                                    </td>
                                    <td>{{ $sug['on_hand'] ?? 0 }}</td>
                                    <td>{{ $sug['warehouse_available'] ?? 0 }}</td>
                                    <td>
                                        <input type="number" min="1" class="form-control form-control-sm sug-qty-input" style="width:90px"
                                               value="{{ $sug['suggested_qty'] }}" data-index="{{ $i }}">
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                    <button type="submit" class="tw-btn-primary mt-3"><i class="bi bi-arrow-left-right"></i> Create Transfer Draft</button>
                </form>
                @endif
            </x-ui.card>

            <x-ui.card title="Rules">
                <x-ui.table>
                    <x-slot:thead>
                        <tr>
                            <th>Store</th>
                            <th>Warehouse</th>
                            <th>Product</th>
                            <th>Min/Max/Reorder</th>
                            <th></th>
                        </tr>
                    </x-slot:thead>
                    @forelse($rules as $rule)
                    <tr>
                        <td>{{ $rule->storeLocation?->name }}</td>
                        <td>{{ $rule->warehouseLocation?->name }}</td>
                        <td>{{ $rule->product?->name ?? 'All' }}</td>
                        <td>{{ $rule->min_qty }} / {{ $rule->max_qty }} / {{ $rule->reorder_qty }}</td>
                        <td>
                            <form method="post" action="{{ route('admin.replenishment.destroy', $rule) }}" onsubmit="return confirm('Delete?')">
                                @csrf @method('DELETE')
                                <x-ui.button type="submit" variant="danger" size="sm">Delete</x-ui.button>
                            </form>
                        </td>
                    </tr>
                    @empty
                    <tr><td colspan="5" class="text-muted text-center py-3">No rules yet.</td></tr>
                    @endforelse
                </x-ui.table>
                {{ $rules->withQueryString()->links() }}
            </x-ui.card>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
(function () {
    const form = document.getElementById('replenish-transfer-form');
    if (!form) return;

    function syncRow(row) {
        const check = row.querySelector('.sug-check');
        const product = row.querySelector('.sug-product');
        const qtyHidden = row.querySelector('.sug-qty');
        const qtyInput = row.querySelector('.sug-qty-input');
        const on = check && check.checked;
        if (product) product.disabled = !on;
        if (qtyHidden) {
            qtyHidden.disabled = !on;
            if (qtyInput) qtyHidden.value = qtyInput.value;
        }
    }

    form.querySelectorAll('[data-sug-row]').forEach(function (row) {
        syncRow(row);
        row.querySelector('.sug-check')?.addEventListener('change', function () { syncRow(row); });
        row.querySelector('.sug-qty-input')?.addEventListener('input', function () { syncRow(row); });
    });

    document.getElementById('select-all-sug')?.addEventListener('change', function () {
        form.querySelectorAll('.sug-check').forEach(function (c) {
            c.checked = this.checked;
            syncRow(c.closest('[data-sug-row]'));
        }.bind(this));
    });

    form.addEventListener('submit', function (e) {
        const enabled = form.querySelectorAll('.sug-product:not([disabled])');
        if (!enabled.length) {
            e.preventDefault();
            alert('Select at least one product.');
        }
    });
})();
</script>
@endpush
