<x-app-layout>
    <div class="py-6" x-data="{
        recordType: '{{ old('record_type', $cashIn->custom_account_id ? 'custom' : 'client') }}',
        showVat: {{ old('vat_rate', $cashIn->vat_rate) ? 'true' : 'false' }},
        formAmount: '{{ old('amount', $cashIn->amount) }}',
        vatRate: '{{ old('vat_rate', $cashIn->vat_rate) }}',
        vatInclusive: {{ old('vat_inclusive', $cashIn->vat_inclusive ?? 1) ? 1 : 0 }},
        
        // Multi-currency details
        isForeign: {{ $cashIn->original_currency ? 'true' : 'false' }},
        originalCurrency: '{{ old('original_currency', $cashIn->original_currency ?? 'USD') }}',
        originalAmount: '{{ old('original_amount', $cashIn->original_amount ?? '') }}',
        exchangeRate: '{{ old('exchange_rate', $cashIn->exchange_rate ?? '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);
        },
        
        showClientModal: false,
        showCustomModal: false,
        clientLoading: false,
        customLoading: false,
        clientErrors: {},
        customErrors: {},
        clientForm: { title: 'Mr', first_name: '', last_name: '', email: '', phone: '', mobile: '', company_name: '', company_vat: '', address_line1: '', address_line2: '', city: '', state: '', postcode: '', country: '' },
        customForm: { name: '', email: '', account_type: '', notes: '' },
        
        customAccounts: [
            @foreach($customAccounts as $account)
                { id: '{{ $account->id }}', name: '{{ addslashes($account->name) }}', type: '{{ addslashes($account->account_type) }}' },
            @endforeach
        ],
        selectedCustomId: '{{ old('custom_account_id', $cashIn->custom_account_id) }}',
        customSearchQuery: '',
        showCustomDropdown: false,

        get filteredCustomAccounts() {
            if (!this.customSearchQuery) return this.customAccounts;
            const q = this.customSearchQuery.toLowerCase();
            return this.customAccounts.filter(a => a.name.toLowerCase().includes(q) || (a.type && a.type.toLowerCase().includes(q)));
        },

        init() {
            if (this.selectedCustomId) {
                const acc = this.customAccounts.find(a => a.id == this.selectedCustomId);
                if (acc) {
                    this.customSearchQuery = acc.name + ' (' + acc.type + ')';
                }
            }
            this.$watch('selectedCustomId', val => {
                const acc = this.customAccounts.find(a => a.id == val);
                if (acc) {
                    this.customSearchQuery = acc.name + ' (' + acc.type + ')';
                } else {
                    this.customSearchQuery = '';
                }
            });
            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.');
            }
        }
    }">
        <a href="{{ route('cash-in.show', $cashIn->id) }}" 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 Transaction Details
        </a>
        <div class="mb-8">
            <h2 class="text-2xl font-bold text-slate-800">Edit Cash In Record</h2>
            <p class="text-slate-500 text-sm mt-1">Modify client payment details, exchange rates, or replace the attached receipt.</p>
        </div>

        <form action="{{ route('cash-in.update', $cashIn->id) }}" method="POST" enctype="multipart/form-data" class="space-y-6 max-w-7xl bg-white border border-slate-200 rounded-xl shadow-sm p-6">
            @csrf
            @method('PUT')
            <input type="hidden" name="record_type" x-model="recordType">

            <!-- Record Type Selector -->
            <div class="flex items-center gap-3 pb-4 border-b border-slate-100 mb-4">
                <span class="text-sm font-semibold text-slate-700">Payment Source:</span>
                <div class="flex gap-1 p-1 bg-slate-100 rounded-lg">
                    <button type="button" @click="recordType = 'client'"
                        class="py-1.5 px-3 text-xs font-semibold rounded-lg transition-all duration-200"
                        :class="recordType === 'client' ? 'bg-white text-emerald-700 shadow-sm' : 'text-slate-600 hover:text-slate-800'">
                        Client Registry
                    </button>

                    <button type="button" @click="recordType = 'custom'"
                        class="py-1.5 px-3 text-xs font-semibold rounded-lg transition-all duration-200"
                        :class="recordType === 'custom' ? 'bg-white text-emerald-700 shadow-sm' : 'text-slate-600 hover:text-slate-800'">
                        Custom Account
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

                <!-- ===== CLIENT MODE ===== -->
                <div x-show="recordType === 'client'" class="col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div x-data="{
                        open: false,
                        search: '',
                        selectedId: '{{ old('client_id', $cashIn->client_id) }}',
                        selectedName: '',
                        clients: [
                            @foreach($clients as $client)
                                {
                                    id: '{{ $client->id }}',
                                    name: '{{ addslashes($client->full_name) }}',
                                    phone: '{{ addslashes($client->phone ?? '') }}',
                                    email: '{{ addslashes($client->email ?? '') }}'
                                },
                            @endforeach
                        ],
                        get filteredClients() {
                            if (this.search.trim() === '') return this.clients;
                            const term = this.search.toLowerCase();
                            return this.clients.filter(c =>
                                c.name.toLowerCase().includes(term) ||
                                c.phone.toLowerCase().includes(term) ||
                                c.email.toLowerCase().includes(term)
                            );
                        },
                        selectClient(id, name) {
                            this.selectedId = id;
                            this.selectedName = name;
                            this.search = name;
                            this.open = false;
                        },
                        init() {
                            const initial = this.clients.find(c => c.id == this.selectedId);
                            if (initial) {
                                this.selectedName = initial.name;
                                this.search = initial.name;
                            }
                        }
                    }" x-on:client-created.window="clients.push($event.detail); selectClient($event.detail.id, $event.detail.name)" class="relative">
                        <div class="flex items-center gap-2">
                            <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Select Client *</label>
                            <button type="button" @click="showClientModal = true"
                                class="w-7 h-7 flex items-center justify-center rounded-full bg-emerald-600 hover:bg-emerald-700 text-white text-lg leading-none shadow-sm transition duration-150 flex-shrink-0">+</button>
                        </div>
                        <input type="hidden" name="client_id" x-model="selectedId" x-bind:required="recordType === 'client'">
                        <div class="relative">
                            <input type="text"
                                   x-model="search"
                                   @focus="open = true"
                                   @click.outside="open = false; if(!selectedId) search = ''; else search = selectedName;"
                                   placeholder="-- Search Client by Name, Phone, or Email --"
                                   class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 placeholder-slate-400 focus:outline-none transition duration-150">
                        </div>
                        <div x-show="open" x-cloak
                             class="absolute z-50 w-full mt-1.5 max-h-60 overflow-y-auto bg-white border border-slate-200 rounded-xl shadow-2xl py-1 divide-y divide-slate-200">
                            <template x-for="client in filteredClients" :key="client.id">
                                <button type="button"
                                        @mousedown="selectClient(client.id, client.name)"
                                        class="w-full text-left px-4 py-2 text-sm text-slate-600 hover:bg-emerald-50 hover:text-emerald-700 transition duration-100 flex flex-col gap-0.5">
                                    <span class="font-semibold" x-text="client.name"></span>
                                    <span class="text-xs text-slate-400" x-text="(client.email ? client.email : 'No Email') + ' | ' + (client.phone ? client.phone : 'No Phone')"></span>
                                </button>
                            </template>
                        </div>
                        @error('client_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Sender Bank Name</label>
                        <input type="text" name="sender_bank_name" value="{{ old('sender_bank_name', $cashIn->sender_bank_name) }}" placeholder="E.g., Barclays, Lloyds"
                            class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 placeholder-slate-400 focus:outline-none transition duration-150">
                        @error('sender_bank_name') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                    </div>

                    <div>
                        <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Sender Account #</label>
                        <input type="text" name="sender_account_no" value="{{ old('sender_account_no', $cashIn->sender_account_no) }}" placeholder="E.g., 12345678"
                            class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 placeholder-slate-400 focus:outline-none transition duration-150">
                        @error('sender_account_no') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                    </div>

                    <!-- Third-Party Payer (Installment machinery/import logic) -->
                    <div class="col-span-1 md:col-span-2 bg-slate-50 border border-slate-200 rounded-xl p-4 mt-2">
                        <div x-data="{ isThirdParty: {{ $cashIn->third_party_payer ? 'true' : 'false' }} }">
                            <label class="inline-flex items-center text-sm font-semibold text-slate-700 cursor-pointer mb-2">
                                <input type="checkbox" x-model="isThirdParty" class="rounded border-slate-300 text-brand-500 focus:ring-brand-500 h-4 w-4">
                                <span class="ml-2">Received via Third-Party Payer (Other country/sender)?</span>
                            </label>
                            <div x-show="isThirdParty" x-cloak class="mt-2 transition duration-150">
                                <label class="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-1">Third-Party Sender Name *</label>
                                <input type="text" name="third_party_payer" value="{{ old('third_party_payer', $cashIn->third_party_payer) }}" placeholder="E.g., Ali (from Dubai Office)"
                                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-1 focus:ring-brand-500 rounded-lg text-slate-800 placeholder-slate-400 focus:outline-none text-sm transition">
                                @error('third_party_payer') <p class="text-rose-600 text-xs mt-1">{{ $message }}</p> @enderror
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ===== CUSTOM ACCOUNT MODE ===== -->
                <div x-show="recordType === 'custom'" x-cloak class="col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <div class="flex items-center gap-2">
                            <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Select Custom Account *</label>
                        </div>
                        <div class="relative" @click.away="showCustomDropdown = false">
                            <input type="hidden" name="custom_account_id" :value="selectedCustomId" x-bind:required="recordType === 'custom'">
                            <input type="text"
                                x-model="customSearchQuery"
                                @focus="showCustomDropdown = true"
                                @input="showCustomDropdown = true; selectedCustomId = ''"
                                placeholder="Type to search custom accounts..."
                                class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150">
                            <div x-show="showCustomDropdown && filteredCustomAccounts.length > 0" x-cloak
                                class="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-xl shadow-lg max-h-60 overflow-y-auto">
                                <template x-for="account in filteredCustomAccounts" :key="account.id">
                                    <button type="button"
                                        @click="selectedCustomId = account.id; customSearchQuery = account.name + ' (' + account.type + ')'; showCustomDropdown = false"
                                        class="w-full text-left px-4 py-2 hover:bg-slate-50 text-sm text-slate-700 transition duration-150 border-b border-slate-100 last:border-0">
                                        <span class="font-semibold" x-text="account.name"></span>
                                        <span class="text-xs text-slate-400 ml-1.5" x-text="'(' + account.type + ')'"></span>
                                    </button>
                                </template>
                            </div>
                        </div>
                        @error('custom_account_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                    </div>
                </div>

                <!-- Transaction Date -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Date *</label>
                    <input type="date" name="date" id="transaction_date" value="{{ old('date', $cashIn->date->format('Y-m-d')) }}" required
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                    @error('date') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Multi-Currency Control Block -->
                <div class="col-span-2 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" 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 (Calculated if Foreign Currency) -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">
                        Amount (<span x-text="baseCurrency"></span>) *
                    </label>
                    <input type="number" step="0.01" name="amount" x-model="formAmount" placeholder="0.00" required
                        :readonly="isForeign"
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150"
                        :class="isForeign ? 'bg-slate-100 font-semibold text-emerald-800' : ''">
                    @error('amount') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Payment Method -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Payment Method *</label>
                    <select name="payment_method_id" required
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                        <option value="">-- Select Method --</option>
                        @foreach($paymentMethods as $method)
                            <option value="{{ $method->id }}" {{ old('payment_method_id', $cashIn->payment_method_id) == $method->id ? 'selected' : '' }}>{{ $method->name }}</option>
                        @endforeach
                    </select>
                    @error('payment_method_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Payment Type -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Transaction Type *</label>
                    <select name="payment_type_id" required
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                        <option value="">-- Select Type --</option>
                        @foreach($paymentTypes as $type)
                            <option value="{{ $type->id }}" {{ old('payment_type_id', $cashIn->payment_type_id) == $type->id ? 'selected' : '' }}>{{ $type->name }}</option>
                        @endforeach
                    </select>
                    @error('payment_type_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Bank Account -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Deposit Bank Account</label>
                    <select name="bank_account_id"
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                        <option value="">-- Select Bank Account --</option>
                        @foreach($bankAccounts as $bank)
                            <option value="{{ $bank->id }}" {{ old('bank_account_id', $cashIn->bank_account_id) == $bank->id ? 'selected' : '' }}>{{ $bank->name }} ({{ $bank->bank_name }})</option>
                        @endforeach
                    </select>
                    @error('bank_account_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Transaction Reference / ID -->
                <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', $cashIn->transaction_id) }}" placeholder="E.g., CHG-1897-A"
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 placeholder-slate-400 focus:outline-none transition duration-150">
                    @error('transaction_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </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 Inflow) --</option>
                        @foreach($consignments as $project)
                            <option value="{{ $project->id }}" {{ old('consignment_id', $cashIn->consignment_id) == $project->id ? 'selected' : '' }}>
                                {{ $project->title }}
                            </option>
                        @endforeach
                    </select>
                    @error('consignment_id') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- Payment Status -->
                <div>
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Payment Status *</label>
                    <select name="payment_status" required
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                        <option value="paid" {{ old('payment_status', $cashIn->payment_status) == 'paid' ? 'selected' : '' }}>Paid</option>
                        <option value="pending" {{ old('payment_status', $cashIn->payment_status) == 'pending' ? 'selected' : '' }}>Pending</option>
                    </select>
                </div>

                <!-- Receipt Upload -->
                <div class="col-span-2">
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Replace Receipt Image/PDF</label>
                    <input type="file" name="receipt"
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 focus:outline-none transition duration-150 text-sm">
                    @if($cashIn->receipt_path)
                        <p class="text-xs text-slate-400 mt-1">Current file: <a href="{{ route('cash-in.download-receipt', $cashIn->id) }}" class="text-emerald-600 underline font-medium">Download receipt</a></p>
                    @endif
                    @error('receipt') <p class="text-rose-600 text-sm mt-1">{{ $message }}</p> @enderror
                </div>

                <!-- VAT Configurations toggler -->
                <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>

                <!-- VAT fields -->
                <div x-show="showVat" x-cloak class="col-span-2 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 tracking-wider 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 tracking-wider 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>

                <!-- Internal Notes -->
                <div class="col-span-2">
                    <label class="block text-sm font-semibold text-slate-600 uppercase tracking-wider mb-1.5">Internal Notes</label>
                    <textarea name="notes" rows="4" placeholder="Log details, transaction notes, invoice details..."
                        class="w-full py-2.5 px-4 bg-white border border-slate-300 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 rounded-xl text-slate-800 placeholder-slate-400 focus:outline-none transition duration-150">{{ old('notes', $cashIn->notes) }}</textarea>
                </div>

                <!-- Destructive toggle -->
                @if(Auth::user()->isAdmin())
                    <div class="col-span-2 flex items-center bg-rose-50 border border-rose-200 rounded-xl p-3">
                        <input type="checkbox" id="is_hidden" name="is_hidden" value="1" {{ old('is_hidden', $cashIn->is_hidden) ? 'checked' : '' }} class="rounded border-slate-300 text-rose-600 focus:ring-rose-500 h-4 w-4">
                        <label for="is_hidden" class="ml-2 text-xs font-semibold text-rose-800">Hide transaction from standard reports (Private ledger only)</label>
                    </div>
                @endif

            </div>

            <div class="flex justify-end gap-3 pt-6 border-t border-slate-200">
                <a href="{{ route('cash-in.show', $cashIn->id) }}" class="py-2.5 px-5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-medium rounded-xl transition duration-150">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 shadow-sm transition duration-150 font-semibold">Update Cash In</button>
            </div>
        </form>

        <!-- Inline Client Creation Modal -->
        <div x-show="showClientModal" x-cloak class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40" @click.self="showClientModal = false">
            <div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-2xl mx-4 overflow-y-auto max-h-[90vh]">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-slate-800">Create Client Profile</h3>
                    <button @click="showClientModal = false" type="button" class="text-slate-400 hover:text-slate-600 text-2xl leading-none">&times;</button>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Title *</label>
                        <select x-model="clientForm.title" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm">
                            <option value="Mr">Mr</option>
                            <option value="Mrs">Mrs</option>
                            <option value="Ms">Ms</option>
                            <option value="Dr">Dr</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">First Name *</label>
                        <input type="text" x-model="clientForm.first_name" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Last Name *</label>
                        <input type="text" x-model="clientForm.last_name" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Email</label>
                        <input type="email" x-model="clientForm.email" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1">Mobile</label>
                        <input type="text" x-model="clientForm.mobile" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm">
                    </div>
                </div>
                <div class="flex justify-end gap-3 mt-6 pt-4 border-t border-slate-200">
                    <button @click="showClientModal = false" type="button" class="py-2 px-4 bg-black text-white text-sm rounded-xl transition">Cancel</button>
                    <button @click="createClient()" type="button" :disabled="clientLoading" class="py-2 px-4 bg-emerald-600 text-white text-sm font-semibold rounded-xl transition" x-text="clientLoading ? 'Saving...' : 'Save & Select'"></button>
                </div>
            </div>
        </div>

    </div>
</x-app-layout>