@extends('layouts.admin')

@section('title', 'New Credit Note')

@section('page-title', 'New Credit Note')

@push('styles')
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400;700&family=Great+Vibes&family=Allura&family=Brush+Script+MT&family=Pacifico&display=swap" rel="stylesheet">
<style>
    #signature-canvas {
        display: block;
        max-width: 100%;
        height: auto;
    }
    #signature-preview-text {
        min-height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
</style>
@endpush

@section('breadcrumbs')
    <a href="{{ route('admin.credit-notes.index') }}" class="hover:text-primary">Credit Notes</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">New Credit Note</span>
@endsection

@section('content')
<form method="POST" action="{{ route('admin.credit-notes.store') }}" class="max-w-7xl mx-auto" enctype="multipart/form-data">
    @csrf
    @if ($errors->any())
        <div class="mb-6 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 space-y-1">
            <p class="font-medium">Please fix the following:</p>
            <ul class="list-disc list-inside">
                @foreach ($errors->all() as $message)
                    <li>{{ $message }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Content -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Credit Note Info -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-bold text-gray-900 text-gray-900">Credit Note Information</h2>
                </div>
                <div class="p-6 grid grid-cols-1 md:grid-cols-3 gap-6">
                    <!-- Invoice -->
                    <div>
                        <label for="invoice_id" class="block text-sm font-medium text-gray-700 mb-2">
                            Invoice <span class="text-red-500">*</span>
                        </label>
                        <select id="invoice_id" name="invoice_id" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="">Search and select invoice</option>
                            @foreach(($invoices ?? []) as $invoice)
                                <option
                                    value="{{ $invoice->id }}"
                                    data-customer-id="{{ $invoice->customer_id }}"
                                    data-customer-name="{{ $invoice->customer->name ?? '' }}"
                                    {{ old('invoice_id') == $invoice->id ? 'selected' : '' }}
                                >
                                    {{ $invoice->invoice_number }} - {{ $invoice->customer->name ?? 'N/A' }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Credit Note Date -->
                    <div>
                        <label for="credit_note_date" class="block text-sm font-medium text-gray-700 mb-2">
                            Credit Note Date <span class="text-red-500">*</span>
                        </label>
                        <input type="date" id="credit_note_date" name="credit_note_date" value="{{ old('credit_note_date', date('Y-m-d')) }}" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                    </div>

                    <!-- Status -->
                    <div>
                        <label for="status" class="block text-sm font-medium text-gray-700 mb-2">
                            Status <span class="text-red-500">*</span>
                        </label>
                        <select id="status" name="status" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="pending" {{ old('status', 'pending') == 'pending' ? 'selected' : '' }}>Pending</option>
                            <option value="approved" {{ old('status') == 'approved' ? 'selected' : '' }}>Approved</option>
                            <option value="rejected" {{ old('status') == 'rejected' ? 'selected' : '' }}>Rejected</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Bill From / Bill To: same pattern as delivery challan -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 relative z-[60] isolate">
                <!-- Bill From -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 relative overflow-visible">
                    <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">
                        <input type="hidden" name="company_id" id="company-id" value="{{ old('company_id', $defaultBillFromCompanyId ?? '') }}"/>
                        <div id="company-search-container" class="relative z-[70]">
                            <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>
                            </div>
                            <div id="company-dropdown" class="hidden absolute left-0 right-0 top-full z-[200] mt-1 bg-white border border-gray-300 rounded-lg shadow-xl max-h-60 overflow-y-auto"></div>
                            <div id="company-loading" class="hidden absolute left-0 right-0 top-full z-[200] mt-1 bg-white border border-gray-300 rounded-lg shadow-xl 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>
                        <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"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bill To -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 relative overflow-visible">
                    <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" rel="noopener noreferrer" 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">
                        <div id="customer-search-container" class="relative z-[70]">
                            <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" value="{{ old('customer_id') }}"/>
                            </div>
                            <div id="customer-dropdown" class="hidden absolute left-0 right-0 top-full z-[200] mt-1 bg-white border border-gray-300 rounded-lg shadow-xl max-h-60 overflow-y-auto"></div>
                            <div id="customer-loading" class="hidden absolute left-0 right-0 top-full z-[200] mt-1 bg-white border border-gray-300 rounded-lg shadow-xl 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>
                        <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"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Products Table -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden relative z-10">
                <div class="overflow-x-auto">
                    <table class="w-full text-left table-fixed">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-[32%]">Product / Service</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-24 min-w-[6rem]">Unit</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-24">Quantity</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-28">Rate</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-24">Discount</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-20">Tax</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-28 text-right">Amount</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-16">Action</th>
                            </tr>
                        </thead>
                        <tbody id="product-rows" class="divide-y divide-gray-100">
                            <tr class="product-row">
                                <td class="py-3 px-4 align-top">
                                    <input type="hidden" name="items[0][product_id]" class="product-id-input">
                                    <input type="text" name="items[0][product]" placeholder="Search or type product..." class="product-search-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" autocomplete="off">
                                </td>
                                <td class="py-3 px-4 min-w-[6rem] align-top">
                                    <input type="text" name="items[0][unit]" class="product-unit-input w-full min-w-0 h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-[14px] focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                </td>
                                <td class="py-3 px-4 align-top">
                                    <input type="number" name="items[0][quantity]" value="1" min="1" step="1" class="product-quantity-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                </td>
                                <td class="py-3 px-4 align-top">
                                    <input type="number" name="items[0][rate]" value="0" step="0.01" min="0" class="product-rate-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                </td>
                                <td class="py-3 px-4 align-top">
                                    <input type="number" name="items[0][discount]" value="0" step="0.01" min="0" class="product-discount-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                </td>
                                <td class="py-3 px-4 align-top">
                                    <input type="number" name="items[0][tax]" value="0" step="0.01" min="0" class="product-tax-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
                                </td>
                                <td class="py-3 px-4 text-right align-top">
                                    <span class="product-amount text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                                </td>
                                <td class="py-3 px-4">
                                    <button type="button" onclick="removeRow(this)" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100700 rounded-lg transition-colors">
                                        <span class="material-symbols-outlined text-lg">delete</span>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="px-4 py-3 border-t border-gray-200">
                    <button type="button" onclick="addNewRow()" class="flex items-center gap-2 text-sm text-primary hover:text-blue-600">
                        <span class="material-symbols-outlined text-lg">add</span>
                        Add New Row
                    </button>
                </div>
            </div>

            <!-- Extra Information (tabs — same pattern as delivery challan) -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-x-hidden overflow-y-visible">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-bold text-gray-900">Extra Information</h2>
                </div>
                <div class="p-6">
                    <div class="flex gap-2 mb-4 border-b border-gray-200 flex-wrap">
                        <button type="button" onclick="cnSwitchTab('notes')" id="cn-tab-notes" class="cn-tab-btn px-4 py-2 text-sm font-medium text-gray-700 border-b-2 border-primary bg-primary/5 transition-colors">
                            Add Notes
                        </button>
                        <button type="button" onclick="cnSwitchTab('terms')" id="cn-tab-terms" class="cn-tab-btn px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors">
                            Add Terms & Conditions
                        </button>
                        <button type="button" onclick="cnSwitchTab('payment')" id="cn-tab-payment" class="cn-tab-btn px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors">
                            Payment Details
                        </button>
                    </div>
                    <div id="cn-content-notes" class="cn-tab-content">
                        <label for="notes" class="block text-sm font-medium text-gray-700 mb-2">Additional Notes</label>
                        <textarea id="notes" name="notes" rows="4" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none" placeholder="Enter notes">{{ old('notes') }}</textarea>
                    </div>
                    <div id="cn-content-terms" class="cn-tab-content hidden">
                        <label for="terms" class="block text-sm font-medium text-gray-700 mb-2">Terms & Conditions</label>
                        <textarea id="terms" name="terms" rows="4" class="w-full px-4 py-3 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow resize-none" placeholder="Enter terms">{{ old('terms') }}</textarea>
                    </div>
                    <div id="cn-content-payment" class="cn-tab-content hidden">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Payment Method</label>
                                <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-3">
                                    <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="radio" name="payment_method" value="cash" {{ old('payment_method', 'cash') == 'cash' ? 'checked' : '' }} class="text-primary focus:ring-primary cn-payment-method-radio" id="cn-payment-cash">
                                        <span class="text-sm text-gray-700">Cash</span>
                                    </label>
                                    <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="radio" name="payment_method" value="bank_transfer" {{ old('payment_method') == 'bank_transfer' ? 'checked' : '' }} class="text-primary focus:ring-primary cn-payment-method-radio" id="cn-payment-bank-transfer">
                                        <span class="text-sm text-gray-700">Bank Transfer</span>
                                    </label>
                                    <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="radio" name="payment_method" value="credit_card" {{ old('payment_method') == 'credit_card' ? 'checked' : '' }} class="text-primary focus:ring-primary cn-payment-method-radio" id="cn-payment-credit-card">
                                        <span class="text-sm text-gray-700">Credit Card</span>
                                    </label>
                                    <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                        <input type="radio" name="payment_method" value="cheque" {{ old('payment_method') == 'cheque' ? 'checked' : '' }} class="text-primary focus:ring-primary cn-payment-method-radio" id="cn-payment-cheque">
                                        <span class="text-sm text-gray-700">Cheque</span>
                                    </label>
                                </div>
                            </div>
                            <div id="cn-bank-account-field" class="hidden">
                                <label for="cn-bank-account-select" class="block text-sm font-medium text-gray-700 mb-2">Select Bank Account <span class="text-red-500">*</span></label>
                                <select id="cn-bank-account-select" name="bank_account_id" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                                    <option value="">Select bank account...</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Signature (same pattern as delivery challan) -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-bold text-gray-900">Signature</h2>
                </div>
                <div class="p-6 space-y-4">
                    <div class="flex gap-4">
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="signature_type" value="manual" {{ old('signature_type', 'manual') == 'manual' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="cn-signature-type-manual">
                            <span class="text-sm text-gray-700">Manual Signature</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="signature_type" value="esignature" {{ old('signature_type') == 'esignature' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="cn-signature-type-esignature">
                            <span class="text-sm text-gray-700">eSignature</span>
                        </label>
                    </div>
                    <div id="manual-signature-container" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Manual Signature Type <span class="text-red-500">*</span></label>
                            <div class="grid grid-cols-1 lg:grid-cols-3 gap-3">
                                <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                    <input type="radio" name="manual_signature_type" value="draw" {{ old('manual_signature_type') == 'draw' ? 'checked' : '' }} class="text-primary focus:ring-primary">
                                    <span class="text-sm text-gray-700">Draw Signature (Canvas)</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                    <input type="radio" name="manual_signature_type" value="upload" {{ old('manual_signature_type') == 'upload' ? 'checked' : '' }} class="text-primary focus:ring-primary">
                                    <span class="text-sm text-gray-700">Upload Signature Image</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                                    <input type="radio" name="manual_signature_type" value="type" {{ old('manual_signature_type') == 'type' ? 'checked' : '' }} class="text-primary focus:ring-primary">
                                    <span class="text-sm text-gray-700">Type Signature (Auto-generated font styles)</span>
                                </label>
                            </div>
                        </div>
                        <div id="draw-signature-container" class="hidden">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Draw Your Signature <span class="text-red-500">*</span></label>
                            <div class="border-2 border-gray-300 rounded-lg bg-white">
                                <canvas id="signature-canvas" width="600" height="200" class="w-full cursor-crosshair"></canvas>
                            </div>
                            <div class="flex gap-2 mt-2">
                                <button type="button" id="clear-canvas" class="px-4 py-2 text-sm text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">Clear</button>
                            </div>
                            <input type="hidden" id="signature-canvas-data" name="signature_canvas_data">
                        </div>
                        <div id="upload-signature-container" class="hidden">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Upload Signature Image <span class="text-red-500">*</span></label>
                            <input type="file" id="signature-upload" name="signature_upload" accept="image/*" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <p class="mt-1 text-xs text-gray-500">JPG, PNG or GIF format, not exceeding 5MB.</p>
                            <div id="signature-upload-preview" class="mt-2 hidden">
                                <img id="signature-preview-img" src="" alt="Signature Preview" class="max-w-xs border border-gray-200 rounded-lg">
                            </div>
                        </div>
                        <div id="type-signature-container" class="hidden">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Type Your Signature <span class="text-red-500">*</span></label>
                            <input type="text" id="signature-text" name="signature_text" value="{{ old('signature_text') }}" placeholder="Enter your name" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <div class="mt-2">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Font Style</label>
                                <select id="signature-font" name="signature_font" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                                    <option value="dancing" {{ old('signature_font', 'dancing') == 'dancing' ? 'selected' : '' }}>Dancing Script</option>
                                    <option value="great-vibes" {{ old('signature_font') == 'great-vibes' ? 'selected' : '' }}>Great Vibes</option>
                                    <option value="allura" {{ old('signature_font') == 'allura' ? 'selected' : '' }}>Allura</option>
                                    <option value="brush" {{ old('signature_font') == 'brush' ? 'selected' : '' }}>Brush Script</option>
                                    <option value="pacifico" {{ old('signature_font') == 'pacifico' ? 'selected' : '' }}>Pacifico</option>
                                </select>
                            </div>
                            <div id="signature-text-preview" class="mt-4 p-4 border border-gray-200 rounded-lg bg-gray-50 text-center">
                                <p class="text-2xl" id="signature-preview-text" style="font-family: 'Dancing Script', cursive;">Your signature will appear here</p>
                            </div>
                        </div>
                    </div>
                    <div id="esignature-container" class="hidden">
                        <label for="signature_id" class="block text-sm font-medium text-gray-700 mb-2">Select Signature Name <span class="text-red-500">*</span></label>
                        <select id="signature_id" name="signature_id" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="">Select signature...</option>
                        </select>
                        <div id="cn-esignature-preview" class="mt-4 min-h-[80px] border border-gray-200 rounded-lg flex items-center justify-center bg-gray-50 p-2">
                            <span class="text-sm text-gray-400">No signature selected</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sidebar - Summary -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden sticky top-6">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-bold text-gray-900 text-gray-900">Summary</h2>
                </div>
                <div class="p-6 space-y-4">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Amount</span>
                        <span class="summary-amount text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Tax</span>
                        <span class="summary-tax text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Discount</span>
                        <span class="summary-discount text-sm font-medium text-gray-900">- {{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                    </div>
                    <hr class="border-gray-200">
                    <div class="flex justify-between items-center">
                        <span class="text-base font-semibold text-gray-900">Total (Rounded)</span>
                        <span class="summary-total text-lg font-bold text-gray-900">{{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                    </div>
                    <p class="summary-total-words text-sm text-gray-500 italic">Zero</p>
                </div>
                <div class="px-6 py-4 border-t border-gray-200 space-y-3">
                    <button type="submit" class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-blue-600 transition-colors flex items-center justify-center gap-2">
                        <span class="material-symbols-outlined">save</span>
                        Save Credit Note
                    </button>
                    <a href="{{ route('admin.credit-notes.index') }}" class="w-full py-3 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors flex items-center justify-center gap-2">
                        Cancel
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

@push('scripts')
@php
    $cnDefaultCurrency = \App\Models\Currency::getDefault();
    $cnCurrencyClient = [
        'code' => $defaultCurrencyCode ?? \App\Models\Currency::getDefaultCode(),
        'symbol' => $cnDefaultCurrency ? $cnDefaultCurrency->symbol : \App\Models\Currency::getSymbol(),
        'symbolPosition' => $cnDefaultCurrency && $cnDefaultCurrency->symbol_position ? $cnDefaultCurrency->symbol_position : 'before',
        'decimalPlaces' => $cnDefaultCurrency ? (int) $cnDefaultCurrency->decimal_places : 2,
    ];
@endphp
<script>
    window.creditNoteCurrency = {!! json_encode($cnCurrencyClient) !!};

    function cnFormatMoney(value) {
        const cfg = window.creditNoteCurrency || { symbol: '$', symbolPosition: 'before', decimalPlaces: 2 };
        const places = typeof cfg.decimalPlaces === 'number' ? cfg.decimalPlaces : 2;
        const n = parseFloat(value);
        const num = isNaN(n) ? 0 : n;
        const fixed = num.toFixed(places);
        const sym = cfg.symbol || '$';
        return (cfg.symbolPosition === 'after') ? (fixed + ' ' + sym) : (sym + fixed);
    }

    let cnProductDropdown = null;

    document.addEventListener('click', function(e) {
        if (!cnProductDropdown) return;
        if (cnProductDropdown.contains(e.target)) return;
        if (e.target.closest('.product-search-input')) return;
        cnProductDropdown.remove();
        cnProductDropdown = null;
    });

    function cnShowProductDropdown(input, products, productIdInput, unitInput, rateInput) {
        if (cnProductDropdown) {
            cnProductDropdown.remove();
            cnProductDropdown = null;
        }
        const dropdown = document.createElement('div');
        dropdown.className = 'product-dropdown absolute z-[100] w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto';
        products.forEach(function(product) {
            const item = document.createElement('div');
            item.className = 'px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0';
            item.innerHTML = '<div class="font-medium text-gray-900">' + (product.name || '') + '</div>' +
                '<div class="text-xs text-gray-500">' + (product.code || 'N/A') + ' - ' + cnFormatMoney(parseFloat(product.selling_price || 0)) + '</div>';
            item.addEventListener('click', function() {
                input.value = product.name;
                productIdInput.value = product.id;
                unitInput.value = product.unit || '';
                rateInput.value = product.selling_price || 0;
                dropdown.remove();
                cnProductDropdown = null;
                cnCalculateRowTotal(input.closest('tr'));
                cnCalculateTotal();
            });
            dropdown.appendChild(item);
        });
        const td = input.closest('td');
        if (td) td.style.position = 'relative';
        dropdown.style.position = 'absolute';
        dropdown.style.top = (input.offsetHeight + 4) + 'px';
        dropdown.style.left = '0';
        dropdown.style.width = input.offsetWidth + 'px';
        dropdown.style.maxWidth = input.offsetWidth + 'px';
        td.appendChild(dropdown);
        cnProductDropdown = dropdown;
    }

    function initializeProductSearch(row) {
        const searchInput = row.querySelector('.product-search-input');
        const productIdInput = row.querySelector('.product-id-input');
        const unitInput = row.querySelector('.product-unit-input');
        const rateInput = row.querySelector('.product-rate-input');
        if (!searchInput || !productIdInput || !unitInput || !rateInput) return;
        let searchTimeout;
        searchInput.addEventListener('input', function(e) {
            clearTimeout(searchTimeout);
            const searchValue = e.target.value.trim();
            if (cnProductDropdown) {
                cnProductDropdown.remove();
                cnProductDropdown = null;
            }
            if (searchValue.length < 2) {
                return;
            }
            searchTimeout = setTimeout(function() {
                fetch('{{ route("admin.delivery-challans.api.products") }}?search=' + encodeURIComponent(searchValue), {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                    .then(function(response) { return response.json(); })
                    .then(function(data) {
                        if (data.success && Array.isArray(data.products) && data.products.length > 0) {
                            cnShowProductDropdown(searchInput, data.products, productIdInput, unitInput, rateInput);
                        }
                    })
                    .catch(function() {});
            }, 300);
        });
    }

    function cnCalculateRowTotal(row) {
        const quantity = parseFloat(row.querySelector('.product-quantity-input').value) || 0;
        const rate = parseFloat(row.querySelector('.product-rate-input').value) || 0;
        const discount = parseFloat(row.querySelector('.product-discount-input').value) || 0;
        const tax = parseFloat(row.querySelector('.product-tax-input').value) || 0;
        const subtotal = quantity * rate;
        const discountAmount = discount;
        const taxAmount = (subtotal - discountAmount) * (tax / 100);
        const total = subtotal - discountAmount + taxAmount;
        row.querySelector('.product-amount').textContent = cnFormatMoney(total);
    }

    function cnNumberToWords(num) {
        const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
        const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
        const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
        const n = Math.round(num);
        if (n === 0) return 'Zero';
        if (n < 10) return ones[n];
        if (n < 20) return teens[n - 10];
        if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? ' ' + ones[n % 10] : '');
        if (n < 1000) return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' ' + cnNumberToWords(n % 100) : '');
        return String(n);
    }

    function cnCalculateTotal() {
        let subtotal = 0;
        let totalTax = 0;
        let totalDiscount = 0;
        document.querySelectorAll('.product-row').forEach(function(row) {
            const quantity = parseFloat(row.querySelector('.product-quantity-input').value) || 0;
            const rate = parseFloat(row.querySelector('.product-rate-input').value) || 0;
            const discount = parseFloat(row.querySelector('.product-discount-input').value) || 0;
            const tax = parseFloat(row.querySelector('.product-tax-input').value) || 0;
            const itemSubtotal = quantity * rate;
            const itemDiscount = discount;
            const itemTax = (itemSubtotal - itemDiscount) * (tax / 100);
            subtotal += itemSubtotal;
            totalDiscount += itemDiscount;
            totalTax += itemTax;
        });
        const total = subtotal - totalDiscount + totalTax;
        const roundedTotal = Math.round(total);
        const sa = document.querySelector('.summary-amount');
        const st = document.querySelector('.summary-tax');
        const sd = document.querySelector('.summary-discount');
        const su = document.querySelector('.summary-total');
        const sw = document.querySelector('.summary-total-words');
        if (sa) sa.textContent = cnFormatMoney(subtotal);
        if (st) st.textContent = cnFormatMoney(totalTax);
        if (sd) sd.textContent = '- ' + cnFormatMoney(totalDiscount);
        if (su) su.textContent = cnFormatMoney(roundedTotal);
        if (sw) sw.textContent = cnNumberToWords(roundedTotal);
    }

    let rowIndex = 1;
    let cnCompanySearchTimeout;
    let cnCompanyAbortController;
    let cnCustomerSearchTimeout;
    let cnCustomerAbortController;
    let cnBankAccountsLoaded = false;

    const CnFormState = {
        signatureType: 'manual',
        manualSignatureType: null,
        signatures: [],

        setSignatureType(type) {
            this.signatureType = type;
            this.renderSignatureType();
        },

        setManualSignatureType(type) {
            this.manualSignatureType = type;
            this.renderManualSignatureType();
        },

        renderSignatureType() {
            const manualContainer = document.getElementById('manual-signature-container');
            const esignatureContainer = document.getElementById('esignature-container');
            if (!manualContainer || !esignatureContainer) return;
            if (this.signatureType === 'manual') {
                manualContainer.classList.remove('hidden');
                esignatureContainer.classList.add('hidden');
                document.querySelectorAll('input[name="manual_signature_type"]').forEach(function(radio) { radio.checked = false; });
                this.manualSignatureType = null;
                this.hideAllManualSignatureContainers();
                cnResetEsignaturePreview();
            } else {
                manualContainer.classList.add('hidden');
                esignatureContainer.classList.remove('hidden');
                if (this.signatures.length === 0) {
                    this.loadSignatures();
                }
            }
        },

        renderManualSignatureType() {
            this.hideAllManualSignatureContainers();
            if (this.manualSignatureType === 'draw') {
                document.getElementById('draw-signature-container').classList.remove('hidden');
                this.initCanvas();
            } else if (this.manualSignatureType === 'upload') {
                document.getElementById('upload-signature-container').classList.remove('hidden');
            } else if (this.manualSignatureType === 'type') {
                document.getElementById('type-signature-container').classList.remove('hidden');
                this.initTypeSignature();
            }
        },

        hideAllManualSignatureContainers() {
            const draw = document.getElementById('draw-signature-container');
            const upload = document.getElementById('upload-signature-container');
            const preview = document.getElementById('signature-upload-preview');
            const type = document.getElementById('type-signature-container');
            if (draw) draw.classList.add('hidden');
            if (upload) upload.classList.add('hidden');
            if (preview) preview.classList.add('hidden');
            if (type) type.classList.add('hidden');
        },

        async loadSignatures() {
            try {
                const response = await fetch('{{ route("admin.delivery-challans.api.signatures") }}', {
                    method: 'GET',
                    headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                    credentials: 'same-origin',
                });
                if (!response.ok) throw new Error('Request failed');
                const data = await response.json();
                if (data.success && data.signatures) {
                    this.signatures = data.signatures;
                    const signatureSelect = document.getElementById('signature_id');
                    if (!signatureSelect) return;
                    signatureSelect.innerHTML = '<option value="">Select signature...</option>';
                    data.signatures.forEach(function(signature) {
                        const option = document.createElement('option');
                        option.value = signature.id;
                        option.textContent = signature.name;
                        signatureSelect.appendChild(option);
                    });
                    const oldSigId = @json(old('signature_id', ''));
                    if (oldSigId !== '' && oldSigId !== null) {
                        signatureSelect.value = String(oldSigId);
                        signatureSelect.dispatchEvent(new Event('change'));
                    }
                }
            } catch (error) {
                console.error('Error loading signatures:', error);
            }
        },

        initCanvas() {
            const canvas = document.getElementById('signature-canvas');
            if (!canvas || canvas.dataset.cnBound === '1') return;
            canvas.dataset.cnBound = '1';
            const ctx = canvas.getContext('2d');
            let isDrawing = false;
            let lastX = 0;
            let lastY = 0;
            ctx.strokeStyle = '#000000';
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';

            canvas.addEventListener('mousedown', function(e) {
                isDrawing = true;
                const rect = canvas.getBoundingClientRect();
                lastX = e.clientX - rect.left;
                lastY = e.clientY - rect.top;
            });
            canvas.addEventListener('mousemove', function(e) {
                if (!isDrawing) return;
                const rect = canvas.getBoundingClientRect();
                const currentX = e.clientX - rect.left;
                const currentY = e.clientY - rect.top;
                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(currentX, currentY);
                ctx.stroke();
                lastX = currentX;
                lastY = currentY;
            });
            canvas.addEventListener('mouseup', function() {
                isDrawing = false;
                CnFormState.saveCanvasData();
            });
            canvas.addEventListener('mouseout', function() { isDrawing = false; });

            canvas.addEventListener('touchstart', function(e) {
                e.preventDefault();
                isDrawing = true;
                const rect = canvas.getBoundingClientRect();
                const touch = e.touches[0];
                lastX = touch.clientX - rect.left;
                lastY = touch.clientY - rect.top;
            });
            canvas.addEventListener('touchmove', function(e) {
                e.preventDefault();
                if (!isDrawing) return;
                const rect = canvas.getBoundingClientRect();
                const touch = e.touches[0];
                const currentX = touch.clientX - rect.left;
                const currentY = touch.clientY - rect.top;
                ctx.beginPath();
                ctx.moveTo(lastX, lastY);
                ctx.lineTo(currentX, currentY);
                ctx.stroke();
                lastX = currentX;
                lastY = currentY;
            });
            canvas.addEventListener('touchend', function() {
                isDrawing = false;
                CnFormState.saveCanvasData();
            });

            const clearBtn = document.getElementById('clear-canvas');
            if (clearBtn && !clearBtn.dataset.cnBound) {
                clearBtn.dataset.cnBound = '1';
                clearBtn.addEventListener('click', function() {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    const dataInput = document.getElementById('signature-canvas-data');
                    if (dataInput) dataInput.value = '';
                });
            }
        },

        saveCanvasData() {
            const canvas = document.getElementById('signature-canvas');
            const dataInput = document.getElementById('signature-canvas-data');
            if (canvas && dataInput) {
                dataInput.value = canvas.toDataURL('image/png');
            }
        },

        initTypeSignature() {
            const textInput = document.getElementById('signature-text');
            const fontSelect = document.getElementById('signature-font');
            const previewText = document.getElementById('signature-preview-text');
            if (!textInput || !fontSelect || !previewText || textInput.dataset.cnTypeBound === '1') return;
            textInput.dataset.cnTypeBound = '1';
            const updatePreview = function() {
                const text = textInput.value || 'Your signature will appear here';
                const font = fontSelect.value;
                const fontMap = {
                    'dancing': "'Dancing Script', cursive",
                    'great-vibes': "'Great Vibes', cursive",
                    'allura': "'Allura', cursive",
                    'brush': "'Brush Script MT', cursive",
                    'pacifico': "'Pacifico', cursive"
                };
                previewText.textContent = text;
                previewText.style.fontFamily = fontMap[font] || fontMap['dancing'];
            };
            textInput.addEventListener('input', updatePreview);
            fontSelect.addEventListener('change', updatePreview);
            updatePreview();
        },
    };

    function cnResetEsignaturePreview() {
        const el = document.getElementById('cn-esignature-preview');
        if (el) {
            el.innerHTML = '<span class="text-sm text-gray-400">No signature selected</span>';
        }
    }

    function cnBindRadioGroup(groupName, onValue) {
        const radios = document.querySelectorAll('input[name="' + groupName + '"]');
        radios.forEach(function(radio) {
            radio.addEventListener('change', function() {
                onValue(this.value);
            });
            const wrapperLabel = radio.closest('label');
            if (wrapperLabel) {
                wrapperLabel.addEventListener('click', function() {
                    if (!radio.checked) {
                        radio.checked = true;
                        onValue(radio.value);
                    }
                });
            }
        });
    }

    function cnHandleSignatureUpload(event) {
        const file = event.target.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) {
            alert('File size must not exceed 5MB');
            event.target.value = '';
            return;
        }
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('signature-upload-preview');
            const img = document.getElementById('signature-preview-img');
            if (img) img.src = e.target.result;
            if (preview) preview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    }

    function initCreditNoteSignature() {
        cnBindRadioGroup('signature_type', function(value) {
            CnFormState.setSignatureType(value);
        });
        cnBindRadioGroup('manual_signature_type', function(value) {
            CnFormState.setManualSignatureType(value);
        });
        const signatureUpload = document.getElementById('signature-upload');
        if (signatureUpload) {
            signatureUpload.addEventListener('change', cnHandleSignatureUpload);
        }
        const signatureIdSelect = document.getElementById('signature_id');
        if (signatureIdSelect) {
            signatureIdSelect.addEventListener('change', function() {
                const id = this.value;
                const preview = document.getElementById('cn-esignature-preview');
                if (!preview) return;
                const sig = CnFormState.signatures.find(function(s) { return String(s.id) === String(id); });
                if (sig && sig.url) {
                    preview.innerHTML = '<img src="' + sig.url + '" alt="" class="w-[240px] max-h-24 object-contain">';
                } else {
                    cnResetEsignaturePreview();
                }
            });
        }

        const initialSigType = document.querySelector('input[name="signature_type"]:checked')?.value || 'manual';
        CnFormState.setSignatureType(initialSigType);
        if (initialSigType === 'manual') {
            @if(old('manual_signature_type'))
            (function() {
                const v = @json(old('manual_signature_type'));
                const r = document.querySelector('input[name="manual_signature_type"][value="' + v + '"]');
                if (r) {
                    r.checked = true;
                    CnFormState.setManualSignatureType(v);
                }
            })();
            @endif
        }
    }

    window.cnSwitchTab = function(tab) {
        document.querySelectorAll('.cn-tab-content').forEach(function(el) { el.classList.add('hidden'); });
        document.querySelectorAll('.cn-tab-btn').forEach(function(btn) {
            btn.classList.remove('border-b-2', 'border-primary', 'bg-primary/5', 'text-gray-700');
            btn.classList.add('text-gray-500');
        });
        const contentEl = document.getElementById('cn-content-' + tab);
        if (contentEl) contentEl.classList.remove('hidden');
        const activeTab = document.getElementById('cn-tab-' + tab);
        if (activeTab) {
            activeTab.classList.add('border-b-2', 'border-primary', 'bg-primary/5', 'text-gray-700');
            activeTab.classList.remove('text-gray-500');
        }
        if (tab === 'payment') {
            cnRenderPaymentMethod();
        }
    };

    function cnRenderPaymentMethod() {
        const field = document.getElementById('cn-bank-account-field');
        const select = document.getElementById('cn-bank-account-select');
        const paymentPane = document.getElementById('cn-content-payment');
        if (!field || !select) return;
        const method = paymentPane
            ? (paymentPane.querySelector('input[name="payment_method"]:checked')?.value || 'cash')
            : 'cash';
        if (method === 'bank_transfer') {
            field.classList.remove('hidden');
            select.required = true;
            cnLoadBankAccounts();
        } else {
            field.classList.add('hidden');
            select.required = false;
            select.value = '';
        }
    }

    async function cnLoadBankAccounts() {
        const select = document.getElementById('cn-bank-account-select');
        if (!select || cnBankAccountsLoaded) return;
        try {
            const response = await fetch('{{ route("admin.delivery-challans.api.bank-accounts") }}', {
                method: 'GET',
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                credentials: 'same-origin',
            });
            if (!response.ok) throw new Error('Request failed');
            const data = await response.json();
            select.innerHTML = '<option value="">Select bank account...</option>';
            if (data.success && data.bank_accounts && data.bank_accounts.length) {
                data.bank_accounts.forEach(function(account) {
                    const option = document.createElement('option');
                    option.value = account.id;
                    option.textContent = account.account_name + ' - ' + account.bank_name + ' (' + account.account_number + ')';
                    select.appendChild(option);
                });
            }
            const oldVal = @json(old('bank_account_id', ''));
            if (oldVal !== '' && oldVal !== null) {
                select.value = String(oldVal);
            }
            cnBankAccountsLoaded = true;
        } catch (e) {
            console.error('Error loading bank accounts:', e);
            select.innerHTML = '<option value="">Select bank account...</option>';
        }
    }

    function cnDisplayCompany(company) {
        const companyIdInput = document.getElementById('company-id');
        const companySearch = document.getElementById('company-search');
        const companyDropdown = document.getElementById('company-dropdown');
        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');

        if (!companySearch || !companyDisplay) return;

        if (companyIdInput) {
            companyIdInput.value = company.id ? String(company.id) : '';
        }
        companySearch.value = company.name || '';
        companyDisplay.classList.remove('hidden');
        companyDisplayName.textContent = company.name || '';

        if (company.logo || company.logo_path) {
            const logoUrl = company.logo || ('{{ 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>';
        }

        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>';

        if (companyDropdown) companyDropdown.classList.add('hidden');
    }

    function cnSearchCompanies(searchTerm) {
        const companyDropdown = document.getElementById('company-dropdown');
        const companyLoading = document.getElementById('company-loading');
        if (cnCompanyAbortController) cnCompanyAbortController.abort();
        cnCompanyAbortController = new AbortController();

        if (companyLoading) companyLoading.classList.remove('hidden');
        if (companyDropdown) 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: cnCompanyAbortController.signal,
        })
            .then(function(response) {
                if (!response.ok) throw new Error('Request failed');
                return response.json();
            })
            .then(function(data) {
                if (companyLoading) companyLoading.classList.add('hidden');
                if (!companyDropdown) return;
                companyDropdown.innerHTML = '';
                if (data.success && data.companies && data.companies.length > 0) {
                    data.companies.forEach(function(company) {
                        const option = document.createElement('div');
                        option.className = 'px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-200 last:border-b-0';
                        option.innerHTML = '<div class="font-medium text-gray-900">' + company.name + '</div>' +
                            (company.email ? '<div class="text-xs text-gray-500">' + company.email + '</div>' : '');
                        option.addEventListener('click', function() {
                            cnDisplayCompany(company);
                        });
                        companyDropdown.appendChild(option);
                    });
                } else {
                    companyDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-gray-500">No companies found</div>';
                }
                companyDropdown.classList.remove('hidden');
            })
            .catch(function(error) {
                if (error.name !== 'AbortError' && companyDropdown) {
                    if (companyLoading) 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');
                }
            });
    }

    function cnLoadCompanySettings() {
        fetch('{{ route("admin.invoices.api.company-settings") }}', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
            credentials: 'same-origin',
        })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                if (data.success && data.company && data.company.name) {
                    cnDisplayCompany(data.company);
                }
            })
            .catch(function(e) {
                console.error('Error loading company settings:', e);
            });
    }

    function cnDisplayCustomer(customer) {
        const customerIdInput = document.getElementById('customer-id');
        const customerSearch = document.getElementById('customer-search');
        const customerDropdown = document.getElementById('customer-dropdown');
        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');

        if (!customerIdInput || !customerSearch || !customerDisplay) return;

        customerIdInput.value = customer.id || '';
        customerSearch.value = customer.name || '';
        customerDisplay.classList.remove('hidden');
        customerDisplayName.textContent = (customer.company || customer.name || '');

        const initial = (customer.name || 'N').charAt(0).toUpperCase();
        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 = '';
            const img = document.createElement('img');
            img.src = imageUrl;
            img.alt = customer.name || '';
            img.className = 'w-full h-full object-cover rounded-full';
            img.onerror = function() {
                customerLogoContainer.innerHTML = '<span class="text-primary font-bold">' + initial + '</span>';
            };
            customerLogoContainer.appendChild(img);
        } else {
            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>';
        customerDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
        if (customerDropdown) customerDropdown.classList.add('hidden');
    }

    function cnSearchCustomers(searchTerm) {
        const customerDropdown = document.getElementById('customer-dropdown');
        const customerLoading = document.getElementById('customer-loading');
        if (cnCustomerAbortController) cnCustomerAbortController.abort();
        cnCustomerAbortController = new AbortController();

        if (customerLoading) customerLoading.classList.remove('hidden');
        if (customerDropdown) 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: cnCustomerAbortController.signal,
        })
            .then(function(response) {
                if (!response.ok) throw new Error('Request failed');
                return response.json();
            })
            .then(function(data) {
                if (customerLoading) customerLoading.classList.add('hidden');
                if (!customerDropdown) return;
                customerDropdown.innerHTML = '';
                if (data.success && data.customers && data.customers.length > 0) {
                    data.customers.forEach(function(customer) {
                        const option = document.createElement('div');
                        option.className = 'px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-200 last:border-b-0';
                        option.innerHTML = '<div class="font-medium text-gray-900">' + customer.name + '</div>' +
                            (customer.email ? '<div class="text-xs text-gray-500">' + customer.email + '</div>' : '');
                        option.addEventListener('click', function() {
                            cnDisplayCustomer(customer);
                        });
                        customerDropdown.appendChild(option);
                    });
                } else {
                    customerDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-gray-500">No customers found</div>';
                }
                customerDropdown.classList.remove('hidden');
            })
            .catch(function(error) {
                if (error.name !== 'AbortError' && customerDropdown) {
                    if (customerLoading) 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');
                }
            });
    }

    function initCreditNoteBillFromBillTo() {
        cnLoadCompanySettings();

        const companySearch = document.getElementById('company-search');
        const companySearchContainer = document.getElementById('company-search-container');
        const companyDropdown = document.getElementById('company-dropdown');
        const companyLoading = document.getElementById('company-loading');
        const customerSearch = document.getElementById('customer-search');
        const customerSearchContainer = document.getElementById('customer-search-container');
        const customerDropdown = document.getElementById('customer-dropdown');
        const customerLoading = document.getElementById('customer-loading');

        if (companySearch) {
            companySearch.addEventListener('input', function() {
                const term = this.value.trim();
                clearTimeout(cnCompanySearchTimeout);
                cnCompanySearchTimeout = setTimeout(function() {
                    cnSearchCompanies(term);
                }, 300);
            });
            companySearch.addEventListener('focus', function() {
                cnSearchCompanies(this.value.trim());
            });
        }

        if (customerSearch) {
            customerSearch.addEventListener('input', function() {
                const term = this.value.trim();
                clearTimeout(cnCustomerSearchTimeout);
                cnCustomerSearchTimeout = setTimeout(function() {
                    cnSearchCustomers(term);
                }, 300);
            });
            customerSearch.addEventListener('focus', function() {
                cnSearchCustomers(this.value.trim());
            });
        }

        document.addEventListener('click', function(e) {
            if (companySearchContainer && companyDropdown && companyLoading &&
                !companySearchContainer.contains(e.target) &&
                !companyDropdown.contains(e.target) &&
                !companyLoading.contains(e.target)) {
                companyDropdown.classList.add('hidden');
                companyLoading.classList.add('hidden');
            }

            if (customerSearchContainer && customerDropdown && customerLoading &&
                !customerSearchContainer.contains(e.target) &&
                !customerDropdown.contains(e.target) &&
                !customerLoading.contains(e.target)) {
                customerDropdown.classList.add('hidden');
                customerLoading.classList.add('hidden');
            }
        });
    }

    function addNewRow() {
        const tbody = document.getElementById('product-rows');
        const newRow = document.createElement('tr');
        newRow.className = 'product-row';
        newRow.innerHTML = `
            <td class="py-3 px-4 align-top">
                <input type="hidden" name="items[${rowIndex}][product_id]" class="product-id-input">
                <input type="text" name="items[${rowIndex}][product]" placeholder="Search or type product..." class="product-search-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" autocomplete="off">
            </td>
            <td class="py-3 px-4 min-w-[6rem] align-top">
                <input type="text" name="items[${rowIndex}][unit]" class="product-unit-input w-full min-w-0 h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-[14px] focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4 align-top">
                <input type="number" name="items[${rowIndex}][quantity]" value="1" min="1" step="1" class="product-quantity-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4 align-top">
                <input type="number" name="items[${rowIndex}][rate]" value="0" step="0.01" min="0" class="product-rate-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4 align-top">
                <input type="number" name="items[${rowIndex}][discount]" value="0" step="0.01" min="0" class="product-discount-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4 align-top">
                <input type="number" name="items[${rowIndex}][tax]" value="0" step="0.01" min="0" class="product-tax-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white text-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4 text-right align-top">
                <span class="product-amount text-sm font-medium text-gray-900">${cnFormatMoney(0)}</span>
            </td>
            <td class="py-3 px-4 align-top">
                <button type="button" onclick="removeRow(this)" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100700 rounded-lg transition-colors">
                    <span class="material-symbols-outlined text-lg">delete</span>
                </button>
            </td>
        `;
        tbody.appendChild(newRow);
        initializeProductSearch(newRow);
        rowIndex++;
        cnCalculateTotal();
    }

    function removeRow(button) {
        const row = button.closest('tr');
        if (document.querySelectorAll('.product-row').length > 1) {
            row.remove();
            cnCalculateTotal();
        }
    }

    document.addEventListener('input', function(e) {
        if (e.target.classList.contains('product-quantity-input') ||
            e.target.classList.contains('product-rate-input') ||
            e.target.classList.contains('product-discount-input') ||
            e.target.classList.contains('product-tax-input')) {
            const row = e.target.closest('.product-row');
            if (row) {
                cnCalculateRowTotal(row);
                cnCalculateTotal();
            }
        }
    });

    function cnSyncCustomerFromInvoice() {
        const invSel = document.getElementById('invoice_id');
        const customerIdInput = document.getElementById('customer-id');
        const customerSearch = document.getElementById('customer-search');
        if (!invSel || !customerIdInput) return;
        const opt = invSel.options[invSel.selectedIndex];
        if (!opt || !opt.value) {
            return;
        }
        const cid = opt.getAttribute('data-customer-id');
        const cname = opt.getAttribute('data-customer-name') || '';
        if (cid) {
            customerIdInput.value = cid;
            if (customerSearch) {
                customerSearch.value = cname;
            }
            const customerDisplay = document.getElementById('customer-display');
            const customerDisplayName = document.getElementById('customer-display-name');
            if (customerDisplay && customerDisplayName && cname) {
                customerDisplay.classList.remove('hidden');
                customerDisplayName.textContent = cname;
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        const invoiceSelect = document.getElementById('invoice_id');
        if (invoiceSelect) {
            invoiceSelect.addEventListener('change', cnSyncCustomerFromInvoice);
            cnSyncCustomerFromInvoice();
        }
        initCreditNoteBillFromBillTo();
        initCreditNoteSignature();
        const firstProductRow = document.querySelector('#product-rows .product-row');
        if (firstProductRow) {
            initializeProductSearch(firstProductRow);
        }
        document.querySelectorAll('#cn-content-payment input[name="payment_method"]').forEach(function(r) {
            r.addEventListener('change', cnRenderPaymentMethod);
        });
        cnRenderPaymentMethod();
        @if(old('bank_account_id') || old('payment_method') == 'bank_transfer')
            cnSwitchTab('payment');
        @endif
    });
</script>
@endpush
@endsection




