@extends('layouts.admin')

@section('title', 'Create New Invoice')

@section('page-title', 'Create New Invoice')

@section('content')
<div class="flex-1 overflow-y-auto scroll-smooth pb-24">
    <div class="max-w-5xl mx-auto p-6">
        <form method="POST" action="{{ route('admin.invoices.store') }}" id="invoice-form" class="flex flex-col gap-6 w-full min-w-0">
                @csrf
                <input type="hidden" name="status" id="invoice-status" value="draft">
        <!-- 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 Title <span class="text-red-500">*</span></label>
                        <input name="title" value="{{ old('title', 'Invoice') }}" 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 placeholder:text-[#617589]" type="text"/>
                    </div>
                    <div class="md:col-span-1">
                        <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Invoice No. <span class="text-red-500">*</span></label>
                        <div class="relative">
                            <span class="absolute left-3 top-1/2 -translate-y-1/2 text-[#617589] font-medium">#</span>
                            <input name="invoice_number" id="invoice-number" value="{{ old('invoice_number', $nextInvoiceNumber ?? '') }}" required class="w-full h-11 pl-7 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 placeholder:text-[#617589]" type="text"/>
                        </div>
                        <p class="text-xs text-[#617589] mt-1">Auto-generated based on <a href="{{ route('admin.settings.modules', ['tab' => 'invoice']) }}" class="text-primary hover:underline">Invoice Settings</a></p>
                    </div>
                    <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>
                        <div class="relative">
                            <input name="issue_date" id="issue-date" value="{{ old('issue_date', now()->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 text-[#617589]" type="date"/>
                        </div>
                    </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>
                        <div class="relative">
                            <input name="due_date" id="due-date" value="{{ old('due_date', now()->addDays(30)->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 text-[#617589]" type="date"/>
                        </div>
                    </div>
                </div>
        </div>

        <!-- Section 2 & 3: Bill From / Bill To -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Bill From -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wider">Bill From <span class="text-red-500">*</span></h3>
                </div>
                <div class="space-y-4">
                    <!-- Company Search -->
                    <div id="company-search-container" class="relative">
                        <div class="relative">
                            <input type="text" id="company-search" autocomplete="off" placeholder="Company settings loaded automatically. Type to search other companies..." class="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 pr-10 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900 placeholder:text-gray-500"/>
                            <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-lg">search</span>
                            <input type="hidden" name="company_id" id="company-id" value="{{ old('company_id') }}"/>
                        </div>
                        <div id="company-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                            <!-- Results will be populated via AJAX -->
                        </div>
                        <div id="company-loading" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg p-4">
                            <div class="flex items-center gap-2 text-sm text-gray-500">
                                <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                                <span>Loading...</span>
                            </div>
                        </div>
                    </div>
                    <!-- Company Display Card -->
                    <div id="company-display" class="hidden">
                        <div class="bg-gray-50 rounded-lg border border-gray-200 p-4">
                            <div class="flex items-start gap-4">
                                <div id="company-logo-container" class="flex-shrink-0 w-12 h-12 rounded-lg bg-white border border-gray-200 flex items-center justify-center overflow-hidden">
                                    <span class="material-symbols-outlined text-gray-400">business</span>
                                </div>
                                <div class="flex-1">
                                    <h4 id="company-display-name" class="text-base font-bold text-gray-900 mb-2"></h4>
                                    <div class="text-sm text-gray-600 flex flex-col gap-1" id="company-display-details">
                                        <!-- Company details will be inserted here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Bill To -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex justify-between items-start mb-4">
                    <h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wider">Bill To <span class="text-red-500">*</span></h3>
                    <a href="{{ route('admin.customers.create') }}" target="_blank" class="text-primary text-sm font-medium hover:underline flex items-center gap-1">
                        <span class="material-symbols-outlined text-base">add</span>
                        <span>+ New Customer</span>
                    </a>
                </div>
                <div class="space-y-4">
                    <!-- Customer Search -->
                    <div id="customer-search-container" class="relative">
                        <div class="relative">
                            <input type="text" id="customer-search" autocomplete="off" placeholder="Type to search customers..." class="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 pr-10 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900 placeholder:text-gray-500"/>
                            <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-lg">search</span>
                            <input type="hidden" name="customer_id" id="customer-id" required value="{{ old('customer_id') }}"/>
                        </div>
                        <div id="customer-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                            <!-- Results will be populated via AJAX -->
                        </div>
                        <div id="customer-loading" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg p-4">
                            <div class="flex items-center gap-2 text-sm text-gray-500">
                                <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                                <span>Loading...</span>
                            </div>
                        </div>
                    </div>
                    <!-- Customer Display Card -->
                    <div id="customer-display" class="hidden">
                        <div class="bg-gray-50 rounded-lg border border-gray-200 p-4">
                            <div class="flex items-start gap-4">
                                <div id="customer-logo-container" class="flex-shrink-0 w-12 h-12 rounded-full bg-primary/20 flex items-center justify-center overflow-hidden text-primary font-bold">
                                    <span class="material-symbols-outlined text-gray-400">person</span>
                                </div>
                                <div class="flex-1">
                                    <h4 id="customer-display-name" class="text-base font-bold text-gray-900 mb-2"></h4>
                                    <div class="text-sm text-gray-600 flex flex-col gap-1" id="customer-display-details">
                                        <!-- Customer details will be inserted here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Invoice Items Section -->
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <!-- Settings Row -->
            <div class="flex flex-wrap gap-4 items-center justify-between mb-6 pb-6 border-b border-[#e5e7eb]">
                <div class="flex items-center gap-4">
                    <div class="flex flex-col gap-1">
                        <label class="text-xs font-medium text-[#617589]">Currency</label>
                        <div class="flex items-center gap-2">
                            <span class="material-symbols-outlined text-[#111418] text-gray-900 text-lg">attach_money</span>
                            <select name="currency" id="currency-select" class="text-sm font-bold text-[#111418] text-gray-900 bg-transparent border-none p-0 pr-6 focus:ring-0 cursor-pointer">
                                @php
                                    $defaultCurrency = $localizationSettings->default_currency ?? 'USD';
                                @endphp
                                @foreach($currencies as $currency)
                                    <option value="{{ $currency->code }}" {{ old('currency', $defaultCurrency) == $currency->code ? 'selected' : '' }} data-symbol="{{ $currency->symbol }}" data-position="{{ $currency->symbol_position ?? 'before' }}">
                                        {{ $currency->code }} - {{ $currency->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Table -->
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <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-24">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">
                        <!-- Row 1 -->
                        <tr class="group hover:bg-background-light/50 border-b border-[#f0f2f4]">
                            <td class="py-4 px-2 align-top">
                                <input name="items[0][description]" required class="w-full font-medium text-[#111418] text-gray-900 bg-transparent border-none p-0 focus:ring-0 placeholder:text-[#dbe0e6] mb-1" placeholder="Item name" type="text" value="{{ old('items.0.description', '') }}"/>
                                <textarea name="items[0][notes]" class="w-full text-[#617589] bg-transparent border-none p-0 focus:ring-0 text-sm resize-none overflow-hidden" placeholder="Add description..." rows="1">{{ old('items.0.notes', '') }}</textarea>
                            </td>
                            <td class="py-4 px-2 align-top">
                                <input name="items[0][quantity]" type="number" step="0.01" value="{{ old('items.0.quantity', '1') }}" required onchange="calculateRow(this)" 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"/>
                            </td>
                            <td class="py-4 px-2 align-top">
                                <input name="items[0][unit_price]" type="number" step="0.01" value="{{ old('items.0.unit_price', '0') }}" required onchange="calculateRow(this)" 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"/>
                            </td>
                            <td class="py-4 px-2 align-top">
                                <input name="items[0][tax_rate]" type="number" step="0.01" min="0" max="100" value="{{ old('items.0.tax_rate', '0') }}" onchange="calculateRow(this)" 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"/>
                            </td>
                            <td class="py-4 px-2 align-top text-right font-medium text-[#111418] text-gray-900">
                                <span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span class="item-amount">0.00</span>
                            </td>
                            <td class="py-4 px-2 align-top text-center">
                                <button type="button" onclick="removeItemRow(this)" class="text-red-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <span class="material-symbols-outlined text-lg">delete</span>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- Table Footer Actions -->
            <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">
            <!-- Left: Notes & Terms -->
            <div class="flex flex-col gap-6">
                <!-- Customer Notes Button -->
                <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">Customer Notes</h3>
                        <button type="button" onclick="openNotesModal()" 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 Notes</span>
                        </button>
                    </div>
                    <div id="notes-preview" class="min-h-[60px] p-3 rounded-lg border border-[#dbe0e6] bg-gray-50 text-sm text-[#617589]">
                        <p id="notes-content">{{ old('notes') ?: 'No notes added yet. Click "Add Notes" to add customer notes.' }}</p>
                    </div>
                    <textarea name="notes" id="notes-input" class="hidden">{{ old('notes') }}</textarea>
                </div>
                
                <!-- Terms & Conditions Button -->
                <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">Terms & Conditions</h3>
                        <button type="button" onclick="openTermsModal()" 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 Terms</span>
                        </button>
                    </div>
                    <div id="terms-preview" class="min-h-[60px] p-3 rounded-lg border border-[#dbe0e6] bg-gray-50 text-sm text-[#617589]">
                        <p id="terms-content">{{ old('terms') ?: 'No terms added yet. Click "Add Terms" to add terms and conditions.' }}</p>
                    </div>
                    <textarea name="terms" id="terms-input" class="hidden">{{ old('terms') }}</textarea>
                </div>
            </div>
            
            <!-- Right: Calculations -->
            <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6" style="height: 356px;">
                <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"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="subtotal">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center text-sm">
                        <span class="text-[#617589]">Tax</span>
                        <span class="font-medium text-[#111418] text-gray-900"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="tax-amount">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center text-sm">
                        <div class="flex items-center gap-2">
                            <span class="text-[#617589]">Discount</span>
                            <select name="discount_type" id="discount-type" class="text-xs border border-[#dbe0e6] rounded px-2 py-1 bg-white text-gray-900">
                                <option value="fixed">Fixed</option>
                                <option value="percentage">%</option>
                            </select>
                            <input name="discount_amount" id="discount-amount" type="number" step="0.01" min="0" value="{{ old('discount_amount', '0') }}" onchange="calculateTotal()" class="w-20 text-right border border-[#dbe0e6] rounded px-2 py-1 text-sm focus:border-primary focus:ring-1 focus:ring-primary text-gray-900"/>
                        </div>
                        <span class="font-medium text-[#111418] text-gray-900"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="discount-amount-display">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center text-sm pt-2 border-t border-dashed border-[#e5e7eb]">
                        <span class="text-[#617589]">Amount Paid</span>
                        <div class="flex items-center gap-2">
                            <input name="paid_amount" type="number" step="0.01" min="0" value="{{ old('paid_amount', '0') }}" onchange="calculateTotal()" class="w-24 text-right border border-[#dbe0e6] rounded px-2 py-1 text-sm focus:border-primary focus:ring-1 focus:ring-primary text-gray-900"/>
                        </div>
                    </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">Balance Due</span>
                        <span class="text-2xl font-bold text-primary"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="balance-due">0.00</span></span>
                    </div>
                </div>
            </div>
            
            <!-- Payment Method & Signature (Full Width) -->
            <div class="md:col-span-2 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 text-[#617589]">
                        <p id="payment-method-content">No payment method selected. Click "Add Payment Method" to select.</p>
                    </div>
                    <input type="hidden" name="payment_method" id="payment-method-input" value="{{ old('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') == $signature->id ? 'selected' : '' }}>{{ $signature->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    @if($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>
                        <script>
                            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
                            };
                        </script>
                    @endif
                </div>
            </div>
        </div>
        </form>
    </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.index') }}" 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="button" onclick="saveAsDraft()" class="px-6 py-2.5 rounded-lg border border-[#dbe0e6] text-[#111418] text-gray-900 font-medium hover:bg-background-light transition-colors">
                Save as Draft
            </button>
            <button type="button" onclick="previewInvoice()" 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">
                Preview <span class="material-symbols-outlined text-lg">preview</span>
            </button>
        </div>
    </div>
</div>

<script>
let itemIndex = 1;
const currencySymbols = {};
const currencyPositions = {};

// Initialize currency data
document.querySelectorAll('#currency-select option').forEach(option => {
    currencySymbols[option.value] = option.dataset.symbol || '$';
    currencyPositions[option.value] = option.dataset.position || 'before';
});

function updateCurrencySymbol() {
    const selectedCurrency = document.getElementById('currency-select').value;
    const symbol = currencySymbols[selectedCurrency] || '$';
    const position = currencyPositions[selectedCurrency] || 'before';
    
    document.querySelectorAll('.currency-symbol').forEach(el => {
        el.textContent = symbol;
    });
}

document.getElementById('currency-select').addEventListener('change', updateCurrencySymbol);

function addItemRow() {
    const tbody = document.getElementById('items-tbody');
    const row = tbody.insertRow();
    row.className = 'group hover:bg-background-light/50 border-b border-[#f0f2f4]';
    const symbol = document.querySelector('.currency-symbol').textContent;
    row.innerHTML = `
        <td class="py-4 px-2 align-top">
            <input name="items[${itemIndex}][description]" required class="w-full font-medium text-[#111418] text-gray-900 bg-transparent border-none p-0 focus:ring-0 placeholder:text-[#dbe0e6] mb-1" placeholder="Item name" type="text"/>
            <textarea name="items[${itemIndex}][notes]" class="w-full text-[#617589] bg-transparent border-none p-0 focus:ring-0 text-sm resize-none overflow-hidden" placeholder="Add description..." rows="1"></textarea>
        </td>
        <td class="py-4 px-2 align-top">
            <input name="items[${itemIndex}][quantity]" type="number" step="0.01" value="1" required onchange="calculateRow(this)" 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"/>
        </td>
        <td class="py-4 px-2 align-top">
            <input name="items[${itemIndex}][unit_price]" type="number" step="0.01" value="0" required onchange="calculateRow(this)" 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"/>
        </td>
        <td class="py-4 px-2 align-top">
            <input name="items[${itemIndex}][tax_rate]" type="number" step="0.01" min="0" max="100" value="0" onchange="calculateRow(this)" 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"/>
        </td>
        <td class="py-4 px-2 align-top text-right font-medium text-[#111418] text-gray-900">
            ${symbol}<span class="item-amount">0.00</span>
        </td>
        <td class="py-4 px-2 align-top text-center">
            <button type="button" onclick="removeItemRow(this)" class="text-red-400 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity">
                <span class="material-symbols-outlined text-lg">delete</span>
            </button>
        </td>
    `;
    itemIndex++;
}

function removeItemRow(button) {
    button.closest('tr').remove();
    calculateTotal();
}

function calculateRow(input) {
    const row = input.closest('tr');
    const quantity = parseFloat(row.querySelector('input[name*="[quantity]"]').value) || 0;
    const unitPrice = parseFloat(row.querySelector('input[name*="[unit_price]"]').value) || 0;
    const taxRate = parseFloat(row.querySelector('input[name*="[tax_rate]"]').value) || 0;
    
    const subtotal = quantity * unitPrice;
    const taxAmount = subtotal * (taxRate / 100);
    const total = subtotal + taxAmount;
    
    row.querySelector('.item-amount').textContent = total.toFixed(2);
    calculateTotal();
}

function calculateTotal() {
    let subtotal = 0;
    let taxAmount = 0;
    
    document.querySelectorAll('#items-tbody tr').forEach(row => {
        const quantity = parseFloat(row.querySelector('input[name*="[quantity]"]').value) || 0;
        const unitPrice = parseFloat(row.querySelector('input[name*="[unit_price]"]').value) || 0;
        const taxRate = parseFloat(row.querySelector('input[name*="[tax_rate]"]').value) || 0;
        
        const itemSubtotal = quantity * unitPrice;
        const itemTax = itemSubtotal * (taxRate / 100);
        
        subtotal += itemSubtotal;
        taxAmount += itemTax;
    });
    
    // Calculate discount
    const discountType = document.getElementById('discount-type').value;
    const discountAmount = parseFloat(document.getElementById('discount-amount').value) || 0;
    let discount = 0;
    
    if (discountType === 'percentage') {
        discount = subtotal * (discountAmount / 100);
    } else {
        discount = discountAmount;
    }
    
    const total = subtotal + taxAmount - discount;
    const paidAmount = parseFloat(document.querySelector('input[name="paid_amount"]').value) || 0;
    const balanceDue = total - paidAmount;
    
    document.getElementById('subtotal').textContent = subtotal.toFixed(2);
    document.getElementById('tax-amount').textContent = taxAmount.toFixed(2);
    document.getElementById('discount-amount-display').textContent = discount.toFixed(2);
    document.getElementById('balance-due').textContent = Math.max(0, balanceDue).toFixed(2);
}

function saveAsDraft() {
    document.getElementById('invoice-status').value = 'draft';
    document.getElementById('invoice-form').submit();
}

function previewInvoice() {
    // Create a temporary form to submit to preview route
    const form = document.getElementById('invoice-form');
    const formData = new FormData(form);
    
    // Create a temporary form element
    const tempForm = document.createElement('form');
    tempForm.method = 'POST';
    tempForm.action = '{{ route("admin.invoices.preview") }}';
    tempForm.style.display = 'none';
    
    // Add CSRF token
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = '_token';
    csrfInput.value = '{{ csrf_token() }}';
    tempForm.appendChild(csrfInput);
    
    // Copy all form data - handle arrays properly
    const processedKeys = new Set();
    for (let [key, value] of formData.entries()) {
        // Handle array inputs (e.g., items[0][description])
        if (key.includes('[') && key.includes(']')) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = key;
            input.value = value;
            tempForm.appendChild(input);
        } else {
            // Handle regular inputs - only add once per key
            if (!processedKeys.has(key)) {
                processedKeys.add(key);
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = key;
                input.value = value;
                tempForm.appendChild(input);
            }
        }
    }
    
    // Explicitly ensure payment_method is included
    const paymentMethodInput = document.getElementById('payment-method-input');
    if (paymentMethodInput && paymentMethodInput.value) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'payment_method';
        input.value = paymentMethodInput.value;
        tempForm.appendChild(input);
    }
    
    document.body.appendChild(tempForm);
    tempForm.submit();
}

// Initialize calculations
document.addEventListener('DOMContentLoaded', function() {
    // Load company settings first
    loadCompanySettings();
    
    document.querySelectorAll('input[name*="[quantity]"], input[name*="[unit_price]"], input[name*="[tax_rate]"]').forEach(input => {
        input.addEventListener('change', function() {
            calculateRow(this);
        });
    });
    
    document.getElementById('discount-type').addEventListener('change', calculateTotal);
    document.getElementById('discount-amount').addEventListener('input', calculateTotal);
    
    // ========== COMPANY DROPDOWN (AJAX) ==========
    const companySearch = document.getElementById('company-search');
    const companyDropdown = document.getElementById('company-dropdown');
    const companyLoading = document.getElementById('company-loading');
    const companyIdInput = document.getElementById('company-id');
    const companySearchContainer = document.getElementById('company-search-container');
    const companyDisplay = document.getElementById('company-display');
    const companyDisplayName = document.getElementById('company-display-name');
    const companyDisplayDetails = document.getElementById('company-display-details');
    const companyLogoContainer = document.getElementById('company-logo-container');
    
    let companySearchTimeout;
    let companyAbortController;
    
    function displayCompany(company) {
        // If company doesn't have an id (from settings), we'll use a special identifier
        if (company.id) {
            companyIdInput.value = company.id;
        } else {
            // For company settings, we'll use a special value or leave it empty
            // The form will use company settings instead
            companyIdInput.value = '';
        }
        
        companySearch.value = company.name;
        companyDisplay.classList.remove('hidden');
        
        companyDisplayName.textContent = company.name;
        
        // Handle logo display - logo is already a full URL from the API
        if (company.logo) {
            // The logo field from API is already a full URL (Storage::url())
            const logoUrl = company.logo;
            const img = document.createElement('img');
            img.src = logoUrl;
            img.alt = company.name;
            img.className = 'w-full h-full object-cover rounded-lg';
            img.onerror = function() {
                companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
            };
            companyLogoContainer.innerHTML = '';
            companyLogoContainer.appendChild(img);
        } else if (company.logo_path) {
            // Fallback: if logo_path exists but logo doesn't, build the URL
            const logoUrl = '{{ asset("storage") }}/' + company.logo_path;
            const img = document.createElement('img');
            img.src = logoUrl;
            img.alt = company.name;
            img.className = 'w-full h-full object-cover rounded-lg';
            img.onerror = function() {
                companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
            };
            companyLogoContainer.innerHTML = '';
            companyLogoContainer.appendChild(img);
        } else {
            companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
        }
        
        // Show key company contact details
        let detailsHTML = '';
        if (company.email) detailsHTML += `<p>${company.email}</p>`;
        if (company.phone) detailsHTML += `<p>${company.phone}</p>`;
        if (company.address) detailsHTML += `<p>${company.address}</p>`;
        
        companyDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
        companyDropdown.classList.add('hidden');
    }

    // Load company settings on page load
    async function loadCompanySettings() {
        try {
            const response = await fetch('{{ route("admin.invoices.api.company-settings") }}', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                },
                credentials: 'same-origin',
            });
            const data = await response.json();
            
            if (data.success && data.company && data.company.name) {
                // Auto-populate company settings
                displayCompany(data.company);
            }
        } catch (error) {
            console.error('Error loading company settings:', error);
        }
    }
    
    function searchCompanies(searchTerm) {
        // Cancel previous request
        if (companyAbortController) {
            companyAbortController.abort();
        }
        companyAbortController = new AbortController();
        
        companyLoading.classList.remove('hidden');
        companyDropdown.classList.add('hidden');
        
        fetch('{{ route("admin.api.companies") }}?search=' + encodeURIComponent(searchTerm), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            credentials: 'same-origin',
            signal: companyAbortController.signal
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Request failed');
            }
            return response.json();
        })
        .then(data => {
            companyLoading.classList.add('hidden');
            
            if (data.success && data.companies && data.companies.length > 0) {
                companyDropdown.innerHTML = '';
                data.companies.forEach(company => {
                    const option = document.createElement('div');
                    option.className = 'company-option px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-[#e5e7eb] last:border-b-0';
                    option.innerHTML = `
                        <div class="font-medium text-[#111418] text-gray-900">${company.name}</div>
                        ${company.email ? `<div class="text-xs text-[#617589]">${company.email}</div>` : ''}
                    `;
                    option.addEventListener('click', () => displayCompany(company));
                    companyDropdown.appendChild(option);
                });
                companyDropdown.classList.remove('hidden');
            } else {
                companyDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-[#617589]">No companies found</div>';
                companyDropdown.classList.remove('hidden');
            }
        })
        .catch(error => {
            if (error.name !== 'AbortError') {
                console.error('Error fetching companies:', error);
                companyLoading.classList.add('hidden');
                companyDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-red-500">Error loading companies</div>';
                companyDropdown.classList.remove('hidden');
            }
        });
    }
    
    if (companySearch) {
        companySearch.addEventListener('input', function() {
            const searchTerm = this.value.trim();
            
            clearTimeout(companySearchTimeout);
            companySearchTimeout = setTimeout(() => {
                searchCompanies(searchTerm);
            }, 300); // Debounce 300ms
        });
        
        companySearch.addEventListener('focus', function() {
            searchCompanies(this.value.trim());
        });
        
        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!companySearch.contains(e.target) && !companyDropdown.contains(e.target) && !companyLoading.contains(e.target)) {
                companyDropdown.classList.add('hidden');
                companyLoading.classList.add('hidden');
            }
        });
    }
    
    function clearCompany() {
        companyIdInput.value = '';
        companySearch.value = '';
        companySearchContainer.classList.remove('hidden');
        companyDisplay.classList.add('hidden');
        companyDisplayDetails.innerHTML = '';
        companyDisplayName.textContent = '';
        companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
        
        // Hide Edit button
        const editButton = document.getElementById('company-edit-button');
        if (editButton) {
            editButton.classList.add('hidden');
        }
    }
    
    // ========== CUSTOMER DROPDOWN (AJAX) ==========
    const customerSearch = document.getElementById('customer-search');
    const customerDropdown = document.getElementById('customer-dropdown');
    const customerLoading = document.getElementById('customer-loading');
    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');
    
    let customerSearchTimeout;
    let customerAbortController;
    
    function displayCustomer(customer) {
        customerIdInput.value = customer.id;
        
        customerSearch.value = customer.name;
        customerDisplay.classList.remove('hidden');
        
        // Display name - use company name for customers if available, otherwise use name
        const displayName = customer.company || customer.name;
        customerDisplayName.textContent = displayName;
        
        if (customer.image) {
            const imageUrl = customer.image.startsWith('http') || customer.image.startsWith('/')
                ? customer.image
                : (customer.image_path ? '{{ asset("storage") }}/' + customer.image_path : customer.image);
            customerLogoContainer.innerHTML = `<img src="${imageUrl}" alt="${customer.name}" class="w-full h-full object-cover rounded-full" onerror="this.parentElement.innerHTML='<span class=\\'text-primary font-bold\\'>${(customer.name || 'N').charAt(0).toUpperCase()}</span>'">`;
        } else {
            const initial = (customer.name || 'N').charAt(0).toUpperCase();
            customerLogoContainer.innerHTML = `<span class="text-primary font-bold">${initial}</span>`;
        }
        
        let detailsHTML = '';
        if (customer.email) detailsHTML += `<p><strong>Email:</strong> ${customer.email}</p>`;
        if (customer.phone) detailsHTML += `<p><strong>Phone:</strong> ${customer.phone}</p>`;
        if (customer.address) detailsHTML += `<p><strong>Address:</strong> ${customer.address}</p>`;
        if (customer.city || customer.state || customer.zip) {
            const location = [customer.city, customer.state, customer.zip].filter(Boolean).join(', ');
            if (location) detailsHTML += `<p>${location}</p>`;
        }
        if (customer.country) detailsHTML += `<p>${customer.country}</p>`;
        
        customerDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
        customerDropdown.classList.add('hidden');
    }
    
    function searchCustomers(searchTerm) {
        // Cancel previous request
        if (customerAbortController) {
            customerAbortController.abort();
        }
        customerAbortController = new AbortController();
        
        customerLoading.classList.remove('hidden');
        customerDropdown.classList.add('hidden');
        
        fetch('{{ route("admin.api.customers") }}?search=' + encodeURIComponent(searchTerm), {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            credentials: 'same-origin',
            signal: customerAbortController.signal
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Request failed');
            }
            return response.json();
        })
        .then(data => {
            customerLoading.classList.add('hidden');
            
            if (data.success && data.customers && data.customers.length > 0) {
                customerDropdown.innerHTML = '';
                data.customers.forEach(customer => {
                    const option = document.createElement('div');
                    option.className = 'customer-option px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-[#e5e7eb] last:border-b-0';
                    option.innerHTML = `
                        <div class="font-medium text-[#111418] text-gray-900">${customer.name}</div>
                        ${customer.email ? `<div class="text-xs text-[#617589]">${customer.email}</div>` : ''}
                    `;
                    option.addEventListener('click', () => displayCustomer(customer));
                    customerDropdown.appendChild(option);
                });
                customerDropdown.classList.remove('hidden');
                } else {
                customerDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-[#617589]">No customers found</div>';
                customerDropdown.classList.remove('hidden');
            }
        })
        .catch(error => {
            if (error.name !== 'AbortError') {
                console.error('Error fetching customers:', error);
                customerLoading.classList.add('hidden');
                customerDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-red-500">Error loading customers</div>';
                customerDropdown.classList.remove('hidden');
            }
        });
    }
    
    if (customerSearch) {
        customerSearch.addEventListener('input', function() {
            const searchTerm = this.value.trim();
            
            clearTimeout(customerSearchTimeout);
            customerSearchTimeout = setTimeout(() => {
                searchCustomers(searchTerm);
            }, 300); // Debounce 300ms
        });
        
        customerSearch.addEventListener('focus', function() {
            searchCustomers(this.value.trim());
        });
        
        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!customerSearch.contains(e.target) && !customerDropdown.contains(e.target) && !customerLoading.contains(e.target)) {
                customerDropdown.classList.add('hidden');
                customerLoading.classList.add('hidden');
            }
        });
    }
    
    function clearCustomer() {
        customerIdInput.value = '';
        customerSearch.value = '';
        customerSearchContainer.classList.remove('hidden');
        customerDisplay.classList.add('hidden');
        customerDisplayDetails.innerHTML = '';
        customerDisplayName.textContent = '';
        customerLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">person</span>';
        
        // Hide Edit button
        const editButton = document.getElementById('customer-edit-button');
        if (editButton) {
            editButton.classList.add('hidden');
        }
    }
    
    // Signature preview
    const signatureSelect = document.querySelector('select[name="signature_id"]');
    if (signatureSelect && typeof signatureData !== 'undefined') {
        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">`;
            }
        }
    }
    
    calculateTotal();
});
</script>

<script>
// Notes Modal Functions - Global scope
function openNotesModal() {
    const notesInput = document.getElementById('notes-input');
    const notesTextarea = document.getElementById('notes-modal-textarea');
    if (notesInput && notesTextarea) {
        notesTextarea.value = notesInput.value || '';
    }
    document.getElementById('notes-modal').classList.remove('hidden');
}

function saveNotes() {
    const notesText = document.getElementById('notes-modal-textarea').value;
    const notesInput = document.getElementById('notes-input');
    if (notesInput) {
        notesInput.value = notesText;
    }
    const preview = document.getElementById('notes-content');
    if (notesText.trim()) {
        preview.textContent = notesText;
        preview.classList.remove('text-[#617589]');
        preview.classList.add('text-[#111418]');
    } else {
        preview.textContent = 'No notes added yet. Click "Add Notes" to add customer notes.';
        preview.classList.add('text-[#617589]');
        preview.classList.remove('text-[#111418]');
    }
    document.getElementById('notes-modal').classList.add('hidden');
}

// Terms Modal Functions - Global scope
function openTermsModal() {
    const termsInput = document.getElementById('terms-input');
    const termsTextarea = document.getElementById('terms-modal-textarea');
    if (termsInput && termsTextarea) {
        termsTextarea.value = termsInput.value || '';
    }
    document.getElementById('terms-modal').classList.remove('hidden');
}

function saveTerms() {
    const termsText = document.getElementById('terms-modal-textarea').value;
    const termsInput = document.getElementById('terms-input');
    if (termsInput) {
        termsInput.value = termsText;
    }
    const preview = document.getElementById('terms-content');
    if (termsText.trim()) {
        preview.textContent = termsText;
        preview.classList.remove('text-[#617589]');
        preview.classList.add('text-[#111418]');
    } else {
        preview.textContent = 'No terms added yet. Click "Add Terms" to add terms and conditions.';
        preview.classList.add('text-[#617589]');
        preview.classList.remove('text-[#111418]');
    }
    document.getElementById('terms-modal').classList.add('hidden');
}

// 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 via window object for inline handlers
window.openNotesModal = openNotesModal;
window.saveNotes = saveNotes;
window.openTermsModal = openTermsModal;
window.saveTerms = saveTerms;
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>

<script>
// Initialize modals with existing values after page load
document.addEventListener('DOMContentLoaded', function() {
    @if(old('notes'))
        const notesTextarea = document.getElementById('notes-modal-textarea');
        if (notesTextarea) {
            notesTextarea.value = {!! json_encode(old('notes')) !!};
            if (typeof saveNotes === 'function') {
                saveNotes();
            }
        }
    @endif
    
    @if(old('terms'))
        const termsTextarea = document.getElementById('terms-modal-textarea');
        if (termsTextarea) {
            termsTextarea.value = {!! json_encode(old('terms')) !!};
            if (typeof saveTerms === 'function') {
                saveTerms();
            }
        }
    @endif
    
    @if(old('payment_method'))
        const paymentMethod = {!! json_encode(old('payment_method')) !!};
        if (paymentMethod === 'online') {
            const onlineRadio = document.querySelector('input[name="payment_method_radio"][value="online"]');
            if (onlineRadio) onlineRadio.checked = true;
        } else if (paymentMethod && paymentMethod.toString().startsWith('bank_')) {
            const bankRadio = document.querySelector('input[name="payment_method_radio"][value="bank"]');
            if (bankRadio) {
                bankRadio.checked = true;
                const bankSection = document.getElementById('bank-account-section');
                if (bankSection) bankSection.classList.remove('hidden');
                const bankId = paymentMethod.toString().replace('bank_', '');
                const bankSelect = document.getElementById('bank-account-select');
                if (bankSelect) {
                    bankSelect.value = bankId;
                }
            }
        }
        if (typeof savePaymentMethod === 'function') {
            savePaymentMethod();
        }
    @endif
});
</script>

<style>
/* Custom scrollbar for clean look */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
    background: #9ca3af;
}
</style>

<!-- Notes Modal -->
<div id="notes-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('notes-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 Customer Notes</h3>
                    <button type="button" onclick="document.getElementById('notes-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">
                    <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Notes</label>
                    <textarea id="notes-modal-textarea" rows="6" 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 placeholder:text-[#617589]" placeholder="Add customer notes...">{{ old('notes') }}</textarea>
                </div>
                <div class="flex items-center justify-end gap-3">
                    <button type="button" onclick="document.getElementById('notes-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="saveNotes()" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Notes</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Terms & Conditions Modal -->
<div id="terms-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('terms-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 Terms & Conditions</h3>
                    <button type="button" onclick="document.getElementById('terms-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">
                    <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Terms & Conditions</label>
                    <textarea id="terms-modal-textarea" rows="6" 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 placeholder:text-[#617589]" placeholder="Add terms and conditions...">{{ old('terms') }}</textarea>
                </div>
                <div class="flex items-center justify-end gap-3">
                    <button type="button" onclick="document.getElementById('terms-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="saveTerms()" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Save Terms</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 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') == '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') && str_starts_with(old('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') && str_starts_with(old('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)
                                <option value="{{ $bankAccount->id }}" {{ ($bankAccount->is_default ?? false) ? 'selected' : '' }}>
                                    {{ $bankAccount->bank_name }} - {{ $bankAccount->account_name }} ({{ $bankAccount->account_number }})
                                </option>
                            @endforeach
                        </select>
                        @if(isset($bankAccounts) && $bankAccounts->count() > 0)
                            @php
                                $defaultBank = $bankAccounts->where('is_default', true)->first() ?? $bankAccounts->first();
                            @endphp
                            @if($defaultBank)
                                <div class="mt-3 p-3 bg-gray-50 rounded-lg text-xs text-[#617589]">
                                    <p class="font-medium text-[#111418] text-gray-900 mb-1">Bank Details:</p>
                                    <p>Account Name: {{ $defaultBank->account_name }}</p>
                                    <p>Account Number: {{ $defaultBank->account_number }}</p>
                                    @if($defaultBank->bank_code)
                                        <p>Routing Number: {{ $defaultBank->bank_code }}</p>
                                    @endif
                                    @if($defaultBank->swift_code)
                                        <p>SWIFT Code: {{ $defaultBank->swift_code }}</p>
                                    @endif
                                    @if($defaultBank->branch_address)
                                        <p>Address: {{ $defaultBank->branch_address }}</p>
                                    @endif
                                </div>
                            @endif
                        @endif
                    </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
