@extends('layouts.admin')

@section('title', 'Edit Invoice')

@section('page-title', 'Edit Invoice')

@section('breadcrumbs')
    <a href="{{ route('admin.invoices.index') }}" class="hover:text-primary">Invoices</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <a href="{{ route('admin.invoices.show', $invoice) }}" class="hover:text-primary">{{ $invoice->invoice_number }}</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Edit</span>
@endsection

@section('content')
<form method="POST" action="{{ route('admin.invoices.update', $invoice) }}" id="invoice-form" class="max-w-5xl mx-auto flex flex-col gap-6 pb-24">
    @csrf
    @method('PUT')

    <!-- Section 1: Header Info -->
    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-lg font-bold text-[#111418] text-gray-900">Invoice Header</h3>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Invoice Date <span class="text-red-500">*</span></label>
                <input type="date" name="issue_date" value="{{ old('issue_date', $invoice->issue_date->format('Y-m-d')) }}" required class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Due Date <span class="text-red-500">*</span></label>
                <input type="date" name="due_date" value="{{ old('due_date', $invoice->due_date->format('Y-m-d')) }}" required class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Status</label>
                <select name="status" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    <option value="draft" {{ old('status', $invoice->status) == 'draft' ? 'selected' : '' }}>Draft</option>
                    <option value="sent" {{ old('status', $invoice->status) == 'sent' ? 'selected' : '' }}>Sent</option>
                    <option value="viewed" {{ old('status', $invoice->status) == 'viewed' ? 'selected' : '' }}>Viewed</option>
                    <option value="partial" {{ old('status', $invoice->status) == 'partial' ? 'selected' : '' }}>Partial</option>
                    <option value="paid" {{ old('status', $invoice->status) == 'paid' ? 'selected' : '' }}>Paid</option>
                </select>
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Currency</label>
                <select name="currency" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    @foreach($currencies ?? [] as $currency)
                        <option value="{{ $currency->code }}" {{ old('currency', $invoice->currency) == $currency->code ? 'selected' : '' }}>
                            {{ $currency->code }} - {{ $currency->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="md:col-span-4 mt-2">
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Invoice template</label>
                <select name="template" class="w-full max-w-md h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    @foreach($invoiceTemplateOptions ?? [] as $key => $label)
                        <option value="{{ $key }}" {{ old('template', $invoice->template ?? ($defaultInvoiceTemplate ?? 'modern')) === $key ? 'selected' : '' }}>{{ $label }}</option>
                    @endforeach
                </select>
                <p class="text-xs text-[#617589] mt-1">PDF and on-screen invoice layout for this document.</p>
            </div>
        </div>
    </div>

    <!-- Billed To -->
    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6 flex flex-col h-full bg-blue-50/30">
        <div class="flex justify-between items-start mb-4">
            <div class="flex flex-col gap-1">
                <p class="text-xs font-semibold text-[#617589] uppercase tracking-wider">Billed To (Client) <span class="text-red-500">*</span></p>
            </div>
            <button type="button" onclick="clearCustomer()" id="customer-edit-button" class="text-primary text-sm font-medium hover:bg-primary/10 p-1 rounded transition hidden">Edit</button>
        </div>
        <div class="flex flex-col gap-1 w-full">
            <!-- Customer Search (shown when no customer selected) -->
            <div id="customer-search-container" class="relative w-full mt-1">
                <div class="relative">
                    <input type="text" id="customer-search" autocomplete="off" placeholder="Search customers..." class="w-full h-10 rounded-lg border border-[#dbe0e6] bg-white px-3 pr-10 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900 placeholder:text-[#617589]"/>
                    <span class="material-symbols-outlined absolute right-3 top-2.5 text-[#617589] pointer-events-none text-lg">search</span>
                    <input type="hidden" name="customer_id" id="customer-id" required value="{{ old('customer_id', $invoice->customer_id) }}"/>
                </div>
                <div id="customer-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-[#dbe0e6] rounded-lg shadow-lg max-h-60 overflow-y-auto">
                        @foreach($customers as $customer)
                        <div class="customer-option px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-[#e5e7eb] last:border-b-0" 
                             data-id="{{ $customer->id }}" 
                             data-name="{{ $customer->name }}" 
                             data-email="{{ $customer->email ?? '' }}"
                             data-phone="{{ $customer->phone ?? '' }}"
                             data-company="{{ $customer->company ?? '' }}"
                             data-address="{{ $customer->address ?? '' }}"
                             data-city="{{ $customer->city ?? '' }}"
                             data-state="{{ $customer->state ?? '' }}"
                             data-zip="{{ $customer->zip ?? '' }}"
                             data-country="{{ $customer->country ?? '' }}"
                             data-logo="{{ ($customer->image && \Illuminate\Support\Facades\Storage::disk('public')->exists($customer->image)) ? \Illuminate\Support\Facades\Storage::url($customer->image) : (($customer->logo && \Illuminate\Support\Facades\Storage::disk('public')->exists($customer->logo)) ? \Illuminate\Support\Facades\Storage::url($customer->logo) : '') }}">
                            <div class="font-medium text-[#111418] text-gray-900">{{ $customer->name }}</div>
                            @if($customer->email)
                                <div class="text-xs text-[#617589]">{{ $customer->email }}</div>
                            @endif
                        </div>
                        @endforeach
                </div>
            </div>
            <!-- Customer Display (shown when customer selected) -->
            <div id="customer-display" class="{{ old('customer_id', $invoice->customer_id) ? '' : 'hidden' }}">
                <div class="flex justify-between items-start mb-4">
                    <div class="flex flex-col gap-1">
                        <h4 id="customer-display-name" class="text-base font-bold text-[#111418] text-gray-900">
                            {{ $invoice->customer->company ?? $invoice->customer->name ?? '' }}
                        </h4>
                    </div>
                </div>
                <div class="flex gap-4 items-start">
                    <div id="customer-logo-container" class="w-16 h-16 rounded-lg bg-background-light dark:bg-black border border-dashed border-[#dbe0e6] flex items-center justify-center overflow-hidden">
                        @if($invoice->customer && (($invoice->customer->image && \Illuminate\Support\Facades\Storage::disk('public')->exists($invoice->customer->image)) || ($invoice->customer->logo && \Illuminate\Support\Facades\Storage::disk('public')->exists($invoice->customer->logo))))
                            <img id="customer-logo-img" src="{{ \Illuminate\Support\Facades\Storage::url($invoice->customer->image ?? $invoice->customer->logo) }}" alt="{{ $invoice->customer->name }}" class="w-full h-full object-contain p-1" style="background-color: rgba(248, 250, 252, 1);">
                        @else
                            <span class="material-symbols-outlined text-[#617589] text-2xl">business</span>
                        @endif
                    </div>
                    <div class="text-sm text-[#617589] flex flex-col gap-1" id="customer-display-details">
                        @if($invoice->customer)
                            @if($invoice->customer->address)
                                <p>{{ $invoice->customer->address }}</p>
                            @endif
                            @php
                                $cityStateZip = trim(($invoice->customer->city ?? '') . ', ' . ($invoice->customer->state ?? '') . ' ' . ($invoice->customer->zip ?? ''), ', ');
                            @endphp
                            @if($cityStateZip)
                                <p>{{ $cityStateZip }}</p>
                            @endif
                            @if($invoice->customer->phone)
                                <p>{{ $invoice->customer->phone }}</p>
                            @endif
                            @if($invoice->customer->email)
                                <p>{{ $invoice->customer->email }}</p>
                            @endif
                        @endif
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-auto border-t border-[#e5e7eb] pt-4 flex justify-between items-center">
            <a href="{{ route('admin.customers.create') }}" class="text-primary text-sm font-medium flex items-center gap-1 hover:underline">
                <span class="material-symbols-outlined text-base">add</span> Add New Client
            </a>
        </div>
    </div>

    <!-- Invoice Items Section -->
    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <div class="flex flex-wrap gap-4 items-center justify-between mb-6 pb-6 border-b border-[#e5e7eb]">
            <h3 class="text-lg font-bold text-[#111418] text-gray-900">Invoice Items</h3>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse" id="items-table">
                <thead>
                    <tr class="border-b border-[#e5e7eb]">
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider w-1/2 min-w-[300px]">Item Details</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right w-24">Qty</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right w-32">Rate</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right w-32">Tax %</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right w-32">Amount</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider w-10"></th>
                    </tr>
                </thead>
                <tbody class="text-sm" id="items-tbody">
                    <!-- Items will be populated from existing invoice -->
                </tbody>
            </table>
        </div>

        <div class="flex gap-3 mt-4">
            <button type="button" onclick="addItemRow()" class="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary/10 text-primary font-medium text-sm hover:bg-primary/20 transition-colors">
                <span class="material-symbols-outlined text-lg">add_circle</span> Add New Line
            </button>
        </div>
    </div>

    <!-- Totals & Summary -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="flex flex-col gap-6">
            <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Notes</h3>
                <textarea name="notes" rows="4" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">{{ old('notes', $invoice->notes) }}</textarea>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Terms & Conditions</h3>
                <textarea name="terms" rows="4" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">{{ old('terms', $invoice->terms) }}</textarea>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <div class="flex flex-col gap-3">
                <div class="flex justify-between items-center text-sm">
                    <span class="text-[#617589]">Subtotal</span>
                    <span class="font-medium text-[#111418] text-gray-900" id="subtotal">$0.00</span>
                </div>
                <div class="flex justify-between items-center text-sm">
                    <span class="text-[#617589]">Tax Amount</span>
                    <span class="font-medium text-[#111418] text-gray-900" id="tax-amount">$0.00</span>
                </div>
                <div class="flex justify-between items-center pt-4 mt-2 border-t border-[#e5e7eb]">
                    <span class="text-base font-bold text-[#111418] text-gray-900">Total</span>
                    <span class="text-2xl font-bold text-primary" id="total">$0.00</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Method Section -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Payment Method -->
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-sm font-bold text-[#111418] text-gray-900">Payment Method</h3>
                <button type="button" onclick="openPaymentMethodModal()" class="flex items-center gap-2 px-4 py-2 text-sm font-medium text-primary bg-primary/10 hover:bg-primary/20 rounded-lg transition-colors">
                    <span class="material-symbols-outlined text-[18px]">add</span>
                    <span>Add Payment Method</span>
                </button>
            </div>
            <div id="payment-method-preview" class="min-h-[60px] p-3 rounded-lg border border-[#dbe0e6] bg-gray-50 text-sm {{ old('payment_method', $invoice->payment_method) ? 'text-[#111418]' : 'text-[#617589]' }}">
                <p id="payment-method-content">
                    @php
                        $paymentMethod = old('payment_method', $invoice->payment_method);
                        if ($paymentMethod === 'online') {
                            echo 'Online Payment';
                        } elseif ($paymentMethod && str_starts_with($paymentMethod, 'bank_')) {
                            $bankId = str_replace('bank_', '', $paymentMethod);
                            $bankAccount = \App\Models\BankAccount::find($bankId);
                            if ($bankAccount) {
                                echo 'Bank Transfer: ' . $bankAccount->bank_name . ' - ' . $bankAccount->account_name;
                            } else {
                                echo 'Bank Transfer';
                            }
                        } else {
                            echo 'No payment method selected. Click "Add Payment Method" to select.';
                        }
                    @endphp
                </p>
            </div>
            <input type="hidden" name="payment_method" id="payment-method-input" value="{{ old('payment_method', $invoice->payment_method) }}">
        </div>
        
        <!-- Signature -->
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Signature</h3>
            <div class="relative">
                <select name="signature_id" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    <option value="">No Signature</option>
                    @foreach($signatures ?? [] as $signature)
                        <option value="{{ $signature->id }}" {{ old('signature_id', $invoice->signature_id ?? '') == $signature->id ? 'selected' : '' }}>{{ $signature->name }}</option>
                    @endforeach
                </select>
            </div>
            @if(isset($signatures) && $signatures->count() > 0)
                <div id="signature-preview" class="mt-4 border-2 border-dashed border-[#dbe0e6] rounded-lg p-4 bg-background-light/50 min-h-[100px] flex items-center justify-center">
                    <p class="text-sm text-[#617589]">Select a signature to preview</p>
                </div>
            @endif
        </div>
    </div>

    <!-- Sticky Footer Action Bar -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-[#e5e7eb] p-4 z-20 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
        <div class="max-w-5xl mx-auto flex justify-between items-center">
            <a href="{{ route('admin.invoices.show', $invoice) }}" class="px-6 py-2.5 rounded-lg border border-[#dbe0e6] text-[#617589] font-medium hover:bg-background-light hover:text-[#111418] transition-colors">
                Cancel
            </a>
            <div class="flex gap-3">
                <button type="submit" class="px-8 py-2.5 rounded-lg bg-primary text-white font-bold hover:bg-blue-600 shadow-lg shadow-blue-500/30 transition-all flex items-center gap-2">
                    Update Invoice <span class="material-symbols-outlined text-lg">save</span>
                </button>
            </div>
        </div>
    </div>
</form>

<script>
let itemIndex = 0;

function addItemRow(item = null) {
    const tbody = document.getElementById('items-tbody');
    const row = document.createElement('tr');
    row.className = 'group hover:bg-background-light/50 border-b border-[#f0f2f4]';
    row.dataset.index = itemIndex;

    row.innerHTML = `
        <td class="py-4 px-2 align-top">
            <input type="text" name="items[${itemIndex}][description]" value="${item?.description || ''}" required placeholder="Item name" class="w-full font-medium text-[#111418] text-gray-900 bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:ring-1 focus:ring-primary focus:border-primary text-gray-900 mb-1">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][quantity]" value="${item?.quantity || '1'}" required min="0.01" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][unit_price]" value="${item?.unit_price || '0'}" required min="0" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][tax_rate]" value="${item?.tax_rate || '0'}" min="0" max="100" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top text-right font-medium text-[#111418] text-gray-900" id="amount-${itemIndex}">
            $0.00
        </td>
        <td class="py-4 px-2 align-top text-center">
            <button type="button" onclick="removeItemRow(${itemIndex})" class="text-red-400 hover:text-red-600 transition-opacity">
                <span class="material-symbols-outlined text-lg">delete</span>
            </button>
        </td>
    `;

    tbody.appendChild(row);
    itemIndex++;
    calculateTotals();
}

function removeItemRow(index) {
    const row = document.querySelector(`tr[data-index="${index}"]`);
    if (row) {
        row.remove();
        calculateTotals();
    }
}

function calculateRow(index) {
    const row = document.querySelector(`tr[data-index="${index}"]`);
    if (!row) return;

    const quantity = parseFloat(row.querySelector(`input[name="items[${index}][quantity]"]`).value) || 0;
    const unitPrice = parseFloat(row.querySelector(`input[name="items[${index}][unit_price]"]`).value) || 0;
    const taxRate = parseFloat(row.querySelector(`input[name="items[${index}][tax_rate]"]`).value) || 0;

    const subtotal = quantity * unitPrice;
    const taxAmount = subtotal * (taxRate / 100);
    const total = subtotal + taxAmount;

    document.getElementById(`amount-${index}`).textContent = '$' + total.toFixed(2);
    calculateTotals();
}

function calculateTotals() {
    let subtotal = 0;
    let taxAmount = 0;

    document.querySelectorAll('tr[data-index]').forEach((row, index) => {
        const quantity = parseFloat(row.querySelector(`input[name="items[${index}][quantity]"]`)?.value) || 0;
        const unitPrice = parseFloat(row.querySelector(`input[name="items[${index}][unit_price]"]`)?.value) || 0;
        const taxRate = parseFloat(row.querySelector(`input[name="items[${index}][tax_rate]"]`)?.value) || 0;

        const itemSubtotal = quantity * unitPrice;
        const itemTax = itemSubtotal * (taxRate / 100);

        subtotal += itemSubtotal;
        taxAmount += itemTax;
    });

    const total = subtotal + taxAmount;

    document.getElementById('subtotal').textContent = '$' + subtotal.toFixed(2);
    document.getElementById('tax-amount').textContent = '$' + taxAmount.toFixed(2);
    document.getElementById('total').textContent = '$' + total.toFixed(2);
}

// Load existing items
document.addEventListener('DOMContentLoaded', function() {
    @foreach($invoice->items as $item)
        addItemRow({
            description: '{{ addslashes($item->description) }}',
            quantity: {{ $item->quantity }},
            unit_price: {{ $item->unit_price }},
            tax_rate: {{ $item->tax_rate }}
        });
    @endforeach

    // Customer search functionality
    const customerSearch = document.getElementById('customer-search');
    const customerDropdown = document.getElementById('customer-dropdown');
    const customerIdInput = document.getElementById('customer-id');
    const customerSearchContainer = document.getElementById('customer-search-container');
    const customerDisplay = document.getElementById('customer-display');
    const customerDisplayName = document.getElementById('customer-display-name');
    const customerDisplayDetails = document.getElementById('customer-display-details');
    const customerLogoContainer = document.getElementById('customer-logo-container');
    const customerOptions = document.querySelectorAll('.customer-option');
    
    function displayCustomer(option) {
        const id = option.dataset.id;
        const name = option.dataset.name;
        const email = option.dataset.email || '';
        const phone = option.dataset.phone || '';
        const company = option.dataset.company || '';
        const address = option.dataset.address || '';
        const city = option.dataset.city || '';
        const state = option.dataset.state || '';
        const zip = option.dataset.zip || '';
        const country = option.dataset.country || '';
        const logo = option.dataset.logo || '';
        
        customerIdInput.value = id;
        
        // Hide search, show display
        customerSearchContainer.classList.add('hidden');
        customerDisplay.classList.remove('hidden');
        
        // Show Edit button
        const editButton = document.getElementById('customer-edit-button');
        if (editButton) {
            editButton.classList.remove('hidden');
        }
        
        // Set customer name
        customerDisplayName.textContent = company || name;
        
        // Update logo
        if (logo && customerLogoContainer) {
            customerLogoContainer.innerHTML = `<img id="customer-logo-img" src="${logo}" alt="${name}" class="w-full h-full object-contain p-1" style="background-color: rgba(248, 250, 252, 1);">`;
        } else if (customerLogoContainer) {
            customerLogoContainer.innerHTML = '<span class="material-symbols-outlined text-[#617589] text-2xl">business</span>';
        }
        
        // Build customer details HTML
        let detailsHTML = '';
        
        if (address) {
            detailsHTML += `<p>${address}</p>`;
        }
        
        const cityStateZip = [city, state, zip].filter(Boolean).join(', ');
        if (cityStateZip) {
            detailsHTML += `<p>${cityStateZip}</p>`;
        }
        
        if (phone) {
            detailsHTML += `<p>${phone}</p>`;
        }
        
        if (email) {
            detailsHTML += `<p>${email}</p>`;
        }
        
        customerDisplayDetails.innerHTML = detailsHTML || '<p class="text-[#617589]">No additional details</p>';
        customerDropdown.classList.add('hidden');
    }
    
    if (customerSearch) {
        customerSearch.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            let hasResults = false;
            
            customerOptions.forEach(option => {
                const name = option.dataset.name.toLowerCase();
                const email = (option.dataset.email || '').toLowerCase();
                const company = (option.dataset.company || '').toLowerCase();
                
                if (name.includes(searchTerm) || email.includes(searchTerm) || company.includes(searchTerm)) {
                    option.style.display = 'block';
                    hasResults = true;
                } else {
                    option.style.display = 'none';
                }
            });
            
            if (searchTerm && hasResults) {
                customerDropdown.classList.remove('hidden');
            } else if (!searchTerm) {
                customerDropdown.classList.add('hidden');
            }
        });
        
        customerSearch.addEventListener('focus', function() {
            if (this.value) {
                customerDropdown.classList.remove('hidden');
            }
        });
        
        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!customerSearch.contains(e.target) && !customerDropdown.contains(e.target)) {
                customerDropdown.classList.add('hidden');
            }
        });
        
        customerOptions.forEach(option => {
            option.addEventListener('click', function() {
                displayCustomer(this);
            });
        });
    }
    
    function clearCustomer() {
        customerIdInput.value = '';
        customerSearch.value = '';
        customerSearchContainer.classList.remove('hidden');
        customerDisplay.classList.add('hidden');
        customerDisplayDetails.innerHTML = '';
        customerDisplayName.textContent = '';
        
        // Hide Edit button
        const editButton = document.getElementById('customer-edit-button');
        if (editButton) {
            editButton.classList.add('hidden');
        }
    }
    
    window.clearCustomer = clearCustomer;

    // Signature preview
    const signatureSelect = document.querySelector('select[name="signature_id"]');
    @if(isset($signatures) && $signatures->count() > 0)
        const signatureData = {
            @foreach($signatures as $signature)
                {{ $signature->id }}: {
                    name: '{{ addslashes($signature->name) }}',
                    url: '{{ $signature->content && \Illuminate\Support\Facades\Storage::disk('public')->exists($signature->content) ? asset('storage/' . $signature->content) : '' }}'
                },
            @endforeach
        };
        
        if (signatureSelect) {
            signatureSelect.addEventListener('change', function() {
                const signatureId = this.value;
                const preview = document.getElementById('signature-preview');
                if (signatureId && preview && signatureData[signatureId]) {
                    const signature = signatureData[signatureId];
                    if (signature.url) {
                        preview.innerHTML = `<img src="${signature.url}" alt="${signature.name}" class="max-w-full max-h-32 object-contain">`;
                    } else {
                        preview.innerHTML = `<p class="text-sm text-[#617589]">${signature.name}</p>`;
                    }
                } else if (preview) {
                    preview.innerHTML = '<p class="text-sm text-[#617589]">Select a signature to preview</p>';
                }
            });
            
            // Initialize with selected signature if exists
            if (signatureSelect.value && signatureData[signatureSelect.value]) {
                const signature = signatureData[signatureSelect.value];
                const preview = document.getElementById('signature-preview');
                if (preview && signature.url) {
                    preview.innerHTML = `<img src="${signature.url}" alt="${signature.name}" class="max-w-full max-h-32 object-contain">`;
                }
            }
        }
    @endif
});
</script>

<script>
// Payment Method Modal Functions - Global scope
function openPaymentMethodModal() {
    const paymentMethodInput = document.getElementById('payment-method-input');
    const currentValue = paymentMethodInput ? paymentMethodInput.value : '';
    
    // Reset radio buttons
    document.querySelectorAll('input[name="payment_method_radio"]').forEach(radio => {
        radio.checked = false;
    });
    
    // Set bank account section hidden by default
    const bankSection = document.getElementById('bank-account-section');
    if (bankSection) {
        bankSection.classList.add('hidden');
    }
    
    // Restore previous selection if exists
    if (currentValue === 'online') {
        const onlineRadio = document.querySelector('input[name="payment_method_radio"][value="online"]');
        if (onlineRadio) onlineRadio.checked = true;
    } else if (currentValue && currentValue.toString().startsWith('bank_')) {
        const bankRadio = document.querySelector('input[name="payment_method_radio"][value="bank"]');
        if (bankRadio) {
            bankRadio.checked = true;
            if (bankSection) bankSection.classList.remove('hidden');
            const bankId = currentValue.toString().replace('bank_', '');
            const bankSelect = document.getElementById('bank-account-select');
            if (bankSelect) bankSelect.value = bankId;
        }
    }
    
    document.getElementById('payment-method-modal').classList.remove('hidden');
}

function savePaymentMethod() {
    const paymentMethod = document.querySelector('input[name="payment_method_radio"]:checked')?.value;
    const bankId = document.getElementById('bank-account-select').value;
    let paymentValue = paymentMethod || '';
    if (paymentMethod === 'bank' && bankId) {
        paymentValue = `bank_${bankId}`;
    }
    const paymentMethodInput = document.getElementById('payment-method-input');
    if (paymentMethodInput) {
        paymentMethodInput.value = paymentValue;
    }
    const preview = document.getElementById('payment-method-content');
    if (paymentMethod) {
        if (paymentMethod === 'online') {
            preview.textContent = 'Online Payment';
        } else if (paymentMethod === 'bank') {
            const bankSelect = document.getElementById('bank-account-select');
            const selectedOption = bankSelect.options[bankSelect.selectedIndex];
            if (selectedOption && selectedOption.text !== 'Select Bank Account') {
                preview.textContent = `Bank Transfer: ${selectedOption.text}`;
            } else {
                preview.textContent = 'Bank Transfer (No account selected)';
            }
        }
        preview.classList.remove('text-[#617589]');
        preview.classList.add('text-[#111418]');
    } else {
        preview.textContent = 'No payment method selected. Click "Add Payment Method" to select.';
        preview.classList.add('text-[#617589]');
        preview.classList.remove('text-[#111418]');
    }
    document.getElementById('payment-method-modal').classList.add('hidden');
}

// Make functions globally accessible
window.openPaymentMethodModal = openPaymentMethodModal;
window.savePaymentMethod = savePaymentMethod;

// Handle bank account radio change
document.addEventListener('DOMContentLoaded', function() {
    const bankRadio = document.getElementById('payment-method-bank');
    const bankSection = document.getElementById('bank-account-section');
    if (bankRadio && bankSection) {
        bankRadio.addEventListener('change', function() {
            bankSection.classList.toggle('hidden', !this.checked);
        });
    }
    
    // Also handle online payment selection
    const onlineRadio = document.querySelector('input[name="payment_method_radio"][value="online"]');
    if (onlineRadio && bankSection) {
        onlineRadio.addEventListener('change', function() {
            if (this.checked) {
                bankSection.classList.add('hidden');
            }
        });
    }
});
</script>

<!-- Payment Method Modal -->
<div id="payment-method-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-slate-900/50 backdrop-blur-sm" onclick="document.getElementById('payment-method-modal').classList.add('hidden')"></div>
        <div class="inline-block align-bottom bg-white rounded-xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-[#111418] text-gray-900">Add Payment Method</h3>
                    <button type="button" onclick="document.getElementById('payment-method-modal').classList.add('hidden')" class="text-[#617589] hover:text-[#111418] transition-colors">
                        <span class="material-symbols-outlined">close</span>
                    </button>
                </div>
                <div class="mb-4 space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-3">Select Payment Method</label>
                        <div class="space-y-3">
                            <label class="flex items-center p-4 border border-[#dbe0e6] rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="radio" name="payment_method_radio" value="online" class="mr-3 text-primary focus:ring-primary" {{ old('payment_method', $invoice->payment_method) == 'online' ? 'checked' : '' }}>
                                <div class="flex-1">
                                    <div class="font-medium text-[#111418] text-gray-900">Online Payment</div>
                                    <div class="text-xs text-[#617589] mt-1">Accept payments online via payment gateway</div>
                                </div>
                            </label>
                            <label class="flex items-center p-4 border border-[#dbe0e6] rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                                <input type="radio" name="payment_method_radio" value="bank" id="payment-method-bank" class="mr-3 text-primary focus:ring-primary" {{ (old('payment_method', $invoice->payment_method) && str_starts_with(old('payment_method', $invoice->payment_method), 'bank_')) ? 'checked' : '' }}>
                                <div class="flex-1">
                                    <div class="font-medium text-[#111418] text-gray-900">Bank Transfer</div>
                                    <div class="text-xs text-[#617589] mt-1">Pay via bank transfer to company account</div>
                                </div>
                            </label>
                        </div>
                    </div>
                    <div id="bank-account-section" class="{{ (old('payment_method', $invoice->payment_method) && str_starts_with(old('payment_method', $invoice->payment_method), 'bank_')) ? '' : 'hidden' }}">
                        <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Select Bank Account</label>
                        <select id="bank-account-select" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                            <option value="">Select Bank Account</option>
                            @foreach($bankAccounts ?? [] as $bankAccount)
                                @php
                                    $currentPaymentMethod = old('payment_method', $invoice->payment_method);
                                    $isSelected = ($currentPaymentMethod && str_starts_with($currentPaymentMethod, 'bank_') && str_replace('bank_', '', $currentPaymentMethod) == $bankAccount->id) || ($bankAccount->is_default ?? false);
                                @endphp
                                <option value="{{ $bankAccount->id }}" {{ $isSelected ? 'selected' : '' }}>
                                    {{ $bankAccount->bank_name }} - {{ $bankAccount->account_name }} ({{ $bankAccount->account_number }})
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="flex items-center justify-end gap-3">
                    <button type="button" onclick="document.getElementById('payment-method-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-[#617589] hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="button" onclick="savePaymentMethod()" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Payment Method</button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection



