@extends('layouts.aura-main')

@section('main-content')
<div class="pb-20 max-w-6xl mx-auto" x-data="invoiceManager()">
    <div class="fixed top-5 right-5 z-[100] space-y-3 w-80">
        {{-- Laravel Validation Errors --}}
        @if ($errors->any())
            <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 8000)" 
                 class="bg-rose-50 border-l-4 border-rose-500 p-4 shadow-xl rounded-sm transition-all duration-300">
                <div class="flex justify-between items-start">
                    <p class="text-[11px] font-bold text-rose-700 uppercase">Validation Failed</p>
                    <button @click="show = false" class="text-rose-400 hover:text-rose-600">&times;</button>
                </div>
                <ul class="mt-2 list-disc list-inside text-[10px] text-rose-600 font-medium">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        {{-- Manual Session Errors (from the Controller catch block) --}}
        @if (session('error'))
            <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 8000)" 
                 class="bg-amber-50 border-l-4 border-amber-500 p-4 shadow-xl rounded-sm">
                <div class="flex justify-between">
                    <p class="text-[11px] font-bold text-amber-700 uppercase">System Error</p>
                    <button @click="show = false" class="text-amber-400 hover:text-amber-600">&times;</button>
                </div>
                <p class="mt-1 text-[10px] text-amber-600 font-medium">{{ session('error') }}</p>
            </div>
        @endif
    </div>
    
    
    <form action="{{ route('invoices.store') }}" method="POST" id="invoiceForm">
        @csrf
        
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-2xl font-black text-slate-900 tracking-tight">New Sales Invoice</h1>
                <p class="text-[12px] font-medium text-slate-500">Record revenue and recognize customer debt</p>
            </div>
            <div class="flex gap-3">
                <a href="{{ route('invoices.index') }}" class="px-4 py-2 text-[13px] font-semibold text-slate-400 hover:text-slate-600 transition">Cancel</a>
                <button type="submit" name="action" value="draft" class="bg-white border border-slate-300 text-slate-600 px-6 py-2 rounded-sm text-[13px] font-bold shadow-sm hover:bg-slate-50 transition">
                    Save as draft
                </button>
                <button type="submit" name="action" value="post" class="bg-indigo-600 text-white px-6 py-2 rounded-sm text-[13px] font-bold shadow-lg hover:bg-indigo-700 transition">
                    Post invoice
                </button>
            </div>
        </div>

        <div class="bg-white border border-slate-300 rounded-sm shadow-sm p-8 mb-6">
            <div class="flex items-center gap-2 mb-6 border-b border-slate-100 pb-4">
                <div class="w-1 h-4 bg-indigo-500 rounded-full"></div>
                <h2 class="text-[10px] font-bold text-slate-500 uppercase tracking-wider">Header information</h2>
            </div>
            
            <div class="grid grid-cols-3 gap-8">
                <div>
                    <label class="block text-[10px] font-bold text-indigo-600 uppercase mb-1 tracking-wider font-black">Customer account</label>
                    <select name="customer_id" required class="w-full border border-indigo-200 rounded px-3 py-2 text-xs focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none shadow-sm bg-white font-semibold">
                        <option value="">-- Select customer --</option>
                        @foreach($customers as $customer)
                            <option value="{{ $customer->id }}">{{ $customer->name }} (TPIN: {{ $customer->tpin ?? 'N/A' }})</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-span-2 grid grid-cols-3 gap-4">
                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Invoice #</label>
                        <input type="text" name="invoice_no" value="{{ $invoiceNo }}" readonly class="w-full border border-slate-300 bg-slate-50 rounded px-3 py-2 text-xs font-mono font-bold text-indigo-600 cursor-not-allowed">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Invoice date</label>
                        <input type="date" name="invoice_date" value="{{ date('Y-m-d') }}" required class="w-full border border-slate-300 rounded px-3 py-2 text-xs focus:border-indigo-500 outline-none shadow-sm">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Due date</label>
                        <input type="date" name="due_date" value="{{ date('Y-m-d', strtotime('+14 days')) }}" required class="w-full border border-slate-300 rounded px-3 py-2 text-xs focus:border-indigo-500 outline-none shadow-sm">
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-white border border-slate-300 rounded-sm shadow-sm overflow-hidden mb-6">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-300 text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                        <th class="px-4 py-3 w-12 text-center border-r border-slate-200">#</th>
                        <th class="px-4 py-3 w-1/3 border-r border-slate-200">Product / Service</th>
                        <th class="px-4 py-3 w-20 text-center border-r border-slate-200">Qty</th>
                        <th class="px-4 py-3 w-36 text-right border-r border-slate-200">Unit Price</th>
                        <th class="px-4 py-3 w-36 text-right border-r border-slate-200">Before Tax</th>
                        <th class="px-4 py-3 w-24 text-center border-r border-slate-200">Tax (%)</th>
                        <th class="px-4 py-3 text-right">Line Total</th>
                        <th class="px-4 py-3 w-12 text-center"></th>
                    </tr>
                </thead>
                
                
               <tbody>
    <template x-for="(item, index) in items" :key="index">
        <tr class="border-b border-slate-100 hover:bg-slate-50/50 transition group">
            
            <input type="hidden" :name="`items[${index}][product_id]`" x-model="item.product_id">
            <input type="hidden" :name="`items[${index}][qty]`" x-model="item.qty">
            <input type="hidden" :name="`items[${index}][price]`" x-model="item.price">
            <input type="hidden" :name="`items[${index}][tax_rate]`" x-model="item.tax_rate">

            <td class="px-4 py-3 text-center text-slate-400 font-mono text-[10px] border-r border-slate-100 bg-slate-50/30" x-text="index + 1"></td>
            
            <td class="px-2 py-1 border-r border-slate-100">
                <select x-model="item.product_id"
                        @change="updateLineFromProduct(index, $event)"
                        required 
                        class="w-full bg-transparent border-none focus:ring-1 focus:ring-indigo-500 rounded-sm text-xs py-1.5 font-bold text-slate-700 outline-none">
                    <option value="">Choose product...</option>
                    @foreach($products as $product)
                        <option value="{{ $product->id }}" 
                                data-price="{{ $product->sales_price }}" 
                                data-tax="{{ $product->tax_category == 'standard' ? 16 : 0 }}">
                            {{ $product->name }}
                        </option>
                    @endforeach
                </select>
            </td>

            <td class="px-2 py-1 border-r border-slate-100">
                <input type="number" step="0.01" x-model.number="item.qty" @input="calculateLine(index)" class="w-full bg-transparent border-none text-center text-xs py-1.5 focus:ring-0 outline-none font-medium">
            </td>

            <td class="px-2 py-1 border-r border-slate-100">
                <input type="number" step="0.01" x-model.number="item.price" @input="calculateLine(index)" class="w-full bg-transparent border-none text-right text-xs py-1.5 focus:ring-0 outline-none font-mono">
            </td>

            <td class="px-4 py-3 border-r border-slate-100 text-right text-xs font-mono text-slate-500 bg-slate-50/30" x-text="formatNumber(item.subtotal)"></td>

            <td class="px-2 py-1 border-r border-slate-100">
                <select x-model.number="item.tax_rate" @change="calculateLine(index)" class="w-full bg-transparent border-none text-center text-[10px] py-1.5 focus:ring-0 outline-none font-bold">
                    <option value="0">0%</option>
                    <option value="16">16%</option>
                </select>
            </td>

            <td class="px-4 py-3 text-right text-xs font-mono font-bold text-slate-900 bg-indigo-50/30" x-text="formatNumber(item.total)"></td>
            
            <td class="px-2 py-1 text-center">
                <button type="button" @click="removeItem(index)" class="text-slate-300 hover:text-rose-500 transition">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                </button>
            </td>
        </tr>
    </template>
</tbody>
            
            
            </table>

            <div class="p-4 bg-slate-50 border-t border-slate-300 flex justify-between items-start">
                <button type="button" @click="addItem()" class="bg-white border border-slate-300 px-4 py-1.5 rounded text-[10px] font-bold uppercase text-slate-600 hover:bg-slate-100 transition shadow-sm flex items-center gap-2 tracking-tighter">
                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                    Add Line Item
                </button>
                
                <div class="w-72 space-y-2">
                    <div class="flex justify-between text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                        <span>Subtotal</span>
                        <span class="font-mono" x-text="formatNumber(subtotal)"></span>
                    </div>
                    <div class="flex justify-between text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                        <span>VAT (16%)</span>
                        <span class="font-mono" x-text="formatNumber(taxTotal)"></span>
                    </div>
                    <div class="flex justify-between pt-3 border-t border-slate-200 items-baseline">
                        <span class="text-[11px] font-black text-slate-900 uppercase tracking-widest">Grand Total</span>
                        <p class="text-2xl font-mono font-black text-indigo-600">
                            K<span x-text="formatNumber(grandTotal)"></span>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <div class="max-w-xl bg-white border border-slate-300 rounded-sm p-4 shadow-sm">
            <label class="block text-[10px] font-bold text-slate-500 uppercase mb-2 tracking-widest">Internal Memo / Remarks</label>
            <textarea name="memo" rows="3" class="w-full border border-slate-200 rounded p-3 text-xs italic focus:border-indigo-500 outline-none shadow-sm transition" placeholder="Internal notes for this invoice..."></textarea>
        </div>
    </form>
</div>

<script>
function invoiceManager() {
    return {
        items: [{ product_id: '', qty: 1, price: 0, subtotal: 0, tax_rate: 0, total: 0 }],
        subtotal: 0, taxTotal: 0, grandTotal: 0,
        addItem() { this.items.push({ product_id: '', qty: 1, price: 0, subtotal: 0, tax_rate: 0, total: 0 }); },
        removeItem(index) { if(this.items.length > 1) { this.items.splice(index, 1); this.calculateTotals(); } },
        updateLineFromProduct(index) {
            const select = event.target;
            const option = select.options[select.selectedIndex];
            if (option.value) {
                this.items[index].price = parseFloat(option.dataset.price) || 0;
                this.items[index].tax_rate = (option.dataset.tax === 'standard') ? 16 : 0;
                this.calculateLine(index);
            }
        },
        calculateLine(index) {
            let item = this.items[index];
            item.subtotal = item.qty * item.price;
            item.total = item.subtotal + (item.subtotal * (item.tax_rate / 100));
            this.calculateTotals();
        },
        calculateTotals() {
            this.subtotal = this.items.reduce((sum, i) => sum + i.subtotal, 0);
            this.taxTotal = this.items.reduce((sum, i) => sum + (i.subtotal * (i.tax_rate / 100)), 0);
            this.grandTotal = this.subtotal + this.taxTotal;
        },
        formatNumber(val) { return new Intl.NumberFormat('en-ZM', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(val); }
    }
}
</script>
@endsection