@extends('layouts.admin')

@php
    $isEdit = isset($debitNote) && $debitNote !== null;
@endphp

@section('title', $isEdit ? 'Edit Debit Note' : 'New Debit Note')

@section('page-title', $isEdit ? 'Edit Debit Note' : 'New Debit 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.debit-notes.index') }}" class="hover:text-primary">Debit Notes</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    @if($isEdit)
        <a href="{{ route('admin.debit-notes.show', $debitNote) }}" class="hover:text-primary">{{ $debitNote->debit_note_number }}</a>
        <span class="material-symbols-outlined text-xs">chevron_right</span>
        <span class="text-primary font-medium">Edit</span>
    @else
        <span class="text-primary font-medium">New Debit Note</span>
    @endif
@endsection

@section('content')
<form method="POST" action="{{ $isEdit ? route('admin.debit-notes.update', $debitNote) : route('admin.debit-notes.store') }}" class="max-w-7xl mx-auto" id="debit-note-form">
    @csrf
    @if($isEdit)
        @method('PUT')
    @endif
    <div class="space-y-6">
        <!-- Debit Note Details Header -->
        <div class="flex justify-between items-center">
            <h2 class="text-2xl font-bold text-gray-900">{{ $isEdit ? 'Edit Debit Note' : 'New Debit Note' }}</h2>
            <button type="button" class="text-gray-400 hover:text-gray-600">
                <span class="material-symbols-outlined">help</span>
            </button>
        </div>

        <!-- Purchase ID, Order Date, Status -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <input type="hidden" name="debit_note_number" value="{{ old('debit_note_number', $isEdit ? $debitNote->debit_note_number : $nextDebitNoteNumber) }}">
            <div class="grid grid-cols-1 md:grid-cols-2 {{ $isEdit ? 'lg:grid-cols-4' : 'lg:grid-cols-3' }} gap-6">
                @if($isEdit)
                <div>
                    <label for="debit_note_id_display" class="block text-sm font-medium text-gray-700 mb-2">Debit Note ID</label>
                    <input type="text" id="debit_note_id_display" readonly value="{{ old('debit_note_number', $debitNote->debit_note_number) }}" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-gray-100 text-gray-900 cursor-not-allowed">
                </div>
                @endif
                <!-- Purchase ID -->
                <div>
                    <label for="purchase_id" class="block text-sm font-medium text-gray-700 mb-2">Purchase ID</label>
                    <div class="relative">
                        <input type="text" id="purchase-search" placeholder="Select Purchase Order" autocomplete="off" 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">
                        <input type="hidden" id="purchase_id" name="purchase_id" value="{{ old('purchase_id', $isEdit ? $debitNote->purchase_id : '') }}">
                        <div id="purchase-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"></div>
                        <div id="purchase-loading" class="hidden absolute right-3 top-3">
                            <span class="material-symbols-outlined animate-spin text-gray-400">refresh</span>
                        </div>
                    </div>
                </div>

                <!-- Order Date -->
                <div>
                    <label for="order_date" class="block text-sm font-medium text-gray-700 mb-2">Order Date <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <input type="date" id="order_date" name="order_date" value="{{ old('order_date', $isEdit && $debitNote->order_date ? $debitNote->order_date->format('Y-m-d') : date('Y-m-d')) }}" required 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 pr-10" onchange="document.getElementById('debit_note_date').value = this.value">
                        <input type="hidden" id="debit_note_date" name="debit_note_date" value="{{ old('debit_note_date', $isEdit && $debitNote->debit_note_date ? $debitNote->debit_note_date->format('Y-m-d') : date('Y-m-d')) }}">
                        <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">calendar_today</span>
                    </div>
                </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 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow appearance-none bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNiIgdmlld0JveD0iMCAwIDEwIDYiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGQ9Ik0xIDFMNSA1TDkgMSIgc3Ryb2tlPSIjNkI3Mjc5IiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+Cjwvc3ZnPgo=')] bg-no-repeat bg-[right_0.75rem_center] pr-10">
                        <option value="draft" {{ old('status', $isEdit ? $debitNote->status : 'draft') == 'draft' ? 'selected' : '' }}>Draft</option>
                        <option value="pending" {{ old('status', $isEdit ? $debitNote->status : 'draft') == 'pending' ? 'selected' : '' }}>Pending</option>
                        <option value="approved" {{ old('status', $isEdit ? $debitNote->status : 'draft') == 'approved' ? 'selected' : '' }}>Approved</option>
                        <option value="rejected" {{ old('status', $isEdit ? $debitNote->status : 'draft') == 'rejected' ? 'selected' : '' }}>Rejected</option>
                        <option value="completed" {{ old('status', $isEdit ? $debitNote->status : 'draft') == 'completed' ? 'selected' : '' }}>Completed</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- 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', $isEdit ? $debitNote->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.suppliers.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 Supplier</span>
                    </a>
                </div>
                <div class="space-y-4">
                    <!-- Supplier Search -->
                    <div id="supplier-search-container" class="relative">
                        <div class="relative">
                            <input type="text" id="supplier-search" autocomplete="off" placeholder="Type to search customer... Select customer to view customer details" 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="supplier_id" id="supplier-id" required value="{{ old('supplier_id', $isEdit ? $debitNote->supplier_id : '') }}"/>
                        </div>
                        <div id="supplier-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="supplier-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>
                    <!-- Supplier Display Card -->
                    <div id="supplier-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="supplier-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="supplier-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="supplier-display-details">
                                        <!-- Supplier details will be inserted here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Products Table -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="bg-gray-800 text-white">
                        <tr>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider">Product / Service</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-24">Unit</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-24">Quantity</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-24">Rate</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-24">Discount</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-24">Tax</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-28 text-right">Amount</th>
                            <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider w-16">Action</th>
                        </tr>
                    </thead>
                    <tbody id="items-tbody" class="divide-y divide-gray-100">
                        @if($isEdit && $debitNote->items->isNotEmpty())
                            @foreach($debitNote->items as $idx => $item)
                                <tr class="product-row" data-row-index="{{ $idx }}">
                                    <td class="py-3 px-4">
                                        <input type="hidden" name="items[{{ $idx }}][product_id]" class="product-id-input" value="{{ $item->product_id }}">
                                        <input type="text" name="items[{{ $idx }}][product_name]" value="{{ old('items.'.$idx.'.product_name', $item->description) }}" 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">
                                        <input type="text" name="items[{{ $idx }}][unit]" value="{{ old('items.'.$idx.'.unit', $item->unit) }}" class="product-unit-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1); font-size: 15px; font-weight: 500;">
                                    </td>
                                    <td class="py-3 px-4">
                                        <input type="number" name="items[{{ $idx }}][quantity]" value="{{ old('items.'.$idx.'.quantity', $item->quantity) }}" min="0.01" step="0.01" 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" onchange="calculateRowTotal(this.closest('tr'))">
                                    </td>
                                    <td class="py-3 px-4">
                                        <input type="number" name="items[{{ $idx }}][rate]" value="{{ old('items.'.$idx.'.rate', $item->rate) }}" 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" onchange="calculateRowTotal(this.closest('tr'))">
                                    </td>
                                    <td class="py-3 px-4">
                                        <input type="number" name="items[{{ $idx }}][discount]" value="{{ old('items.'.$idx.'.discount', $item->discount) }}" 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" onchange="calculateRowTotal(this.closest('tr'))">
                                    </td>
                                    <td class="py-3 px-4">
                                        <input type="number" name="items[{{ $idx }}][tax]" value="{{ old('items.'.$idx.'.tax', $item->tax_rate) }}" step="0.01" min="0" max="100" 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" onchange="calculateRowTotal(this.closest('tr'))">
                                    </td>
                                    <td class="py-3 px-4 text-right">
                                        <span class="product-amount text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount(0) }}</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-100 rounded-lg transition-colors">
                                            <span class="material-symbols-outlined text-lg">delete</span>
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="8" class="py-8 px-4 text-center text-gray-500">
                                    No Items Selected
                                </td>
                            </tr>
                        @endif
                    </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>

        <!-- Bottom Section: Extra Information & Summary -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Extra Information -->
            <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-bold text-gray-900 mb-4">Extra Information</h3>
                
                <!-- Tabs -->
                <div class="flex gap-2 mb-4 border-b border-gray-200">
                    <button type="button" onclick="switchTab('notes')" id="tab-notes" class="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="switchTab('terms')" id="tab-terms" class="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="switchTab('payment')" id="tab-payment" class="px-4 py-2 text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors">
                        Payment Details
                    </button>
                </div>

                <!-- Notes Tab Content -->
                <div id="content-notes" class="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', $isEdit ? $debitNote->notes : '') }}</textarea>
                </div>

                <!-- Terms Tab Content -->
                <div id="content-terms" class="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 & Conditions">{{ old('terms', $isEdit ? $debitNote->terms : '') }}</textarea>
                </div>

                <!-- Payment Tab Content -->
                <div id="content-payment" class="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="space-y-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', $isEdit ? ($debitNote->payment_method ?? 'cash') : 'cash') == 'cash' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="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', $isEdit ? ($debitNote->payment_method ?? 'cash') : 'cash') == 'bank_transfer' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="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', $isEdit ? ($debitNote->payment_method ?? 'cash') : 'cash') == 'credit_card' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="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', $isEdit ? ($debitNote->payment_method ?? 'cash') : 'cash') == 'cheque' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="payment-cheque">
                                    <span class="text-sm text-gray-700">Cheque</span>
                                </label>
                            </div>
                        </div>
                        <div id="bank-account-field" class="hidden">
                            <label for="bank_account_id" class="block text-sm font-medium text-gray-700 mb-2">Select Bank Account <span class="text-red-500">*</span></label>
                            <select id="bank_account_id" 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>

            <!-- Summary -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-bold text-gray-900 mb-4">Summary</h3>
                <div class="space-y-3">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Amount</span>
                        <span class="text-sm font-medium text-gray-900"><span id="summary-amount">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Tax</span>
                        <span class="text-sm font-medium text-gray-900"><span id="summary-tax">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Discount</span>
                        <span class="text-sm font-medium text-gray-900">- <span id="summary-discount">0.00</span></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="text-lg font-bold text-gray-900"><span id="summary-total">0.00</span></span>
                    </div>
                    <p class="text-sm text-gray-500 italic" id="summary-total-words">Zero</p>
                </div>

                <!-- Signature -->
                <div class="mt-6 pt-6 border-t border-gray-200">
                    <div class="space-y-4">
                        <!-- Signature Type Selection -->
                        <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', $isEdit ? ($debitNote->signature_type ?? 'manual') : 'manual') === 'manual' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="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', $isEdit ? ($debitNote->signature_type ?? 'manual') : 'manual') === 'esignature' ? 'checked' : '' }} class="text-primary focus:ring-primary" id="signature-type-esignature">
                                <span class="text-sm text-gray-700">eSignature</span>
                            </label>
                        </div>

                        <!-- Manual Signature Options -->
                        <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="space-y-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" 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" 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" class="text-primary focus:ring-primary">
                                        <span class="text-sm text-gray-700">Type Signature (Auto-generated font styles)</span>
                                    </label>
                                </div>
                            </div>

                            <!-- Draw Signature Canvas -->
                            <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>

                            <!-- Upload Signature Image -->
                            <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>

                            <!-- Type Signature -->
                            <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" 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">Dancing Script</option>
                                        <option value="great-vibes">Great Vibes</option>
                                        <option value="allura">Allura</option>
                                        <option value="brush">Brush Script</option>
                                        <option value="pacifico">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>

                        <!-- eSignature Dropdown -->
                        <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>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex items-center justify-end gap-3 pb-6">
            @if($isEdit)
                <a href="{{ route('admin.debit-notes.show', $debitNote) }}" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                    Cancel
                </a>
            @else
                <a href="{{ route('admin.debit-notes.index') }}" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50 transition-colors">
                    Cancel
                </a>
            @endif
            <button type="submit" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 shadow-sm transition-colors flex items-center gap-2">
                <span class="material-symbols-outlined text-lg">save</span>
                {{ $isEdit ? 'Update Debit Note' : 'Save Debit Note' }}
            </button>
        </div>
    </div>
</form>

@push('scripts')
@if($isEdit)
@php
    $editCompany = $debitNote->company ? [
        'id' => $debitNote->company->id,
        'name' => $debitNote->company->name,
        'email' => $debitNote->company->email ?? '',
        'phone' => $debitNote->company->phone ?? '',
        'address' => $debitNote->company->address ?? '',
        'city' => $debitNote->company->city ?? '',
        'state' => $debitNote->company->state ?? '',
        'zip' => $debitNote->company->zip ?? '',
        'country' => $debitNote->company->country ?? '',
        'logo' => $debitNote->company->logo_url,
        'logo_path' => $debitNote->company->logo,
    ] : null;
    $editSupplier = $debitNote->supplier ? [
        'id' => $debitNote->supplier->id,
        'name' => $debitNote->supplier->name,
        'email' => $debitNote->supplier->email ?? '',
        'phone' => $debitNote->supplier->phone ?? '',
        'address' => $debitNote->supplier->address ?? '',
        'city' => $debitNote->supplier->city ?? '',
        'state' => $debitNote->supplier->state ?? '',
        'zip' => $debitNote->supplier->zip ?? '',
        'country' => $debitNote->supplier->country ?? '',
        'image' => $debitNote->supplier->image_url ?? null,
        'image_path' => $debitNote->supplier->image,
        'type' => 'supplier',
    ] : null;
    $editPurchase = $debitNote->purchase ? [
        'id' => $debitNote->purchase->id,
        'label' => $debitNote->purchase->purchase_number,
    ] : null;
@endphp
<script>
window.__DN_EDIT__ = true;
window.__EDIT_COMPANY__ = @json($editCompany);
window.__EDIT_SUPPLIER__ = @json($editSupplier);
window.__EDIT_PURCHASE__ = @json($editPurchase);
window.__EDIT_SIGNATURE_ID__ = @json($debitNote->signature_id);
</script>
@else
<script>
window.__DN_EDIT__ = false;
</script>
@endif
<script>
let rowIndex = {{ $isEdit ? $debitNote->items->count() : 0 }};
let companySearchTimeout;
let supplierSearchTimeout;
let purchaseSearchTimeout;
let companyAbortController;
let supplierAbortController;
let purchaseAbortController;

// Currency settings
const currencySymbol = '{{ $defaultCurrencyModel->symbol ?? '$' }}';
const currencyPosition = '{{ $defaultCurrencyModel->symbol_position ?? 'before' }}';
const currencyDecimalPlaces = {{ $defaultCurrencyModel->decimal_places ?? 2 }};

// Format currency amount - Make it globally accessible
window.formatCurrency = function(amount) {
    const formatted = parseFloat(amount || 0).toFixed(currencyDecimalPlaces);
    if (currencyPosition === 'before') {
        return currencySymbol + formatted;
    }
    return formatted + ' ' + currencySymbol;
};

// Tab switching - Make it globally accessible
window.switchTab = function(tab) {
    // Hide all tab contents
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.add('hidden');
    });
    
    // Remove active class from all tabs
    document.querySelectorAll('[id^="tab-"]').forEach(btn => {
        btn.classList.remove('border-b-2', 'border-primary', 'bg-primary/5', 'text-gray-700');
        btn.classList.add('text-gray-500');
    });
    
    // Show selected tab content
    document.getElementById('content-' + tab).classList.remove('hidden');
    
    // Add active class to selected tab
    const activeTab = document.getElementById('tab-' + tab);
    activeTab.classList.add('border-b-2', 'border-primary', 'bg-primary/5', 'text-gray-700');
    activeTab.classList.remove('text-gray-500');
}

// ========== 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');

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;
    companySearchContainer.classList.add('hidden');
    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>';
    }
    
    // Only show essential details (Email and Phone)
    let detailsHTML = '';
    if (company.email) detailsHTML += `<p>${company.email}</p>`;
    if (company.phone) detailsHTML += `<p>${company.phone}</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.debit-notes.api.company-settings") }}', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            }
        });
        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) {
    if (companyAbortController) {
        companyAbortController.abort();
    }
    companyAbortController = new AbortController();
    
    if (!searchTerm || searchTerm.length < 2) {
        companyDropdown.classList.add('hidden');
        companyLoading.classList.add('hidden');
        return;
    }
    
    companyLoading.classList.remove('hidden');
    companyDropdown.classList.add('hidden');
    
    fetch('{{ route("admin.debit-notes.api.companies") }}?search=' + encodeURIComponent(searchTerm), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        signal: companyAbortController.signal
    })
    .then(response => 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-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', () => displayCompany(company));
                companyDropdown.appendChild(option);
            });
            companyDropdown.classList.remove('hidden');
        } else {
            companyDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-gray-500">No companies found</div>';
            companyDropdown.classList.remove('hidden');
        }
    })
    .catch(error => {
        if (error.name !== 'AbortError') {
            console.error('Error fetching companies:', error);
            companyLoading.classList.add('hidden');
        }
    });
}

if (companySearch) {
    companySearch.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        clearTimeout(companySearchTimeout);
        companySearchTimeout = setTimeout(() => searchCompanies(searchTerm), 300);
    });
    
    companySearch.addEventListener('focus', function() {
        if (this.value.trim().length >= 2) {
            searchCompanies(this.value.trim());
        }
    });
    
    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');
        }
    });
}

// ========== SUPPLIER DROPDOWN (AJAX) ==========
const supplierSearch = document.getElementById('supplier-search');
const supplierDropdown = document.getElementById('supplier-dropdown');
const supplierLoading = document.getElementById('supplier-loading');
const supplierIdInput = document.getElementById('supplier-id');
const supplierSearchContainer = document.getElementById('supplier-search-container');
const supplierDisplay = document.getElementById('supplier-display');
const supplierDisplayName = document.getElementById('supplier-display-name');
const supplierDisplayDetails = document.getElementById('supplier-display-details');
const supplierLogoContainer = document.getElementById('supplier-logo-container');

function displaySupplier(supplier) {
    supplierIdInput.value = supplier.id;
    supplierSearch.value = supplier.name;
    supplierSearchContainer.classList.add('hidden');
    supplierDisplay.classList.remove('hidden');
    
    supplierDisplayName.textContent = supplier.company || supplier.name;
    
    if (supplier.image) {
        const imageUrl = supplier.image.startsWith('http') || supplier.image.startsWith('/')
            ? supplier.image
            : (supplier.image_path ? '{{ asset("storage") }}/' + supplier.image_path : '');
        if (imageUrl) {
            supplierLogoContainer.innerHTML = `<img src="${imageUrl}" alt="${supplier.name}" class="w-full h-full object-cover rounded-full">`;
        } else {
            const initial = (supplier.name || 'N').charAt(0).toUpperCase();
            supplierLogoContainer.innerHTML = `<span class="text-primary font-bold">${initial}</span>`;
        }
    } else {
        const initial = (supplier.name || 'N').charAt(0).toUpperCase();
        supplierLogoContainer.innerHTML = `<span class="text-primary font-bold">${initial}</span>`;
    }
    
    let detailsHTML = '';
    if (supplier.email) detailsHTML += `<p>${supplier.email}</p>`;
    if (supplier.phone) detailsHTML += `<p>${supplier.phone}</p>`;
    
    supplierDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
    supplierDropdown.classList.add('hidden');
}

function searchSuppliers(searchTerm) {
    if (supplierAbortController) {
        supplierAbortController.abort();
    }
    supplierAbortController = new AbortController();
    
    if (!searchTerm || searchTerm.length < 2) {
        supplierDropdown.classList.add('hidden');
        supplierLoading.classList.add('hidden');
        return;
    }
    
    supplierLoading.classList.remove('hidden');
    supplierDropdown.classList.add('hidden');
    
    fetch('{{ route("admin.debit-notes.api.suppliers") }}?search=' + encodeURIComponent(searchTerm), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        signal: supplierAbortController.signal
    })
    .then(response => response.json())
    .then(data => {
        supplierLoading.classList.add('hidden');
        
        if (data.success && data.suppliers && data.suppliers.length > 0) {
            supplierDropdown.innerHTML = '';
            data.suppliers.forEach(supplier => {
                const option = document.createElement('div');
                option.className = 'supplier-option 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">${supplier.name}</div>
                    ${supplier.email ? `<div class="text-xs text-gray-500">${supplier.email}</div>` : ''}
                `;
                option.addEventListener('click', () => displaySupplier(supplier));
                supplierDropdown.appendChild(option);
            });
            supplierDropdown.classList.remove('hidden');
        } else {
            supplierDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-gray-500">No suppliers found</div>';
            supplierDropdown.classList.remove('hidden');
        }
    })
    .catch(error => {
        if (error.name !== 'AbortError') {
            console.error('Error fetching suppliers:', error);
            supplierLoading.classList.add('hidden');
        }
    });
}

if (supplierSearch) {
    supplierSearch.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        clearTimeout(supplierSearchTimeout);
        supplierSearchTimeout = setTimeout(() => searchSuppliers(searchTerm), 300);
    });
    
    supplierSearch.addEventListener('focus', function() {
        if (this.value.trim().length >= 2) {
            searchSuppliers(this.value.trim());
        }
    });
    
    document.addEventListener('click', function(e) {
        if (!supplierSearch.contains(e.target) && !supplierDropdown.contains(e.target) && !supplierLoading.contains(e.target)) {
            supplierDropdown.classList.add('hidden');
            supplierLoading.classList.add('hidden');
        }
    });
}

// ========== PURCHASE DROPDOWN (AJAX) ==========
const purchaseSearch = document.getElementById('purchase-search');
const purchaseDropdown = document.getElementById('purchase-dropdown');
const purchaseLoading = document.getElementById('purchase-loading');
const purchaseIdInput = document.getElementById('purchase_id');

function searchPurchases(searchTerm) {
    if (purchaseAbortController) {
        purchaseAbortController.abort();
    }
    purchaseAbortController = new AbortController();
    
    if (!searchTerm || searchTerm.length < 2) {
        purchaseDropdown.classList.add('hidden');
        purchaseLoading.classList.add('hidden');
        return;
    }
    
    purchaseLoading.classList.remove('hidden');
    purchaseDropdown.classList.add('hidden');
    
    fetch('{{ route("admin.debit-notes.api.purchases") }}?search=' + encodeURIComponent(searchTerm), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        signal: purchaseAbortController.signal
    })
    .then(response => response.json())
    .then(data => {
        purchaseLoading.classList.add('hidden');
        
        if (data.success && data.purchases && data.purchases.length > 0) {
            purchaseDropdown.innerHTML = '';
            data.purchases.forEach(purchase => {
                const option = document.createElement('div');
                option.className = 'purchase-option 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">${purchase.purchase_number}</div>
                    <div class="text-xs text-gray-500">${purchase.supplier_name} - ${formatCurrency(purchase.total)}</div>
                `;
                option.addEventListener('click', () => {
                    purchaseIdInput.value = purchase.id;
                    purchaseSearch.value = purchase.purchase_number;
                    purchaseDropdown.classList.add('hidden');
                });
                purchaseDropdown.appendChild(option);
            });
            purchaseDropdown.classList.remove('hidden');
        } else {
            purchaseDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-gray-500">No purchases found</div>';
            purchaseDropdown.classList.remove('hidden');
        }
    })
    .catch(error => {
        if (error.name !== 'AbortError') {
            console.error('Error fetching purchases:', error);
            purchaseLoading.classList.add('hidden');
        }
    });
}

if (purchaseSearch) {
    purchaseSearch.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        clearTimeout(purchaseSearchTimeout);
        purchaseSearchTimeout = setTimeout(() => searchPurchases(searchTerm), 300);
    });
    
    purchaseSearch.addEventListener('focus', function() {
        if (this.value.trim().length >= 2) {
            searchPurchases(this.value.trim());
        }
    });
    
    document.addEventListener('click', function(e) {
        if (!purchaseSearch.contains(e.target) && !purchaseDropdown.contains(e.target) && !purchaseLoading.contains(e.target)) {
            purchaseDropdown.classList.add('hidden');
            purchaseLoading.classList.add('hidden');
        }
    });
}

// ========== PRODUCT ITEMS TABLE ==========
function addNewRow() {
    const tbody = document.getElementById('items-tbody');
    
    // Remove "No Items" row if it exists
    const noItemsRow = tbody.querySelector('tr td[colspan]');
    if (noItemsRow) {
        noItemsRow.parentElement.remove();
    }
    
    const newRow = document.createElement('tr');
    newRow.className = 'product-row';
    newRow.dataset.rowIndex = rowIndex;
    newRow.innerHTML = `
        <td class="py-3 px-4">
            <input type="hidden" name="items[${rowIndex}][product_id]" class="product-id-input">
            <input type="text" name="items[${rowIndex}][product_name]" 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">
            <input type="text" name="items[${rowIndex}][unit]" class="product-unit-input w-full h-10 px-3 rounded-lg border border-gray-300 bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" style="background-color: rgba(255, 255, 255, 1); color: rgba(0, 0, 0, 1); font-size: 15px; font-weight: 500;">
        </td>
        <td class="py-3 px-4">
            <input type="number" name="items[${rowIndex}][quantity]" value="1" min="0.01" step="0.01" 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" onchange="calculateRowTotal(this)">
        </td>
        <td class="py-3 px-4">
            <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" onchange="calculateRowTotal(this)">
        </td>
        <td class="py-3 px-4">
            <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" onchange="calculateRowTotal(this)">
        </td>
        <td class="py-3 px-4">
            <input type="number" name="items[${rowIndex}][tax]" value="0" step="0.01" min="0" max="100" 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" onchange="calculateRowTotal(this)">
        </td>
        <td class="py-3 px-4 text-right">
            <span class="product-amount text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount(0) }}</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-100 rounded-lg transition-colors">
                <span class="material-symbols-outlined text-lg">delete</span>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // Initialize product search for this row
    initializeProductSearch(newRow, rowIndex);
    
    rowIndex++;
    calculateTotal();
}

function initializeProductSearch(row, index) {
    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');
    
    let searchTimeout;
    let productDropdown = null;
    
    searchInput.addEventListener('input', function(e) {
        clearTimeout(searchTimeout);
        const searchValue = e.target.value.trim();
        
        if (productDropdown) {
            productDropdown.remove();
            productDropdown = null;
        }
        
        if (searchValue.length < 2) {
            return;
        }
        
        searchTimeout = setTimeout(function() {
            fetch('{{ route("admin.debit-notes.api.products") }}?search=' + encodeURIComponent(searchValue), {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && Array.isArray(data.products) && data.products.length > 0) {
                    showProductDropdown(searchInput, data.products, productIdInput, unitInput, rateInput);
                }
            })
            .catch(error => {
                console.error('Error fetching products:', error);
            });
        }, 300);
    });
    
    document.addEventListener('click', function(e) {
        if (productDropdown && !productDropdown.contains(e.target) && e.target !== searchInput) {
            productDropdown.remove();
            productDropdown = null;
        }
    });
}

function showProductDropdown(input, products, productIdInput, unitInput, rateInput) {
    if (productDropdown) {
        productDropdown.remove();
    }
    
    const dropdown = document.createElement('div');
    dropdown.className = 'product-dropdown absolute z-50 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'} - ${formatCurrency(product.purchase_price || 0)}</div>
        `;
        item.addEventListener('click', function() {
            input.value = product.name;
            productIdInput.value = product.id;
            unitInput.value = product.unit || '';
            rateInput.value = product.purchase_price || 0;
            dropdown.remove();
            productDropdown = null;
            calculateRowTotal(input.closest('tr'));
            calculateTotal();
        });
        dropdown.appendChild(item);
    });
    
    const inputRect = input.getBoundingClientRect();
    const td = input.closest('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';
    
    td.appendChild(dropdown);
    productDropdown = dropdown;
}

function calculateRowTotal(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 = formatCurrency(total);
    calculateTotal();
}

function calculateTotal() {
    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);
    
    document.getElementById('summary-amount').textContent = formatCurrency(subtotal);
    document.getElementById('summary-tax').textContent = formatCurrency(totalTax);
    document.getElementById('summary-discount').textContent = formatCurrency(totalDiscount);
    document.getElementById('summary-total').textContent = formatCurrency(roundedTotal);
    document.getElementById('summary-total-words').textContent = numberToWords(roundedTotal);
}

function numberToWords(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'];
    
    if (num === 0) return 'Zero';
    if (num < 10) return ones[num];
    if (num < 20) return teens[num - 10];
    if (num < 100) return tens[Math.floor(num / 10)] + (num % 10 ? ' ' + ones[num % 10] : '');
    if (num < 1000) return ones[Math.floor(num / 100)] + ' Hundred' + (num % 100 ? ' ' + numberToWords(num % 100) : '');
    if (num < 100000) return numberToWords(Math.floor(num / 1000)) + ' Thousand' + (num % 1000 ? ' ' + numberToWords(num % 1000) : '');
    return num.toString();
}

function removeRow(button) {
    const row = button.closest('tr');
    const tbody = document.getElementById('items-tbody');
    row.remove();
    
    if (tbody.querySelectorAll('.product-row').length === 0) {
        const emptyRow = document.createElement('tr');
        emptyRow.innerHTML = `
            <td colspan="8" class="py-8 px-4 text-center text-gray-500">
                No Items Selected
            </td>
        `;
        tbody.appendChild(emptyRow);
    }
    
    calculateTotal();
}

// Add event listeners for calculations
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) {
            calculateRowTotal(row);
            calculateTotal();
        }
    }
});

async function hydrateDebitNoteEdit() {
    if (!window.__DN_EDIT__) {
        return;
    }
    if (window.__EDIT_COMPANY__) {
        document.getElementById('company-id').value = window.__EDIT_COMPANY__.id;
        displayCompany(window.__EDIT_COMPANY__);
    } else {
        await loadCompanySettings();
    }
    if (window.__EDIT_SUPPLIER__) {
        displaySupplier(window.__EDIT_SUPPLIER__);
    }
    if (window.__EDIT_PURCHASE__) {
        document.getElementById('purchase_id').value = window.__EDIT_PURCHASE__.id;
        document.getElementById('purchase-search').value = window.__EDIT_PURCHASE__.label;
    }
    document.querySelectorAll('#items-tbody .product-row').forEach((row) => {
        const idx = parseInt(row.dataset.rowIndex, 10);
        initializeProductSearch(row, idx);
        calculateRowTotal(row);
    });
    const pm = document.querySelector('input[name="payment_method"]:checked')?.value || 'cash';
    PurchaseFormState.paymentMethod = pm;
    PurchaseFormState.renderPaymentMethod();
    if (pm === 'bank_transfer') {
        await PurchaseFormState.loadBankAccounts();
    }
    const st = document.querySelector('input[name="signature_type"]:checked')?.value || 'manual';
    PurchaseFormState.signatureType = st;
    if (st === 'esignature') {
        await PurchaseFormState.loadSignatures();
        if (window.__EDIT_SIGNATURE_ID__) {
            document.getElementById('signature_id').value = window.__EDIT_SIGNATURE_ID__;
        }
        PurchaseFormState.renderSignatureType();
    }
}

// ========== PAYMENT METHOD LOGIC ==========
const PurchaseFormState = {
    paymentMethod: 'cash',
    signatureType: 'manual',
    manualSignatureType: null,
    bankAccounts: [],
    signatures: [],
    
    init() {
        // Payment method change handlers
        document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.paymentMethod = e.target.value;
                this.renderPaymentMethod();
            });
        });
        
        // Signature type change handlers
        document.querySelectorAll('input[name="signature_type"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.signatureType = e.target.value;
                this.renderSignatureType();
            });
        });
        
        // Manual signature type change handlers
        document.querySelectorAll('input[name="manual_signature_type"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.manualSignatureType = e.target.value;
                this.renderManualSignatureType();
            });
        });
        
        // Load bank accounts and signatures
        this.loadBankAccounts();
        if (this.signatureType === 'esignature') {
            this.loadSignatures();
        }
        
        // Initialize signature handlers
        this.initSignatureHandlers();
    },
    
    renderPaymentMethod() {
        const bankAccountField = document.getElementById('bank-account-field');
        const bankAccountSelect = document.getElementById('bank_account_id');
        
        if (this.paymentMethod === 'bank_transfer') {
            bankAccountField.classList.remove('hidden');
            bankAccountSelect.required = true;
            if (this.bankAccounts.length === 0) {
                this.loadBankAccounts();
            }
        } else {
            bankAccountField.classList.add('hidden');
            bankAccountSelect.required = false;
            bankAccountSelect.value = '';
        }
    },
    
    renderSignatureType() {
        const manualContainer = document.getElementById('manual-signature-container');
        const esignatureContainer = document.getElementById('esignature-container');
        
        if (this.signatureType === 'manual') {
            manualContainer.classList.remove('hidden');
            esignatureContainer.classList.add('hidden');
            document.querySelectorAll('input[name="manual_signature_type"]').forEach(radio => {
                radio.checked = false;
            });
            this.manualSignatureType = null;
            this.hideAllManualSignatureContainers();
        } 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() {
        document.getElementById('draw-signature-container').classList.add('hidden');
        document.getElementById('upload-signature-container').classList.add('hidden');
        document.getElementById('signature-upload-preview').classList.add('hidden');
        document.getElementById('type-signature-container').classList.add('hidden');
    },
    
    async loadBankAccounts() {
        try {
            const response = await fetch('{{ route("admin.debit-notes.api.bank-accounts") }}', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            });
            const data = await response.json();
            
            if (data.success && data.bank_accounts) {
                this.bankAccounts = data.bank_accounts;
                const bankAccountSelect = document.getElementById('bank_account_id');
                bankAccountSelect.innerHTML = '<option value="">Select bank account...</option>';
                data.bank_accounts.forEach(account => {
                    const option = document.createElement('option');
                    option.value = account.id;
                    option.textContent = `${account.account_name} - ${account.bank_name} (${account.account_number})`;
                    bankAccountSelect.appendChild(option);
                });
            }
        } catch (error) {
            console.error('Error loading bank accounts:', error);
        }
    },
    
    async loadSignatures() {
        try {
            const response = await fetch('{{ route("admin.debit-notes.api.signatures") }}', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            });
            const data = await response.json();
            
            if (data.success && data.signatures) {
                this.signatures = data.signatures;
                const signatureSelect = document.getElementById('signature_id');
                signatureSelect.innerHTML = '<option value="">Select signature...</option>';
                data.signatures.forEach(signature => {
                    const option = document.createElement('option');
                    option.value = signature.id;
                    option.textContent = signature.name;
                    signatureSelect.appendChild(option);
                });
            }
        } catch (error) {
            console.error('Error loading signatures:', error);
        }
    },
    
    initCanvas() {
        const canvas = document.getElementById('signature-canvas');
        if (!canvas) return;
        
        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', (e) => {
            isDrawing = true;
            const rect = canvas.getBoundingClientRect();
            lastX = e.clientX - rect.left;
            lastY = e.clientY - rect.top;
        });
        
        canvas.addEventListener('mousemove', (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', () => {
            isDrawing = false;
            document.getElementById('signature-canvas-data').value = canvas.toDataURL('image/png');
        });
        
        canvas.addEventListener('mouseout', () => {
            isDrawing = false;
        });
        
        document.getElementById('clear-canvas').addEventListener('click', () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            document.getElementById('signature-canvas-data').value = '';
        });
    },
    
    initTypeSignature() {
        const textInput = document.getElementById('signature-text');
        const fontSelect = document.getElementById('signature-font');
        const preview = document.getElementById('signature-preview-text');
        
        const updatePreview = () => {
            const text = textInput.value.trim();
            const font = fontSelect.value;
            const fontFamilies = {
                'dancing': "'Dancing Script', cursive",
                'great-vibes': "'Great Vibes', cursive",
                'allura': "'Allura', cursive",
                'brush': "'Brush Script MT', cursive",
                'pacifico': "'Pacifico', cursive"
            };
            
            if (text) {
                preview.textContent = text;
                preview.style.fontFamily = fontFamilies[font] || fontFamilies['dancing'];
            } else {
                preview.textContent = 'Your signature will appear here';
            }
        };
        
        textInput.addEventListener('input', updatePreview);
        fontSelect.addEventListener('change', updatePreview);
    },
    
    initSignatureHandlers() {
        // Upload signature preview
        const uploadInput = document.getElementById('signature-upload');
        if (uploadInput) {
            uploadInput.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        document.getElementById('signature-preview-img').src = event.target.result;
                        document.getElementById('signature-upload-preview').classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    }
};

document.addEventListener('DOMContentLoaded', async function() {
    if (window.__DN_EDIT__) {
        await hydrateDebitNoteEdit();
    } else {
        await loadCompanySettings();
    }
    PurchaseFormState.init();
    if (!window.__DN_EDIT__) {
        const initialPaymentMethod = document.querySelector('input[name="payment_method"]:checked')?.value || 'cash';
        PurchaseFormState.paymentMethod = initialPaymentMethod;
        PurchaseFormState.renderPaymentMethod();
        const initialSignatureType = document.querySelector('input[name="signature_type"]:checked')?.value || 'manual';
        PurchaseFormState.signatureType = initialSignatureType;
        if (initialSignatureType === 'esignature') {
            await PurchaseFormState.loadSignatures();
        }
        PurchaseFormState.renderSignatureType();
    }
});

// Form validation
document.getElementById('debit-note-form').addEventListener('submit', function(e) {
    const companyId = document.getElementById('company-id').value;
    const companyDisplayEl = document.getElementById('company-display');
    const supplierId = document.getElementById('supplier-id').value;
    const orderDate = document.getElementById('order_date').value;
    const status = document.getElementById('status').value;
    const productRows = document.querySelectorAll('.product-row');
    
    // Validate company (server can resolve from settings when Bill From is visible)
    if (!window.__DN_EDIT__ && !companyId && companyDisplayEl.classList.contains('hidden')) {
        e.preventDefault();
        alert('Please select a company or ensure company settings are loaded');
        return false;
    }
    
    if (!supplierId) {
        e.preventDefault();
        alert('Please select a supplier');
        return false;
    }
    
    if (!orderDate) {
        e.preventDefault();
        alert('Please select order date');
        return false;
    }
    
    if (!status) {
        e.preventDefault();
        alert('Please select status');
        return false;
    }
    
    if (productRows.length === 0) {
        e.preventDefault();
        alert('Please add at least one product');
        return false;
    }
    
    // Validate payment method and bank account
    const paymentMethod = document.querySelector('input[name="payment_method"]:checked')?.value;
    if (paymentMethod === 'bank_transfer') {
        const bankAccountId = document.getElementById('bank_account_id').value;
        if (!bankAccountId) {
            e.preventDefault();
            alert('Please select a bank account for bank transfer');
            return false;
        }
    }
    
    const signatureType = document.querySelector('input[name="signature_type"]:checked')?.value;
    if (!window.__DN_EDIT__) {
        if (signatureType === 'esignature') {
            const signatureId = document.getElementById('signature_id').value;
            if (!signatureId) {
                e.preventDefault();
                alert('Please select a signature');
                return false;
            }
        } else if (signatureType === 'manual') {
            const manualSignatureType = document.querySelector('input[name="manual_signature_type"]:checked')?.value;
            if (!manualSignatureType) {
                e.preventDefault();
                alert('Please select a manual signature type');
                return false;
            }
            if (manualSignatureType === 'draw') {
                const canvasData = document.getElementById('signature-canvas-data').value;
                if (!canvasData) {
                    e.preventDefault();
                    alert('Please draw your signature');
                    return false;
                }
            } else if (manualSignatureType === 'upload') {
                const uploadFile = document.getElementById('signature-upload').files[0];
                if (!uploadFile) {
                    e.preventDefault();
                    alert('Please upload a signature image');
                    return false;
                }
            } else if (manualSignatureType === 'type') {
                const signatureText = document.getElementById('signature-text').value.trim();
                if (!signatureText) {
                    e.preventDefault();
                    alert('Please type your signature');
                    return false;
                }
            }
        }
    } else if (signatureType === 'esignature') {
        const signatureId = document.getElementById('signature_id').value;
        if (!signatureId) {
            e.preventDefault();
            alert('Please select a signature');
            return false;
        }
    }
    
    return true;
});
</script>
@endpush
@endsection
