@php
    $oldCustomerId     = old('customer_id', '');
    $oldBillingAddress = old('billing_address')
        ?? $customers->firstWhere('id', $oldCustomerId)?->address
        ?? '';
@endphp

<x-app-layout>
    <x-slot:heading>Create Invoice</x-slot:heading>

    <div class="max-w-2xl">

        <form method="POST" action="{{ route('sales.store') }}"
              x-data="invoiceForm()"
              class="rounded-xl border border-gray-100 bg-white shadow-sm divide-y divide-gray-100">
            @csrf

            {{-- ════════════════════════════════════════════════════
                 SECTION 1 · BILL TO
            ════════════════════════════════════════════════════ --}}
            <div class="p-6">

                <label class="mb-1.5 block text-sm font-semibold text-gray-800">
                    Customer <span class="text-red-500">*</span>
                </label>

                @error('customer_id')
                    <div class="mb-2 rounded-lg border border-red-200 bg-red-50 px-4 py-2.5 text-sm font-medium text-red-700">
                        {{ $message }}
                    </div>
                @enderror

                @if($customers->isEmpty())

                    <div class="rounded-xl border-2 border-dashed border-gray-200 py-10 text-center">
                        <div class="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100">
                            <svg class="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/>
                            </svg>
                        </div>
                        <p class="font-medium text-gray-700">No customers yet</p>
                        <p class="mt-1 text-sm text-gray-500">Add a customer before creating an invoice.</p>
                        <a href="{{ route('customers.create') }}" target="_blank"
                           class="mt-4 inline-flex items-center gap-1.5 rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700">
                            + Add First Customer
                        </a>
                    </div>

                @else

                    <select name="customer_id" id="customer_id"
                            onchange="onCustomerChange(this)"
                            class="w-full rounded-lg border border-gray-300 bg-white py-2.5 pl-3 pr-8 text-sm shadow-sm focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500">
                        <option value="">— Select a customer —</option>
                        @foreach($customers as $c)
                            <option value="{{ $c->id }}"
                                    data-phone="{{ $c->phone ?? '' }}"
                                    data-address="{{ $c->address ?? '' }}"
                                    @selected($oldCustomerId == $c->id)>
                                {{ $c->display_name }}{{ $c->phone ? '  ·  ' . $c->phone : '' }}
                            </option>
                        @endforeach
                    </select>

                    {{-- Customer info card shown after selection --}}
                    <div id="cust-info"
                         class="mt-3 flex items-start gap-3 rounded-lg border border-primary-200 bg-primary-50 px-4 py-3"
                         style="display:none">
                        <div id="cust-avatar"
                             class="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary-200 text-sm font-bold text-primary-800">
                        </div>
                        <div class="min-w-0 flex-1">
                            <p id="cust-info-name" class="text-sm font-semibold text-gray-900"></p>
                            <p id="cust-info-phone" class="mt-0.5 text-xs text-gray-500"></p>
                        </div>
                        <a href="{{ route('customers.create') }}" target="_blank"
                           class="shrink-0 text-xs text-primary-600 hover:underline">+ New</a>
                    </div>

                    {{-- Billing address (optional) --}}
                    <div class="mt-3">
                        <label class="mb-1 block text-xs font-medium text-gray-500">
                            Billing Address <span class="ml-1 font-normal text-gray-400">— optional, edit if different</span>
                        </label>
                        <textarea name="billing_address" id="billing_address" rows="2"
                                  placeholder="Auto-filled from customer record…"
                                  class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500">{{ $oldBillingAddress }}</textarea>
                    </div>

                @endif
            </div>

            {{-- ════════════════════════════════════════════════════
                 SECTION 2 · SALE DETAILS
            ════════════════════════════════════════════════════ --}}
            <div class="space-y-4 p-6">

                <div class="flex items-center gap-2 mb-1">
                    <div class="flex h-7 w-7 items-center justify-center rounded-lg bg-blue-100">
                        <svg class="h-4 w-4 text-blue-600" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25z"/>
                        </svg>
                    </div>
                    <h3 class="text-sm font-semibold text-gray-800">Sale Details</h3>
                </div>

                {{-- Harvest --}}
                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700">
                        Harvest <span class="text-red-500">*</span>
                    </label>
                    <select name="harvest_id"
                            class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                        <option value="">Select harvest…</option>
                        @foreach($harvests as $h)
                            <option value="{{ $h->id }}" @selected($selectedHarvestId == $h->id)>
                                {{ $h->pond->name }} — {{ $h->harvest_date->format('d M Y') }}
                                ({{ number_format($h->total_weight_kg, 1) }} kg)
                            </option>
                        @endforeach
                    </select>
                    @error('harvest_id') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>

                {{-- Date --}}
                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700">
                        Sale Date <span class="text-red-500">*</span>
                    </label>
                    <input type="date" name="sale_date"
                           value="{{ old('sale_date', today()->toDateString()) }}"
                           max="{{ today()->toDateString() }}"
                           class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                    @error('sale_date') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>

                {{-- Qty + Price --}}
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="mb-1 block text-sm font-medium text-gray-700">
                            Quantity (kg) <span class="text-red-500">*</span>
                        </label>
                        <input type="number" name="quantity_kg" x-model.number="qty"
                               value="{{ old('quantity_kg') }}" step="0.01" min="0.01" placeholder="0.00"
                               class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                        @error('quantity_kg') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>
                    <div>
                        <label class="mb-1 block text-sm font-medium text-gray-700">
                            Price / kg <span class="text-red-500">*</span>
                        </label>
                        <div class="flex">
                            <span class="inline-flex items-center rounded-l-lg border border-r-0 border-gray-300 bg-gray-50 px-3 text-sm font-medium text-gray-600">₦</span>
                            <input type="number" name="price_per_kg_naira" x-model.number="price"
                                   value="{{ old('price_per_kg_naira') }}" step="0.01" min="0.01" placeholder="0.00"
                                   class="w-full rounded-r-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                        </div>
                        @error('price_per_kg_naira') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>
                </div>

                {{-- Running total --}}
                <div x-show="qty > 0 && price > 0" x-cloak
                     class="flex items-center justify-between rounded-xl border border-green-200 bg-green-50 px-5 py-3.5">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wider text-green-700">Invoice Total</p>
                        <p class="mt-0.5 text-xs text-green-600"
                           x-text="qty + ' kg × ₦' + price.toLocaleString('en-NG')"></p>
                    </div>
                    <p class="text-xl font-bold text-green-800"
                       x-text="'₦' + (qty * price).toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2})"></p>
                </div>
            </div>

            {{-- ════════════════════════════════════════════════════
                 SECTION 3 · PAYMENT
            ════════════════════════════════════════════════════ --}}
            <div class="space-y-4 p-6">

                <div class="flex items-center gap-2 mb-1">
                    <div class="flex h-7 w-7 items-center justify-center rounded-lg bg-green-100">
                        <svg class="h-4 w-4 text-green-600" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0115.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 013 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 00-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 01-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 003 15h-.75M15 10.5a3 3 0 11-6 0 3 3 0 016 0zm3 0h.008v.008H18V10.5zm-12 0h.008v.008H6V10.5z"/>
                        </svg>
                    </div>
                    <h3 class="text-sm font-semibold text-gray-800">Payment</h3>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="mb-1 block text-sm font-medium text-gray-700">
                            Method <span class="text-red-500">*</span>
                        </label>
                        <select name="payment_method"
                                class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                            <option value="cash"          @selected(old('payment_method') === 'cash')>Cash</option>
                            <option value="bank_transfer" @selected(old('payment_method') === 'bank_transfer')>Bank Transfer</option>
                            <option value="pos"           @selected(old('payment_method') === 'pos')>POS Terminal</option>
                        </select>
                        @error('payment_method') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>
                    <div>
                        <label class="mb-1 block text-sm font-medium text-gray-700">
                            Status <span class="text-red-500">*</span>
                        </label>
                        <select name="payment_status" x-model="payStatus"
                                class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                            <option value="paid"    @selected(old('payment_status', 'paid') === 'paid')>Paid in Full</option>
                            <option value="partial" @selected(old('payment_status') === 'partial')>Partial Payment</option>
                            <option value="pending" @selected(old('payment_status') === 'pending')>Pending</option>
                        </select>
                        @error('payment_status') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                    </div>
                </div>

                <div x-show="payStatus === 'partial'" x-cloak>
                    <label class="mb-1 block text-sm font-medium text-gray-700">
                        Amount Received <span class="text-red-500">*</span>
                    </label>
                    <div class="flex">
                        <span class="inline-flex items-center rounded-l-lg border border-r-0 border-gray-300 bg-gray-50 px-3 text-sm font-medium text-gray-600">₦</span>
                        <input type="number" name="amount_received_naira"
                               value="{{ old('amount_received_naira') }}"
                               step="0.01" min="0" placeholder="0.00"
                               class="w-full rounded-r-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                    </div>
                    @error('amount_received_naira') <p class="mt-1 text-xs text-red-600">{{ $message }}</p> @enderror
                </div>
            </div>

            {{-- ════════════════════════════════════════════════════
                 SECTION 4 · EXTRA
            ════════════════════════════════════════════════════ --}}
            <div class="space-y-4 p-6">

                <div class="flex items-center gap-2 mb-1">
                    <div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gray-100">
                        <svg class="h-4 w-4 text-gray-500" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z"/>
                        </svg>
                    </div>
                    <h3 class="text-sm font-semibold text-gray-800">Additional Info</h3>
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700">Notes</label>
                    <textarea name="notes" rows="2"
                              placeholder="Optional notes printed on the invoice…"
                              class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">{{ old('notes') }}</textarea>
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700">Sales Agent</label>
                    @if(auth()->user()->isAdmin())
                        <select name="sale_agent_id"
                                class="w-full rounded-lg border border-gray-300 text-sm shadow-sm focus:border-primary-500 focus:ring-primary-500">
                            @foreach($agents as $agent)
                                <option value="{{ $agent->id }}" @selected(old('sale_agent_id', auth()->id()) == $agent->id)>
                                    {{ $agent->name }}@if($agent->id === auth()->id()) (you)@endif
                                </option>
                            @endforeach
                        </select>
                    @else
                        <input type="hidden" name="sale_agent_id" value="{{ auth()->id() }}">
                        <div class="flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700">
                            <div class="flex h-6 w-6 items-center justify-center rounded-full bg-primary-100 text-xs font-bold text-primary-700">
                                {{ strtoupper(substr(auth()->user()->name, 0, 1)) }}
                            </div>
                            {{ auth()->user()->name }}
                        </div>
                    @endif
                </div>
            </div>

            {{-- ── SUBMIT ── --}}
            <div class="flex items-center gap-4 px-6 py-5">
                <button type="submit"
                        class="inline-flex items-center gap-2 rounded-lg bg-primary-600 px-6 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2">
                    <svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Create Invoice
                </button>
                <a href="{{ route('sales.index') }}" class="text-sm text-gray-500 hover:text-gray-700">Cancel</a>
            </div>

        </form>
    </div>
</x-app-layout>

@push('head')
<style>[x-cloak]{display:none!important}</style>
@endpush

@push('scripts')
<script>
function onCustomerChange(select) {
    var opt  = select.options[select.selectedIndex];
    var info = document.getElementById('cust-info');

    if (!opt || !opt.value) {
        info.style.display = 'none';
        return;
    }

    var name  = opt.text.split('  ·  ')[0].trim();
    var phone = opt.getAttribute('data-phone') || '';
    var addr  = opt.getAttribute('data-address') || '';

    var initials = name.replace(/[^a-zA-Z]/g, '').substring(0, 2).toUpperCase() || '?';

    document.getElementById('cust-avatar').textContent    = initials;
    document.getElementById('cust-info-name').textContent = name;
    document.getElementById('cust-info-phone').textContent = phone;
    document.getElementById('billing_address').value      = addr;

    info.style.display = '';
}

document.addEventListener('DOMContentLoaded', function () {
    var sel = document.getElementById('customer_id');
    if (sel && sel.value) {
        onCustomerChange(sel);
    }
});

function invoiceForm() {
    return {
        qty:       {{ old('quantity_kg', 'null') }},
        price:     {{ old('price_per_kg_naira', 'null') }},
        payStatus: '{{ old('payment_status', 'paid') }}',
    };
}
</script>
@endpush
