<x-app-layout>
    <a href="{{ route('expenses.index') }}" class="inline-flex items-center gap-1.5 text-slate-600 hover:text-slate-900 text-sm font-medium mb-3 transition duration-150">
        &larr; Back to Expenses
    </a>
    <!-- Page Header -->
    <div class="flex items-center space-x-4 mb-8">
        <div>
            <h2 class="text-2xl font-bold text-slate-800">Log Business Expense</h2>
            <p class="text-slate-500 text-sm mt-1">Record business payments, utilities, purchases, and support live currency conversions.</p>
        </div>
    </div>

    <!-- Form Container -->
    <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-6 max-w-7xl" x-data="{
        showVat: {{ old('vat_rate') ? 'true' : 'false' }},
        formAmount: '{{ old('amount', '') }}',
        vatRate: '{{ old('vat_rate') }}',
        vatInclusive: {{ old('vat_inclusive', 1) }},

        // Multi-currency details
        isForeign: false,
        originalCurrency: 'USD',
        originalAmount: '',
        exchangeRate: '1.000000',
        baseCurrency: '{{ $baseCurrencyCode }}',

        get calcNet() {
            const a = parseFloat(this.formAmount) || 0;
            if (!this.vatRate) return a.toFixed(2);
            const r = parseFloat(this.vatRate) / 100;
            return parseInt(this.vatInclusive) === 1 ? (a / (1 + r)).toFixed(2) : a.toFixed(2);
        },
        get calcVat() {
            const a = parseFloat(this.formAmount) || 0;
            if (!this.vatRate) return '0.00';
            const r = parseFloat(this.vatRate) / 100;
            return parseInt(this.vatInclusive) === 1 ? (a - (a / (1 + r))).toFixed(2) : (a * r).toFixed(2);
        },

        init() {
            this.$watch('originalAmount', () => this.recalculateBaseAmount());
            this.$watch('exchangeRate', () => this.recalculateBaseAmount());
        },

        recalculateBaseAmount() {
            if (this.isForeign) {
                const oAmt = parseFloat(this.originalAmount) || 0;
                const rate = parseFloat(this.exchangeRate) || 0;
                this.formAmount = (oAmt * rate).toFixed(2);
            }
        },

        async fetchRate() {
            const date = document.getElementById('transaction_date').value;
            if (!date) {
                alert('Please pick a transaction date first.');
                return;
            }
            try {
                let targetUrl = `{{ route('currency.fetch-rate') }}?date=${date}&from=${this.originalCurrency}`;
                let url = new URL(targetUrl, window.location.origin);
                const res = await fetch(url.pathname + url.search);
                const data = await res.json();
                if (data.success) {
                    this.exchangeRate = parseFloat(data.rate).toFixed(6);
                    this.recalculateBaseAmount();
                } else {
                    alert(data.message || 'Error fetching rate.');
                }
            } catch (e) {
                console.error(e);
                alert('Failed to contact exchange service.');
            }
        }
    }">
        <form action="{{ route('expenses.store') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
            @csrf

            <!-- Category & Date -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Expense Category <span class="text-rose-600">*</span></label>
                    <select name="category_id" required
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                        <option value="">Select Category</option>
                        @foreach($parentCategories as $parent)
                            <optgroup label="{{ $parent->name }}">
                                @foreach($parent->children as $child)
                                    <option value="{{ $child->id }}" {{ old('category_id') == $child->id ? 'selected' : '' }}>{{ $child->name }}</option>
                                @endforeach
                            </optgroup>
                        @endforeach
                    </select>
                    <x-input-error :messages="$errors->get('category_id')" class="mt-1" />
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Expense Date <span class="text-rose-600">*</span></label>
                    <input type="date" name="date" id="transaction_date" value="{{ old('date', date('Y-m-d')) }}" required
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                    <x-input-error :messages="$errors->get('date')" class="mt-1" />
                </div>
            </div>

            <!-- Multi-Currency Control Block -->
            <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-4">
                <div class="flex items-center">
                    <input type="checkbox" id="is_foreign" x-model="isForeign" name="is_foreign" class="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 h-4 w-4">
                    <label for="is_foreign" class="ml-2 text-sm font-semibold text-slate-700">{{ __('Foreign Currency Transaction') }}</label>
                </div>

                <div x-show="isForeign" x-cloak class="grid grid-cols-1 md:grid-cols-3 gap-4 pt-2">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1">{{ __('Transaction Currency') }}</label>
                        <select name="original_currency" x-model="originalCurrency" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500">
                            <option value="USD">USD - US Dollar</option>
                            <option value="EUR">EUR - Euro</option>
                            <option value="PKR">PKR - Pakistani Rupee</option>
                            <option value="AED">AED - UAE Dirham</option>
                            <option value="SAR">SAR - Saudi Riyal</option>
                            <option value="GBP">GBP - British Pound</option>
                            <option value="INR">INR - Indian Rupee</option>
                            <option value="JPY">JPY - Japanese Yen</option>
                            <option value="CNY">CNY - Chinese Yuan</option>
                            <option value="CAD">CAD - Canadian Dollar</option>
                            <option value="AUD">AUD - Australian Dollar</option>
                            <option value="CHF">CHF - Swiss Franc</option>
                            <option value="SGD">SGD - Singapore Dollar</option>
                            <option value="HKD">HKD - Hong Kong Dollar</option>
                            <option value="NZD">NZD - New Zealand Dollar</option>
                            <option value="TRY">TRY - Turkish Lira</option>
                            <option value="ZAR">ZAR - South African Rand</option>
                            <option value="MYR">MYR - Malaysian Ringgit</option>
                            <option value="THB">THB - Thai Baht</option>
                            <option value="QAR">QAR - Qatari Riyal</option>
                            <option value="KWD">KWD - Kuwaiti Dinar</option>
                            <option value="OMR">OMR - Omani Rial</option>
                            <option value="BHD">BHD - Bahraini Dinar</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1">{{ __('Foreign Amount') }}</label>
                        <input type="number" step="0.01" name="original_amount" x-model="originalAmount" placeholder="0.00" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1">{{ __('Exchange Rate') }}</label>
                        <div class="flex gap-1.5">
                            <input type="number" step="0.000001" name="exchange_rate" x-model="exchangeRate" placeholder="1.000000" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500">
                            <button type="button" @click="fetchRate()" class="px-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-semibold transition shrink-0">
                                {{ __('Fetch Rate') }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Amount & Paid From -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">
                        Amount Paid (<span x-text="baseCurrency"></span>) *
                    </label>
                    <input type="number" step="0.01" name="amount" x-model="formAmount" required placeholder="0.00"
                        :readonly="isForeign"
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-750 text-sm"
                        :class="isForeign ? 'bg-slate-100 font-semibold text-emerald-800' : ''">
                    <x-input-error :messages="$errors->get('amount')" class="mt-1" />
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Paid From Bank Account <span class="text-rose-600">*</span></label>
                    <select name="bank_account_id" required
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                        <option value="">Select Bank Account</option>
                        @foreach($bankAccounts as $acc)
                            <option value="{{ $acc->id }}" {{ old('bank_account_id') == $acc->id ? 'selected' : '' }}>{{ $acc->name }} ({{ $acc->bank_name }})</option>
                        @endforeach
                    </select>
                    <x-input-error :messages="$errors->get('bank_account_id')" class="mt-1" />
                </div>
            </div>

            <!-- Payee details & Transaction ID -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Payee Bank Name</label>
                    <input type="text" name="payee_bank_name" value="{{ old('payee_bank_name') }}" placeholder="Barclays, Lloyds etc."
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                    <x-input-error :messages="$errors->get('payee_bank_name')" class="mt-1" />
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Payee Account #</label>
                    <input type="text" name="payee_account_no" value="{{ old('payee_account_no') }}" placeholder="8-digit account number"
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                    <x-input-error :messages="$errors->get('payee_account_no')" class="mt-1" />
                </div>

                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Transaction Ref / ID</label>
                    <input type="text" name="transaction_id" value="{{ old('transaction_id') }}" placeholder="e.g. TXN-12345"
                        class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                    <x-input-error :messages="$errors->get('transaction_id')" class="mt-1" />
                </div>
            </div>

            <!-- Consignment Project -->
            <div>
                <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Link to Consignment / Project</label>
                <select name="consignment_id"
                    class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-brand-500 focus:ring-1 focus:ring-brand-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                    <option value="">-- No Project (General Expense) --</option>
                    @foreach($consignments as $project)
                        <option value="{{ $project->id }}" {{ old('consignment_id') == $project->id ? 'selected' : '' }}>
                            {{ $project->title }}
                        </option>
                    @endforeach
                </select>
                <x-input-error :messages="$errors->get('consignment_id')" class="mt-1" />
            </div>

            <!-- Receipt attachment -->
            <div>
                <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Attach Expense Receipt (Image/PDF)</label>
                <input type="file" name="receipt"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">
                <x-input-error :messages="$errors->get('receipt')" class="mt-1" />
            </div>

            <!-- Collapsible VAT section -->
            <div class="col-span-2">
                <div class="flex items-center">
                    <input type="checkbox" id="show_vat" x-model="showVat" class="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 h-4 w-4">
                    <label for="show_vat" class="ml-2 text-sm font-semibold text-slate-700">Calculate VAT on transaction</label>
                </div>
            </div>

            <div x-show="showVat" x-cloak class="grid grid-cols-1 md:grid-cols-3 gap-6 bg-slate-50 border border-slate-200 rounded-xl p-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-600 uppercase mb-1">VAT Rate (%)</label>
                    <input type="number" step="0.1" name="vat_rate" x-model="vatRate" placeholder="e.g. 20.0" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 uppercase mb-1">VAT Type</label>
                    <select name="vat_inclusive" x-model="vatInclusive" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500">
                        <option value="1">VAT Inclusive</option>
                        <option value="0">VAT Exclusive</option>
                    </select>
                </div>
                <div class="flex flex-col justify-center text-sm text-slate-500 space-y-1">
                    <div>Net Amount: <span class="font-bold text-slate-700" x-text="calcNet"></span></div>
                    <div>VAT Amount: <span class="font-bold text-slate-700" x-text="calcVat"></span></div>
                </div>
            </div>

            <!-- Notes -->
            <div>
                <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-2">Internal Notes</label>
                <textarea name="notes" rows="4" placeholder="Log details, vendor info, item list..."
                    class="w-full py-2.5 px-3 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-700 text-sm">{{ old('notes') }}</textarea>
                <x-input-error :messages="$errors->get('notes')" class="mt-1" />
            </div>

            <!-- Action buttons -->
            <div class="flex justify-end gap-3 pt-6 border-t border-slate-200">
                <a href="{{ route('expenses.index') }}" class="py-2.5 px-5 bg-slate-100 hover:bg-slate-200 text-slate-750 text-sm font-medium rounded-xl transition">Cancel</a>
                <button type="submit" class="py-2.5 px-5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-semibold rounded-xl transition">Log Expense</button>
            </div>
        </form>
    </div>
</x-app-layout>