@extends('layouts.admin')

@section('title', 'New Delivery Challan')

@section('page-title', 'New Delivery Challan')

@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.delivery-challans.index') }}" class="hover:text-primary">Delivery Challans</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">New Delivery Challan</span>
@endsection

@section('content')
<form method="POST" action="{{ route('admin.delivery-challans.store') }}" class="max-w-7xl mx-auto" id="delivery-challan-form" enctype="multipart/form-data">
    @csrf
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Content -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Challan 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">Delivery Challan 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</label>
                        <select id="invoice_id" name="invoice_id" 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-invoice='@json($invoice)'>{{ $invoice['text'] }}</option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Delivery Date -->
                    <div>
                        <label for="delivery_date" class="block text-sm font-medium text-gray-700 mb-2">
                            Delivery Date <span class="text-red-500">*</span>
                        </label>
                        <input type="date" id="delivery_date" name="delivery_date" value="{{ 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">Pending</option>
                            <option value="shipped">Shipped</option>
                            <option value="delivered">Delivered</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Bill From / Bill To: elevated stacking so dropdowns paint above the Products section below -->
            <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="bill_from" id="bill-from-user-id" value="{{ auth()->id() }}">
                        <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>
                                <input type="hidden" id="company-id" value=""/>
                            </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=""/>
                            </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 (below bill panels; keep below bill dropdown stacking) -->
            <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">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500">Product / Service</th>
                                <th class="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 w-20">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>
                                <td colspan="8" class="py-8 px-4 text-center text-gray-500">
                                    No Items Selected
                                </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 purchases) -->
            <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">
                        <button type="button" onclick="dcSwitchTab('notes')" id="dc-tab-notes" class="dc-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="dcSwitchTab('terms')" id="dc-tab-terms" class="dc-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="dcSwitchTab('payment')" id="dc-tab-payment" class="dc-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="dc-content-notes" class="dc-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="dc-content-terms" class="dc-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="dc-content-payment" class="dc-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 dc-payment-method-radio" id="dc-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 dc-payment-method-radio" id="dc-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 dc-payment-method-radio" id="dc-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 dc-payment-method-radio" id="dc-payment-cheque">
                                        <span class="text-sm text-gray-700">Cheque</span>
                                    </label>
                                </div>
                            </div>
                            <div id="dc-bank-account-field" class="hidden">
                                <label for="dc-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="dc-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 purchases) -->
            <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" checked class="text-primary focus:ring-primary" id="dc-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" class="text-primary focus:ring-primary" id="dc-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" 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>
                        <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" 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 text-gray-900" 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="dc-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="text-sm font-medium text-gray-900 text-gray-900 summary-amount">{{ \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="text-sm font-medium text-gray-900 text-gray-900 summary-tax">{{ \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="text-sm font-medium text-gray-900 text-gray-900 summary-discount">-{{ \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 text-gray-900">Total (Rounded)</span>
                        <span class="text-lg font-bold text-gray-900 text-gray-900 summary-total">{{ \App\Models\Currency::formatAmount(0, $defaultCurrencyCode) }}</span>
                    </div>
                    <p class="text-sm text-gray-500 italic summary-total-words">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 Delivery Challan
                    </button>
                    <a href="{{ route('admin.delivery-challans.index') }}" class="w-full py-3 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50800 transition-colors flex items-center justify-center gap-2">
                        Cancel
                    </a>
                </div>
            </div>
        </div>
    </div>
</form>

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container--default .select2-selection--single {
        height: 44px;
        border: 1px solid #d1d5db;
        border-radius: 0.5rem;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 44px;
        padding-left: 16px;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 42px;
    }
    .select2-container {
        color: rgba(0, 0, 0, 1);
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: rgba(0, 0, 0, 1) !important;
    }
    .select2-search__field {
        color: rgba(0, 0, 0, 1) !important;
    }
    .select2-selection__placeholder {
        color: rgba(0, 0, 0, 1) !important;
    }
    span.select2 {
        color: rgba(0, 0, 0, 1);
    }
</style>
@endpush

@push('scripts')
@php
    $dcCurrencyClient = [
        'code' => $defaultCurrencyCode ?? \App\Models\Currency::getDefaultCode(),
        'symbol' => $defaultCurrencySymbol ?? \App\Models\Currency::getSymbol(),
        'symbolPosition' => $defaultCurrencySymbolPosition ?? 'before',
        'decimalPlaces' => (int) ($defaultCurrencyDecimalPlaces ?? 2),
    ];
@endphp
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    window.deliveryChallanCurrency = {!! json_encode($dcCurrencyClient) !!};

    function dcFormatMoney(value) {
        const cfg = window.deliveryChallanCurrency || { 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);
    }

    window.dcSwitchTab = function(tab) {
        document.querySelectorAll('.dc-tab-content').forEach(function(el) { el.classList.add('hidden'); });
        document.querySelectorAll('.dc-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('dc-content-' + tab);
        if (contentEl) contentEl.classList.remove('hidden');
        const activeTab = document.getElementById('dc-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') {
            const method = document.querySelector('#dc-content-payment input[name="payment_method"]:checked')?.value
                || document.querySelector('input[name="payment_method"]:checked')?.value
                || 'cash';
            DcFormState.setPaymentMethod(method);
        }
    };

    const DcFormState = {
        paymentMethod: 'cash',
        signatureType: 'manual',
        manualSignatureType: null,
        bankAccounts: [],
        signatures: [],

        setPaymentMethod(method) {
            this.paymentMethod = method;
            this.renderPaymentMethod();
        },

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

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

        renderPaymentMethod() {
            const bankAccountField = document.getElementById('dc-bank-account-field');
            const bankAccountSelect = document.getElementById('dc-bank-account-select');
            if (!bankAccountField || !bankAccountSelect) return;
            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 (!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();
                dcResetEsignaturePreview();
            } 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 loadBankAccounts() {
            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 (' + response.status + ')');
                const data = await response.json();
                if (data.success && data.bank_accounts) {
                    this.bankAccounts = data.bank_accounts;
                    const bankAccountSelect = document.getElementById('dc-bank-account-select');
                    if (!bankAccountSelect) return;
                    bankAccountSelect.innerHTML = '<option value="">Select bank account...</option>';
                    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 + ')';
                        bankAccountSelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading bank accounts:', error);
            }
        },

        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 (' + response.status + ')');
                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(function(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 || canvas.dataset.dcBound === '1') return;
            canvas.dataset.dcBound = '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;
                DcFormState.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;
                DcFormState.saveCanvasData();
            });

            const clearBtn = document.getElementById('clear-canvas');
            if (clearBtn && !clearBtn.dataset.dcBound) {
                clearBtn.dataset.dcBound = '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 container = document.getElementById('type-signature-container');
            if (!container) return;
            const textInput = container.querySelector('#signature-text');
            const fontSelect = container.querySelector('#signature-font');
            const previewText = container.querySelector('#signature-preview-text');
            if (!textInput || !fontSelect || !previewText) return;

            const updatePreview = function() {
                const text = textInput.value.trim();
                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"
                };
                if (text) {
                    previewText.textContent = text;
                    previewText.style.fontFamily = fontMap[font] || fontMap['dancing'];
                } else {
                    previewText.textContent = 'Your signature will appear here';
                    previewText.style.fontFamily = fontMap['dancing'];
                }
            };

            if (textInput.dataset.dcTypeBound === '1') {
                updatePreview();
                return;
            }
            textInput.dataset.dcTypeBound = '1';
            textInput.addEventListener('input', updatePreview);
            fontSelect.addEventListener('change', updatePreview);
            updatePreview();
        },
    };

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

    function dcHandleSignatureTypeChange(event) {
        DcFormState.setSignatureType(event.target.value);
    }

    function dcHandleManualSignatureTypeChange(event) {
        DcFormState.setManualSignatureType(event.target.value);
    }

    function dcBindRadioGroup(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 dcHandleSignatureUpload(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);
    }

    let rowIndex = 0;
    let dcCompanySearchTimeout;
    let dcCompanyAbortController;
    let dcCustomerSearchTimeout;
    let dcCustomerAbortController;

    function dcDisplayCompany(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 (!companyDisplay || !companySearch) {
            return;
        }
        if (companyIdInput) {
            companyIdInput.value = company.id ? company.id : '';
        }
        companySearch.value = company.name || '';
        companyDisplay.classList.remove('hidden');
        companyDisplayName.textContent = company.name || '';
        if (company.logo) {
            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) {
            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>';
        }
        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 dcSearchCompanies(searchTerm) {
        const companyDropdown = document.getElementById('company-dropdown');
        const companyLoading = document.getElementById('company-loading');
        if (dcCompanyAbortController) dcCompanyAbortController.abort();
        dcCompanyAbortController = 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: dcCompanyAbortController.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 = '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', function() {
                            dcDisplayCompany(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(function(error) {
                if (error.name !== 'AbortError') {
                    if (companyLoading) companyLoading.classList.add('hidden');
                    if (companyDropdown) {
                        companyDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-red-500">Error loading companies</div>';
                        companyDropdown.classList.remove('hidden');
                    }
                }
            });
    }

    function dcLoadCompanySettings() {
        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) {
                    dcDisplayCompany(data.company);
                }
            })
            .catch(function(e) {
                console.error('Error loading company settings:', e);
            });
    }

    function dcDisplayCustomer(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');
        const displayName = customer.company || customer.name;
        customerDisplayName.textContent = displayName || '';
        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>';
        if (customer.city || customer.state || customer.zip) {
            const location = [customer.city, customer.state, customer.zip].filter(Boolean).join(', ');
            if (location) detailsHTML += '<p>' + location + '</p>';
        }
        if (customer.country) detailsHTML += '<p>' + customer.country + '</p>';
        customerDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
        if (customerDropdown) customerDropdown.classList.add('hidden');
    }

    function dcClearCustomer() {
        const customerIdInput = document.getElementById('customer-id');
        const customerSearch = document.getElementById('customer-search');
        const customerDisplay = document.getElementById('customer-display');
        const customerDisplayDetails = document.getElementById('customer-display-details');
        const customerDisplayName = document.getElementById('customer-display-name');
        const customerLogoContainer = document.getElementById('customer-logo-container');
        if (customerIdInput) customerIdInput.value = '';
        if (customerSearch) customerSearch.value = '';
        if (customerDisplay) customerDisplay.classList.add('hidden');
        if (customerDisplayDetails) customerDisplayDetails.innerHTML = '';
        if (customerDisplayName) customerDisplayName.textContent = '';
        if (customerLogoContainer) customerLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">person</span>';
    }

    function dcSearchCustomers(searchTerm) {
        const customerDropdown = document.getElementById('customer-dropdown');
        const customerLoading = document.getElementById('customer-loading');
        if (dcCustomerAbortController) dcCustomerAbortController.abort();
        dcCustomerAbortController = 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: dcCustomerAbortController.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 = 'customer-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">' + customer.name + '</div>' +
                            (customer.email ? '<div class="text-xs text-gray-500">' + customer.email + '</div>' : '');
                        option.addEventListener('click', function() {
                            dcDisplayCustomer(customer);
                        });
                        customerDropdown.appendChild(option);
                    });
                    customerDropdown.classList.remove('hidden');
                } 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') {
                    if (customerLoading) customerLoading.classList.add('hidden');
                    if (customerDropdown) {
                        customerDropdown.innerHTML = '<div class="px-4 py-2 text-sm text-red-500">Error loading customers</div>';
                        customerDropdown.classList.remove('hidden');
                    }
                }
            });
    }

    function initDeliveryChallanBillFromBillTo() {
        dcLoadCompanySettings();
        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 customerDropdown = document.getElementById('customer-dropdown');
        const customerLoading = document.getElementById('customer-loading');
        if (companySearch) {
            companySearch.addEventListener('input', function() {
                const term = this.value.trim();
                clearTimeout(dcCompanySearchTimeout);
                dcCompanySearchTimeout = setTimeout(function() {
                    dcSearchCompanies(term);
                }, 300);
            });
            companySearch.addEventListener('focus', function() {
                dcSearchCompanies(this.value.trim());
            });
        }
        document.addEventListener('click', function(e) {
            if (companySearchContainer && companyDropdown && companyLoading) {
                if (!companySearchContainer.contains(e.target) && !companyDropdown.contains(e.target) && !companyLoading.contains(e.target)) {
                    companyDropdown.classList.add('hidden');
                    companyLoading.classList.add('hidden');
                }
            }
            if (customerSearch && customerDropdown && customerLoading) {
                const csc = document.getElementById('customer-search-container');
                if (csc && !csc.contains(e.target) && !customerDropdown.contains(e.target) && !customerLoading.contains(e.target)) {
                    customerDropdown.classList.add('hidden');
                    customerLoading.classList.add('hidden');
                }
            }
        });
        if (customerSearch) {
            customerSearch.addEventListener('input', function() {
                const term = this.value.trim();
                clearTimeout(dcCustomerSearchTimeout);
                dcCustomerSearchTimeout = setTimeout(function() {
                    dcSearchCustomers(term);
                }, 300);
            });
            customerSearch.addEventListener('focus', function() {
                dcSearchCustomers(this.value.trim());
            });
        }
    }

    $(document).ready(function() {
        // Initialize Select2 for Invoice dropdown with pre-populated data
        $('#invoice_id').select2({
            placeholder: 'Search and select invoice',
            allowClear: true,
            width: '100%',
            ajax: {
                url: '{{ route("admin.delivery-challans.api.invoices") }}',
                type: 'GET',
                dataType: 'json',
                delay: 250,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                data: function(params) {
                    return { search: params.term || '' };
                },
                processResults: function(data) {
                    if (data.success && Array.isArray(data.invoices)) {
                        return {
                            results: data.invoices.map(function(invoice) {
                                return {
                                    id: invoice.id,
                                    text: invoice.text,
                                    invoice: invoice
                                };
                            })
                        };
                    }
                    return { results: [] };
                },
                cache: false
            },
            minimumInputLength: 0
        });

        // Handle Invoice selection to auto-populate customer and items
        $('#invoice_id').on('select2:select', function(e) {
            const invoiceId = e.params.data.id;
            if (invoiceId) {
                fetch('{{ route("admin.delivery-challans.api.invoice-details", ":id") }}'.replace(':id', invoiceId), {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.invoice) {
                        // Auto-populate customer
                        if (data.invoice.customer) {
                            const customer = data.invoice.customer;
                            dcDisplayCustomer({
                                id: customer.id,
                                name: customer.name,
                                email: customer.email,
                                phone: customer.phone,
                                company: customer.company,
                                address: customer.address,
                                city: customer.city,
                                state: customer.state,
                                zip: customer.zip,
                                country: customer.country,
                            });
                        }
                        
                        // Auto-populate items
                        if (data.invoice.items && data.invoice.items.length > 0) {
                            // Clear existing rows
                            const tbody = document.getElementById('product-rows');
                            tbody.innerHTML = '';
                            rowIndex = 0;
                            
                            // Add items from invoice
                            data.invoice.items.forEach(function(item) {
                                addNewRow();
                                const lastRow = tbody.querySelector('tr:last-child');
                                if (lastRow) {
                                    const searchInput = lastRow.querySelector('.product-search-input');
                                    const quantityInput = lastRow.querySelector('.product-quantity-input');
                                    const rateInput = lastRow.querySelector('.product-rate-input');
                                    const taxInput = lastRow.querySelector('.product-tax-input');
                                    
                                    if (searchInput) searchInput.value = item.description;
                                    if (quantityInput) quantityInput.value = item.quantity;
                                    if (rateInput) rateInput.value = item.unit_price;
                                    if (taxInput) taxInput.value = item.tax_rate || 0;
                                    
                                    calculateRowTotal(lastRow);
                                }
                            });
                            calculateTotal();
                        }
                    }
                })
                .catch(error => {
                    console.error('Error fetching invoice details:', error);
                });
            }
        });
        
        $('#invoice_id').on('select2:clear', function() {
            dcClearCustomer();
        });

        initDeliveryChallanBillFromBillTo();

        const dcFormEl = document.getElementById('delivery-challan-form');
        if (dcFormEl) {
            dcFormEl.addEventListener('change', function(e) {
                if (e.target && e.target.name === 'payment_method') {
                    DcFormState.setPaymentMethod(e.target.value);
                }
            });
        }
        dcBindRadioGroup('payment_method', function(value) {
            DcFormState.setPaymentMethod(value);
        });
        dcBindRadioGroup('signature_type', function(value) {
            DcFormState.setSignatureType(value);
        });
        dcBindRadioGroup('manual_signature_type', function(value) {
            DcFormState.setManualSignatureType(value);
        });
        const signatureUpload = document.getElementById('signature-upload');
        if (signatureUpload) {
            signatureUpload.addEventListener('change', dcHandleSignatureUpload);
        }
        const signatureIdSelect = document.getElementById('signature_id');
        if (signatureIdSelect) {
            signatureIdSelect.addEventListener('change', function() {
                const id = this.value;
                const preview = document.getElementById('dc-esignature-preview');
                if (!preview) return;
                const sig = DcFormState.signatures.find(function(s) { return String(s.id) === String(id); });
                if (sig && sig.url) {
                    preview.innerHTML = '<img src="' + sig.url + '" alt="" class="w-[255px] max-h-24 object-contain">';
                } else {
                    dcResetEsignaturePreview();
                }
            });
        }

        const initialPayment = document.querySelector('#dc-content-payment input[name="payment_method"]:checked')?.value
            || document.querySelector('input[name="payment_method"]:checked')?.value
            || 'cash';
        DcFormState.setPaymentMethod(initialPayment);
        const initialSigType = document.querySelector('input[name="signature_type"]:checked')?.value || 'manual';
        DcFormState.setSignatureType(initialSigType);
    });

    function addNewRow() {
        const tbody = document.getElementById('product-rows');
        
        // Remove the "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]" 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-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 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">
                <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-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </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-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </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-gray-900 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary">
            </td>
            <td class="py-3 px-4">
                <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-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">
                <span class="product-amount text-sm font-medium text-gray-900 text-gray-900">${dcFormatMoney(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.delivery-challans.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);
        });
        
        // Hide dropdown when clicking outside
        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) {
        // Remove existing dropdown
        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'} - ${dcFormatMoney(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();
                productDropdown = null;
                calculateRowTotal(input.closest('tr'));
                calculateTotal();
            });
            dropdown.appendChild(item);
        });
        
        // Position dropdown relative to input
        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';
        dropdown.style.maxWidth = 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 = dcFormatMoney(total);
    }

    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);
        
        // Update summary
        document.querySelector('.summary-amount').textContent = dcFormatMoney(subtotal);
        document.querySelector('.summary-tax').textContent = dcFormatMoney(totalTax);
        document.querySelector('.summary-discount').textContent = '-' + dcFormatMoney(totalDiscount);
        document.querySelector('.summary-total').textContent = dcFormatMoney(roundedTotal);
        document.querySelector('.summary-total-words').textContent = numberToWords(roundedTotal);
    }

    function numberToWords(num) {
        // Simple number to words converter (you can enhance this)
        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) : '');
        return num.toString();
    }

    function removeRow(button) {
        const row = button.closest('tr');
        const tbody = document.getElementById('product-rows');
        row.remove();
        
        // If no rows left, show "No Items" message
        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();
            }
        }
    });

    document.getElementById('delivery-challan-form').addEventListener('submit', function(e) {
        const customerId = document.getElementById('customer-id') ? document.getElementById('customer-id').value : '';
        const billFrom = document.getElementById('bill-from-user-id') ? document.getElementById('bill-from-user-id').value : '';
        const deliveryDate = document.getElementById('delivery_date').value;
        const status = document.getElementById('status').value;
        const productRows = document.querySelectorAll('.product-row');

        if (!customerId) {
            e.preventDefault();
            alert('Please select a customer');
            return false;
        }
        if (!billFrom) {
            e.preventDefault();
            alert('Please select Bill From');
            return false;
        }
        if (!deliveryDate) {
            e.preventDefault();
            alert('Please select delivery 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;
        }

        const paymentMethod = document.querySelector('input[name="payment_method"]:checked')?.value;
        if (paymentMethod === 'bank_transfer') {
            const bankAccountId = document.getElementById('dc-bank-account-select')?.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 (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;
                }
            }
        }

        return true;
    });
</script>
@endpush
@endsection




