@extends('layouts.app')

@php
    $editMode = isset($purchase);
    $title = $editMode ? "Edit Purchase {$purchase->voucher_no}" : 'Purchase Entry';
    $subtitle = $editMode ? "Update purchase information" : 'Create a new purchase from supplier';
    $formAction = $editMode ? route('purchase.update', $purchase->id) : route('purchase.store');
    $formMethod = $editMode ? 'PUT' : 'POST';
    $purchaseDate = $editMode ? $purchase->purchase_date->format('Y-m-d') : now()->format('Y-m-d');
    $invNo = $editMode ? $purchase->invoice_no : '';
    $partyId = $editMode ? $purchase->party_id : '';
    $labourCharge = $editMode ? $purchase->labour_charge : 0;
    $carRent = $editMode ? $purchase->car_rent : 0;
    $remarks = $editMode ? $purchase->remarks : '';
    $paidAmount = $editMode ? $purchase->paid_amount : 0;
    $itemsJson = json_encode($items ?? []);
    $suppliersArray = $suppliers->map(fn ($s) => [
        'id' => $s->id,
        'name' => $s->name,
        'phone' => $s->phone,
        'address' => $s->address ?? '',
        'email' => $s->email ?? '',
        'total_purchase' => $s->total_purchase,
        'opening_balance' => $s->opening_balance,
        'credit_limit' => $s->credit_limit,
    ])->values();
    $suppliersJson = json_encode($suppliersArray);
@endphp

@section('title', $title)

@section('breadcrumb')
    @include('components.breadcrumb', ['items' => ['Purchase' => route('purchase.index'), $editMode ? "Edit {$purchase->voucher_no}" : 'Purchase Entry' => null]])
@endsection

@section('content')
<div x-data='purchaseForm({!! $itemsJson !!}, {!! $suppliersJson !!})'>
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
            <h1 class="text-2xl font-bold text-slate-900 dark:text-white">{{ $title }}</h1>
            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">{{ $subtitle }}</p>
        </div>
        <x-button variant="secondary" icon="history" :href="route('purchase.index')">All Purchases</x-button>
    </div>

    <form action="{{ $formAction }}" method="POST">
        @csrf
        @if($editMode) @method('PUT') @endif

        <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
            <div class="xl:col-span-2 space-y-6">

                {{-- Purchase Info --}}
                <x-card title="Purchase Information" icon="file-text">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
                        <x-form-input name="purchase_date" label="Purchase Date" type="date" icon="calendar" :value="old('purchase_date', $purchaseDate)" required />
                        <x-form-input name="invoice_no" label="Invoice No" icon="hash" :value="old('invoice_no', $invNo)" placeholder="INV-001" />
                        <div class="form-group relative">
                            <i data-lucide="truck" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 z-10 pointer-events-none"></i>
                            <select name="party_id" x-model="partyId" required
                                class="peer w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-sm text-slate-900 dark:text-white pl-10 pr-3.5 pt-5 pb-2 transition focus:ring-2 focus:ring-primary-500 focus:border-primary-500">
                                <option value="">Select Supplier</option>
                                @foreach($suppliers as $s)
                                    <option value="{{ $s->id }}">{{ $s->name }}</option>
                                @endforeach
                            </select>
                            <label class="absolute left-10 top-3.5 text-sm text-slate-500 dark:text-slate-400 transition-all pointer-events-none origin-left peer-focus:-translate-y-3 peer-focus:scale-75 peer-focus:text-primary-600 peer-[:not(:placeholder-shown)]:-translate-y-3 peer-[:not(:placeholder-shown)]:scale-75">
                                Supplier <span class="text-red-500">*</span>
                            </label>
                        </div>
                        <x-form-input name="account_id" label="Payment Account" type="select" icon="landmark" :options="['' => 'Select Account'] + \App\Models\Account::active()->pluck('name','id')->toArray()" :value="old('account_id', '')" />
                    </div>
                </x-card>

                {{-- Items --}}
                <x-card title="Purchase Items" icon="package" :padding="false">
                    <x-slot:headerActions>
                        <x-button variant="primary" size="sm" icon="plus" type="button" @click="addRow()">Add Row</x-button>
                    </x-slot:headerActions>
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead>
                                <tr class="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-200 dark:border-slate-800">
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500 w-10">#</th>
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Yarn</th>
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase tracking-wider text-slate-500">Lot No</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Bags</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Qty (kg)</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Rate</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase tracking-wider text-slate-500">Amount</th>
                                    <th class="px-3 py-3 w-10"></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                                <template x-for="(row, idx) in rows" :key="idx">
                                    <tr class="hover:bg-slate-50/50">
                                        <td class="px-3 py-2 text-xs text-slate-500 text-center" x-text="idx + 1"></td>
                                        <td class="px-2 py-2">
                                            <select :name="`items[${idx}][yarn_id]`" x-model="row.yarn_id" @change="calcRow(idx)" required
                                                class="w-full px-2 py-1.5 text-sm bg-transparent border-0 focus:ring-2 focus:ring-primary-500 rounded-lg dark:bg-slate-800">
                                                <option value="">Select Yarn</option>
                                                @foreach($yarns as $yarn)
                                                    <option value="{{ $yarn->id }}">{{ $yarn->name }} ({{ $yarn->code }})</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td class="px-2 py-2">
                                            <input type="text" :name="`items[${idx}][lot_no]`" x-model="row.lot_no"
                                                class="w-24 px-2 py-1.5 text-sm bg-transparent border-0 focus:ring-2 focus:ring-primary-500 rounded-lg dark:bg-slate-800"
                                                placeholder="L-001" />
                                        </td>
                                        <td class="px-2 py-2">
                                            <input type="number" :name="`items[${idx}][bags]`" x-model.number="row.bags" @input="calcRow(idx)" min="0"
                                                class="w-20 px-2 py-1.5 text-sm text-right bg-transparent border-0 focus:ring-2 focus:ring-primary-500 rounded-lg dark:bg-slate-800" />
                                        </td>
                                        <td class="px-2 py-2">
                                            <input type="number" step="0.01" :name="`items[${idx}][quantity]`" x-model.number="row.qty" @input="calcRow(idx)" min="0.01" required
                                                class="w-24 px-2 py-1.5 text-sm text-right bg-transparent border-0 focus:ring-2 focus:ring-primary-500 rounded-lg dark:bg-slate-800" />
                                        </td>
                                        <td class="px-2 py-2">
                                            <input type="number" step="0.01" :name="`items[${idx}][rate]`" x-model.number="row.rate" @input="calcRow(idx)" min="0.01" required
                                                class="w-24 px-2 py-1.5 text-sm text-right bg-transparent border-0 focus:ring-2 focus:ring-primary-500 rounded-lg dark:bg-slate-800" />
                                        </td>
                                        <td class="px-3 py-2 text-right font-bold text-sm text-slate-900 dark:text-white counter-num">
                                            ৳<span x-text="row.amount.toLocaleString('en-BD', {minimumFractionDigits:2})"></span>
                                        </td>
                                        <td class="px-2 py-2 text-center">
                                            <button type="button" @click="removeRow(idx)" class="text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 p-1 rounded">
                                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                    <div class="px-4 py-3 border-t border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/30">
                        <button type="button" @click="addRow()" class="text-xs font-semibold text-primary-600 hover:text-primary-700 flex items-center gap-1.5">
                            <i data-lucide="plus-circle" class="w-4 h-4"></i> Add another row
                        </button>
                    </div>
                </x-card>

                {{-- Charges --}}
                <x-card title="Additional Charges" icon="receipt">
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-5">
                        <x-form-input name="labour_charge" label="Labour Charge" type="number" icon="hammer" :value="old('labour_charge', $labourCharge)" />
                        <x-form-input name="car_rent" label="Car Rent" type="number" icon="truck" :value="old('car_rent', $carRent)" />
                        <x-form-input name="paid_amount" label="Advance Paid" type="number" icon="circle-dollar-sign" :value="old('paid_amount', $paidAmount)" />
                    </div>
                    <div class="mt-5">
                        <x-form-input name="remarks" label="Remarks" type="textarea" icon="message-square" :value="old('remarks', $remarks)" />
                    </div>
                </x-card>

                {{-- Actions --}}
                <div class="flex flex-wrap items-center gap-3 justify-end">
                    <x-button variant="secondary" icon="refresh-ccw" type="reset">Reset</x-button>
                    <x-button variant="outline" icon="x" :href="route('purchase.index')">Cancel</x-button>
                    @if($editMode)
                        <x-button variant="primary" icon="save" type="submit">Update Purchase</x-button>
                    @else
                        <x-button variant="primary" icon="save" type="submit">Save Purchase</x-button>
                    @endif
                </div>
            </div>

            {{-- Live Summary --}}
            <div class="space-y-6">
                <x-card title="Live Summary" icon="calculator">
                    <div class="space-y-3 text-sm">
                        <div class="flex items-center justify-between pb-2">
                            <span class="text-slate-500">Total Items</span>
                            <span class="font-semibold counter-num" x-text="rows.length"></span>
                        </div>
                        <div class="flex items-center justify-between pb-2">
                            <span class="text-slate-500">Total Bags</span>
                            <span class="font-semibold counter-num" x-text="totalBags().toLocaleString()"></span>
                        </div>
                        <div class="flex items-center justify-between pb-2">
                            <span class="text-slate-500">Total Quantity</span>
                            <span class="font-semibold counter-num" x-text="totalQty().toLocaleString() + ' kg'"></span>
                        </div>
                        <div class="border-t border-slate-200 dark:border-slate-800 pt-3 space-y-2">
                            <div class="flex justify-between">
                                <span class="text-slate-500">Subtotal</span>
                                <span class="font-semibold counter-num">৳<span x-text="subtotal().toLocaleString('en-BD')"></span></span>
                            </div>
                        </div>
                        <div class="border-t-2 border-dashed border-slate-300 pt-3 flex justify-between">
                            <span class="text-base font-bold text-slate-900 dark:text-white">Grand Total</span>
                            <span class="text-2xl font-bold text-primary-600 dark:text-primary-400 counter-num">৳<span x-text="grandTotal().toLocaleString('en-BD')"></span></span>
                        </div>
                    </div>
                </x-card>

                <x-card title="Supplier Info" icon="building-2" x-show="selectedSupplier">
                    <template x-if="selectedSupplier">
                        <div class="space-y-3">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-xl bg-primary-100 dark:bg-primary-500/15 flex items-center justify-center font-bold text-primary-700 dark:text-primary-300 text-sm" x-text="selectedSupplier.name.substring(0,2).toUpperCase()"></div>
                                <div>
                                    <p class="text-sm font-semibold text-slate-900 dark:text-white" x-text="selectedSupplier.name"></p>
                                    <p class="text-xs text-slate-500" x-text="selectedSupplier.phone"></p>
                                </div>
                            </div>
                            <div class="space-y-1.5 text-xs">
                                <div class="flex justify-between"><span class="text-slate-500">Email</span><span class="font-semibold" x-text="selectedSupplier.email || 'N/A'"></span></div>
                                <div class="flex justify-between"><span class="text-slate-500">Address</span><span class="font-semibold" x-text="selectedSupplier.address || 'N/A'"></span></div>
                                <div class="flex justify-between"><span class="text-slate-500">Total Purchases</span><span class="font-semibold text-primary-600">৳<span x-text="Number(selectedSupplier.total_purchase).toLocaleString()"></span></span></div>
                                <div class="flex justify-between"><span class="text-slate-500">Credit Limit</span><span class="font-semibold">৳<span x-text="Number(selectedSupplier.credit_limit).toLocaleString()"></span></span></div>
                            </div>
                        </div>
                    </template>
                    <p x-show="!selectedSupplier" class="text-xs text-slate-500">Please select a supplier to see info.</p>
                </x-card>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
function purchaseForm(existingRows = [], suppliers = []) {
    const defaultRows = existingRows.length > 0
        ? existingRows.map(r => ({
            yarn_id: r.yarn_id || '',
            lot_no: r.lot_no || '',
            bags: Number(r.bags) || 0,
            qty: Number(r.quantity) || Number(r.qty) || 0,
            rate: Number(r.rate) || 0,
            amount: Number(r.amount) || 0,
          }))
        : [{ yarn_id: '', lot_no: '', bags: 0, qty: 0, rate: 0, amount: 0 }];

    const initPartyId = defaultRows.length > 0 ? '' : '';
    @if($editMode)
    const initParty = suppliers.find(s => s.id == {{ $partyId }}) || null;
    @else
    const initParty = null;
    @endif

    return {
        rows: defaultRows,
        partyId: {{ $partyId ?? 'null' }} || null,
        selectedSupplier: initParty,
        get suppliers() { return suppliers; },
        init() {
            this.$watch('partyId', (val) => {
                this.selectedSupplier = suppliers.find(s => s.id == val) || null;
            });
        },
        addRow() {
            this.rows.push({ yarn_id: '', lot_no: '', bags: 0, qty: 0, rate: 0, amount: 0 });
            this.$nextTick(() => lucide.createIcons());
        },
        removeRow(idx) {
            if (this.rows.length > 1) this.rows.splice(idx, 1);
        },
        calcRow(idx) {
            this.rows[idx].amount = (Number(this.rows[idx].qty) || 0) * (Number(this.rows[idx].rate) || 0);
        },
        totalBags() { return this.rows.reduce((s, r) => s + (Number(r.bags) || 0), 0); },
        totalQty() { return this.rows.reduce((s, r) => s + (Number(r.qty) || 0), 0); },
        subtotal() { return this.rows.reduce((s, r) => s + (Number(r.amount) || 0), 0); },
        grandTotal() { return this.subtotal(); }
    }
}
</script>
@endpush
