@extends('layouts.aura-main')

@section('main-content')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div x-data="expenseForm()" class="max-w-6xl mx-auto pb-20">
    
    @if ($errors->any())
        <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-4 shadow-sm">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="ml-3">
                    <h3 class="text-sm font-bold text-red-800 uppercase tracking-tight">Validation Errors Found</h3>
                    <div class="mt-1 text-xs text-red-700">
                        <ul class="list-disc pl-5 space-y-1">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    @endif

    <form id="editExpenseForm" action="{{ route('suppliers.expenses.update', $expense->id) }}" method="POST" @submit.prevent="validateAndSubmit">
        @csrf
        @method('PUT')
        
        <input type="hidden" name="status" x-model="status">
        
        <div class="bg-white border border-slate-300 rounded-sm shadow-sm mb-6">
            <div class="p-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
                <div class="flex items-center gap-4">
                    <h1 class="text-lg font-bold text-slate-800 tracking-tight">Edit Expense</h1>
                    <div class="flex items-center gap-2">
                        <template x-if="status === 'draft'">
                            <span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-tighter border border-amber-200">Draft Mode</span>
                        </template>
                        <template x-if="status === 'posted'">
                            <span class="bg-emerald-100 text-emerald-700 px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-tighter border border-emerald-200">Posted Entry</span>
                        </template>
                        <span class="text-slate-400 text-[10px] font-mono italic">#{{ $expense->reference_no ?? $expense->id }}</span>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    <a href="{{ route('suppliers.expenses.index') }}" class="text-[11px] font-bold text-slate-400 uppercase hover:text-slate-600 transition">Cancel</a>
                    
                    <button type="submit" @click="status = 'draft'" class="bg-white border border-slate-300 text-slate-600 px-4 py-2 rounded text-[11px] font-bold shadow-sm hover:bg-slate-50 transition uppercase tracking-tighter">
                        Save as Draft
                    </button>

                    <button type="submit" @click="status = 'posted'" class="bg-indigo-600 text-white px-6 py-2 rounded text-[11px] font-bold shadow-sm hover:bg-indigo-700 transition uppercase tracking-tighter">
                        Update & Post
                    </button>
                </div>
            </div>

            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-5 gap-6">
                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Payee (Supplier)</label>
                        <select name="supplier_id" class="w-full border border-slate-300 rounded px-3 py-2 text-xs focus:border-indigo-500 outline-none shadow-sm bg-white">
                            <option value="">Select a Supplier...</option>
                            @foreach($suppliers as $supplier)
                                <option value="{{ $supplier->id }}" {{ $expense->supplier_id == $supplier->id ? 'selected' : '' }}>
                                    {{ $supplier->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-indigo-600 uppercase mb-1 tracking-wider font-black">Payment Account</label>
                        <select name="bank_account_id" id="bank_account_id" 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" required>
                            <option value="">Select Bank/Cash...</option>
                            @foreach($paymentAccounts as $pAccount)
                                <option value="{{ $pAccount->id }}" {{ $expense->bank_account_id == $pAccount->id ? 'selected' : '' }}>
                                    {{ $pAccount->name }} ({{ $pAccount->code }})
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
    <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">
        Payment Date
    </label>
    <input type="date" 
           name="payment_date" 
           value="{{ old('payment_date', $expense->payment_date ? \Carbon\Carbon::parse($expense->payment_date)->format('Y-m-d') : '') }}" 
           class="w-full border border-slate-300 rounded px-3 py-2 text-xs focus:border-indigo-500 outline-none shadow-sm bg-white" 
           required>
    @error('payment_date')
        <p class="text-[10px] text-rose-600 font-bold mt-1">{{ $message }}</p>
    @enderror
</div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Method</label>
                        <select name="payment_method" class="w-full border border-slate-300 rounded px-3 py-2 text-xs focus:border-indigo-500 outline-none shadow-sm">
                            <option value="Bank Transfer" {{ $expense->payment_method == 'Bank Transfer' ? 'selected' : '' }}>Bank Transfer</option>
                            <option value="Cash" {{ $expense->payment_method == 'Cash' ? 'selected' : '' }}>Cash</option>
                            <option value="Mobile Money" {{ $expense->payment_method == 'Mobile Money' ? 'selected' : '' }}>Mobile Money</option>
                            <option value="Cheque" {{ $expense->payment_method == 'Cheque' ? 'selected' : '' }}>Cheque</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-[10px] font-bold text-slate-500 uppercase mb-1 tracking-wider">Ref no.</label>
                        <input type="text" name="reference_no" value="{{ $expense->reference_no }}" 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">
            <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">
                        <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">Expense Category (Debit Account)</th>
                        <th class="px-4 py-3 border-r border-slate-200">Description</th>
                        <th class="px-4 py-3 w-40 text-right border-r border-slate-200">Amount</th>
                        <th class="px-4 py-3 w-20 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="(row, index) in rows" :key="index">
                        <tr class="border-b border-slate-100 hover:bg-slate-50/50 transition group">
                            <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 :name="`items[${index}][account_id]`" 
                                        x-model="row.account_id" 
                                        class="w-full bg-transparent border-none focus:ring-2 focus:ring-indigo-500/20 rounded-sm text-xs py-1.5 font-medium text-slate-700 outline-none transition" 
                                        required>
                                    <option value="">Choose Category...</option>
                                    @foreach($expenseAccounts as $eAccount)
                                        <option value="{{ $eAccount->id }}">{{ $eAccount->name }} ({{ $eAccount->code }})</option>
                                    @endforeach
                                </select>
                            </td>

                            <td class="px-2 py-1 border-r border-slate-100">
                                <input type="text" 
                                       :name="`items[${index}][description]`" 
                                       x-model="row.description" 
                                       placeholder="Line details..." 
                                       class="w-full bg-transparent border-none focus:ring-2 focus:ring-indigo-500/20 rounded-sm text-xs py-1.5 outline-none transition">
                            </td>

                            <td class="px-2 py-1 border-r border-slate-100">
                                <input type="number" 
                                       step="0.01" 
                                       :name="`items[${index}][amount]`" 
                                       x-model.number="row.amount" 
                                       @input="calculateTotal()" 
                                       class="w-full bg-transparent border-none focus:ring-2 focus:ring-indigo-500/20 rounded-sm text-xs py-1.5 text-right font-mono font-bold outline-none transition">
                            </td>

                            <td class="px-2 py-1 text-center flex items-center justify-center gap-2">
                                <button type="button" @click="duplicateRow(index)" title="Duplicate Line" class="text-slate-300 hover:text-indigo-500 transition-colors mt-1.5">
                                    <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="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2"></path></svg>
                                </button>
                                <button type="button" @click="removeRow(index)" class="text-slate-300 hover:text-red-500 transition-colors mt-1.5">
                                    <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 flex justify-between items-center">
                <button type="button" @click="addRow()" 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">
                    <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
                </button>
                
                <div class="text-right">
                    <p class="text-[9px] font-bold text-slate-400 uppercase tracking-widest mb-1">Updated Total Value</p>
                    <p class="text-2xl font-mono font-bold text-slate-900" x-text="formatCurrency(total)"></p>
                    <input type="hidden" name="total_amount" :value="total">
                </div>
            </div>
        </div>

        <div class="mt-6 flex gap-6">
            <div class="w-full md:w-1/2 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">Overall Memo / Remarks</label>
                <textarea name="memo" rows="3" class="w-full border border-slate-200 rounded p-3 text-xs focus:border-indigo-500 outline-none shadow-sm transition">{{ $expense->memo }}</textarea>
            </div>
            
            <div class="w-full md:w-1/2 p-4 text-[11px] text-slate-400 italic">
                Last modified: {{ $expense->updated_at->format('d M Y, H:i') }}
            </div>
        </div>
    </form>
</div>

<script>
function expenseForm() {
    return {
        rows: @json($expense->items->map(fn($item) => [
            'account_id' => $item->account_id,
            'description' => $item->description,
            'amount' => $item->amount
        ])),
        total: {{ (float)$expense->total_amount }},
        status: '{{ $expense->status }}',
        
        // Custom Validation and Submit logic
        validateAndSubmit() {
            // 1. Check Payment Account (The cause of your account_id is null error)
            const paymentAccount = document.getElementById('bank_account_id').value;
            if (!paymentAccount && this.status === 'posted') {
                return Swal.fire({
                    icon: 'warning',
                    title: 'Payment Account Missing',
                    text: 'You must select a Bank/Cash account before posting to the ledger.',
                    confirmButtonColor: '#6366f1',
                });
            }

            // 2. Check Line Items
            let hasEmptyCategory = this.rows.some(row => !row.account_id);
            let hasZeroAmount = this.rows.some(row => parseFloat(row.amount) <= 0);

            if (hasEmptyCategory) {
                return Swal.fire('Missing Category', 'Please select an expense category for all lines.', 'warning');
            }
            if (hasZeroAmount) {
                return Swal.fire('Invalid Amount', 'All lines must have an amount greater than zero.', 'warning');
            }

            // 3. Submit if all pass
            document.getElementById('editExpenseForm').submit();
        },

        addRow() {
            this.rows.push({ account_id: '', description: '', amount: 0 });
        },
        duplicateRow(index) {
            const original = this.rows[index];
            this.rows.push({ 
                account_id: original.account_id, 
                description: original.description, 
                amount: original.amount 
            });
            this.calculateTotal();
        },
        removeRow(index) {
            if (this.rows.length > 1) {
                this.rows.splice(index, 1);
            }
            this.calculateTotal();
        },
        calculateTotal() {
            this.total = this.rows.reduce((sum, row) => sum + (parseFloat(row.amount) || 0), 0);
        },
        formatCurrency(val) {
            return new Intl.NumberFormat('en-ZM', { 
                style: 'currency', 
                currency: 'ZMW' 
            }).format(val);
        }
    }
}
</script>
@endsection