@extends('layouts.app')
@section('title', 'Sales Entry')
@section('breadcrumb')
    @include('components.breadcrumb', ['items' => ['Sales Management' => null, 'Sales Entry' => null]])
@endsection

@section('content')
<div x-data="saleForm()">
    <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">Sales Entry</h1>
            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Create new sales invoice</p>
        </div>
        <x-button variant="secondary" icon="history" :href="route('sales.index')">History</x-button>
    </div>

    <form action="{{ route('sales.store') }}" method="POST">
        @csrf
        <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
            <div class="xl:col-span-2 space-y-6">
                <x-card title="Customer & Invoice" icon="user">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
                        <x-form-input name="party_id" label="Customer" type="select" icon="user" :options="$customers->pluck('name','id')" required />
                        <x-form-input name="sales_date" label="Sales Date" type="date" icon="calendar" :value="old('sales_date', now()->format('Y-m-d'))" required />
                        <x-form-input name="invoice_no" label="Invoice No" icon="hash" :value="old('invoice_no')" />
                        <x-form-input name="account_id" label="Payment Account" type="select" icon="landmark" :options="['' => 'Select Account'] + \App\Models\Account::active()->pluck('name','id')->toArray()" />
                    </div>
                </x-card>

                <x-card title="Sales Items" icon="package" :padding="false">
                    <x-slot:headerActions>
                        <x-button variant="success" size="sm" icon="plus" type="button" @click="addRow()">Add Item</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">
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase text-slate-500">#</th>
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase text-slate-500">Yarn</th>
                                    <th class="px-3 py-3 text-left text-[10px] font-bold uppercase text-slate-500">Lot No</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase text-slate-500">Bags</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase text-slate-500">Qty (kg)</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase text-slate-500">Rate</th>
                                    <th class="px-3 py-3 text-right text-[10px] font-bold uppercase text-slate-500">Amount</th>
                                    <th class="px-3 py-3 w-10"></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <template x-for="(row, idx) in rows" :key="idx">
                                    <tr>
                                        <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 }}</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" /></td>
                                        <td class="px-2 py-2"><input type="number" :name="`items[${idx}][bags]`" x-model.number="row.bags" @input="calcRow(idx)" 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)" 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)" 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-emerald-600 counter-num">৳<span x-text="row.amount.toLocaleString()"></span></td>
                                        <td class="px-2 py-2 text-center"><button type="button" @click="removeRow(idx)" class="text-rose-500 hover:bg-rose-50 p-1 rounded"><i data-lucide="trash-2" class="w-4 h-4"></i></button></td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </x-card>

                <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', 0)" />
                        <x-form-input name="car_rent" label="Car Rent" type="number" icon="truck" :value="old('car_rent', 0)" />
                        <x-form-input name="paid_amount" label="Advance Received" type="number" icon="circle-dollar-sign" :value="old('paid_amount', 0)" />
                    </div>
                    <div class="mt-5"><x-form-input name="remarks" label="Remarks" type="textarea" icon="message-square" /></div>
                </x-card>

                <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('dashboard')">Cancel</x-button>
                    <x-button variant="success" icon="save" type="submit">Save Sale</x-button>
                </div>
            </div>

            <div class="space-y-6">
                <x-card title="Live Bill Summary" icon="calculator">
                    <div class="space-y-3 text-sm">
                        <div class="flex justify-between"><span class="text-slate-500">Items</span><span class="font-semibold" x-text="rows.length"></span></div>
                        <div class="flex justify-between"><span class="text-slate-500">Total Qty</span><span class="font-semibold counter-num" x-text="totalQty().toLocaleString()"></span></div>
                        <div class="border-t-2 border-dashed pt-3 flex justify-between">
                            <span class="font-bold">Grand Total</span>
                            <span class="text-2xl font-bold text-emerald-600 counter-num">৳<span x-text="grandTotal().toLocaleString()"></span></span>
                        </div>
                    </div>
                </x-card>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
function saleForm() {
    return {
        rows: [{ yarn_id: '', lot_no: '', bags: 0, qty: 0, rate: 0, amount: 0 }],
        labourCharge: 0, carRent: 0,
        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); },
        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() + this.labourCharge + this.carRent; }
    }
}
</script>
@endpush
