@extends('layouts.admin')

@section('title', 'Add New Quotation')

@section('page-title', 'Add New Quotation')

@section('content')
<div class="w-full pb-24 min-w-0">
    <div class="max-w-[1400px] mx-auto px-6 py-6 flex flex-col gap-6">
    <!-- Breadcrumbs -->
    <nav class="flex flex-wrap mb-4 sm:mb-6 text-xs sm:text-sm font-medium text-gray-500">
        <a class="hover:text-primary transition-colors" href="{{ route('admin.dashboard') }}">Dashboard</a>
        <span class="mx-2">/</span>
            <a class="hover:text-primary transition-colors" href="{{ route('admin.quotations.index') }}">Sales</a>
        <span class="mx-2">/</span>
            <span class="text-gray-900">Add New Quotation</span>
    </nav>
    
    <!-- Page Heading -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 mb-6 sm:mb-8">
        <div class="min-w-0 flex-1">
                <h1 class="text-2xl sm:text-3xl font-black text-gray-900 tracking-tight mb-2">Add New Quotation</h1>
            <p class="text-sm sm:text-base text-gray-500">Create a new estimate for your customer.</p>
        </div>
    </div>
    
    <!-- Form Container -->
        <form method="POST" action="{{ route('admin.quotations.store') }}" id="quotation-form" class="flex flex-col gap-6" enctype="multipart/form-data">
        @csrf
            <input type="hidden" name="status" id="quotation-status" value="draft">
            <input type="hidden" name="signature_id" id="form-signature-id" value="{{ old('signature_id') }}">
            <input type="hidden" name="document_title" id="document-title" value="{{ old('document_title', 'quotation') }}">
        
        <!-- Document Title Selection -->
        <section class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-4 sm:px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-bold text-gray-900">Document Title</h3>
                <p class="text-xs text-gray-500 mt-1">This title will appear on the preview and final quotation</p>
            </div>
            <div class="p-4 sm:p-6">
                <div class="flex gap-4">
                    <label class="flex items-center gap-3 p-4 border-2 rounded-lg cursor-pointer transition-all hover:border-primary/50 has-[:checked]:border-primary has-[:checked]:bg-primary/5">
                        <input type="radio" name="document_title_radio" value="quotation" {{ old('document_title', 'quotation') == 'quotation' ? 'checked' : '' }} onchange="updateDocumentTitle(this.value);" class="text-primary focus:ring-primary">
                        <div>
                            <div class="font-semibold text-gray-900">Quotation</div>
                            <div class="text-xs text-gray-500 mt-0.5">Standard quotation document</div>
                        </div>
                    </label>
                    <label class="flex items-center gap-3 p-4 border-2 rounded-lg cursor-pointer transition-all hover:border-primary/50 has-[:checked]:border-primary has-[:checked]:bg-primary/5">
                        <input type="radio" name="document_title_radio" value="estimate" {{ old('document_title', 'quotation') == 'estimate' ? 'checked' : '' }} onchange="updateDocumentTitle(this.value);" class="text-primary focus:ring-primary">
                        <div>
                            <div class="font-semibold text-gray-900">Estimate</div>
                            <div class="text-xs text-gray-500 mt-0.5">Cost estimate document</div>
                        </div>
                    </label>
                </div>
            </div>
        </section>

        <!-- Card 1: Quotation Details -->
        <section class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-4 sm:px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                    <h3 class="text-lg font-bold text-gray-900">Quotation Details</h3>
                    <span class="text-xs font-semibold uppercase tracking-wider text-gray-500 bg-gray-100 px-2 py-1 rounded" id="status-badge">Draft</span>
            </div>
            <div class="p-4 sm:p-6 flex flex-col gap-4 lg:gap-6">
                <!-- First Row: Document Title, Quotation No, Quotation Date (3 columns) -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Quotation Title</label>
                        <input type="text" name="quotation_title" id="quotation-title" value="{{ old('quotation_title', 'Quotation') }}" placeholder="e.g. Quotation, Estimate, Proposal" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                        <p class="text-xs text-gray-500 mt-1">Title to show on preview</p>
                    </div>
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Quotation No. <span class="text-red-500">*</span></label>
                        <div class="relative z-10">
                            <span class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 font-medium">#</span>
                            <input type="text" name="quotation_number" id="quotation-number" value="{{ old('quotation_number', $nextQuotationNumber ?? '') }}" required class="w-full h-10 pl-7 pr-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                        </div>
                        <p class="text-xs text-gray-500 mt-1">Auto-generated</p>
                    </div>
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Quotation Date <span class="text-red-500">*</span></label>
                        <input type="date" name="issue_date" id="issue-date" value="{{ old('issue_date', now()->format('Y-m-d')) }}" required class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                    </div>
                </div>

                <!-- Second Row: Expiry Date, Reference #, Sales Person (3 columns) -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 lg:gap-6">
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Expiry Date</label>
                        <input type="date" name="expiry_date" id="expiry-date" value="{{ old('expiry_date', $defaultExpiryDate ?? now()->addDays(30)->format('Y-m-d')) }}" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                    </div>
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Reference #</label>
                        <input type="text" name="reference_number" value="{{ old('reference_number') }}" placeholder="e.g. PO-2023-001" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                    </div>
                    <div class="flex flex-col gap-2">
                        <label class="text-sm font-semibold text-gray-900">Sales Person</label>
                        <input type="text" name="sales_person" value="{{ old('sales_person', Auth::user()->name) }}" placeholder="Sales person name" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                    </div>
                </div>

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

                    <!-- Bill To -->
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                        <div class="flex justify-between items-start mb-4">
                            <h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wider">Bill To <span class="text-red-500">*</span></h3>
                            <a href="{{ route('admin.customers.create') }}" target="_blank" class="text-primary text-sm font-medium hover:underline flex items-center gap-1">
                                <span class="material-symbols-outlined text-base">add</span>
                                <span>+ New Customer</span>
                            </a>
                        </div>
                        <div class="space-y-4">
                            <!-- Customer Search -->
                            <div id="customer-search-container" class="relative">
                                <div class="relative">
                                    <input type="text" id="customer-search" autocomplete="off" placeholder="Type to search customers..." class="w-full h-10 rounded-lg border border-gray-300 bg-white px-3 pr-10 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900 placeholder:text-gray-500"/>
                                    <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-lg">search</span>
                                    <input type="hidden" name="customer_id" id="customer-id" required value="{{ old('customer_id') }}"/>
                                </div>
                                <div id="customer-dropdown" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                                    <!-- Results will be populated via AJAX -->
                                </div>
                                <div id="customer-loading" class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg p-4">
                                    <div class="flex items-center gap-2 text-sm text-gray-500">
                                        <svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                        <span>Loading...</span>
                                    </div>
                                </div>
                            </div>
                            <!-- Customer Display Card -->
                            <div id="customer-display" class="hidden">
                                <div class="bg-gray-50 rounded-lg border border-gray-200 p-4">
                                    <div class="flex items-start gap-4">
                                        <div id="customer-logo-container" class="flex-shrink-0 w-12 h-12 rounded-full bg-primary/20 flex items-center justify-center overflow-hidden text-primary font-bold">
                                            <span class="material-symbols-outlined text-gray-400">person</span>
                                        </div>
                                        <div class="flex-1">
                                            <h4 id="customer-display-name" class="text-base font-bold text-gray-900 mb-2"></h4>
                                            <div class="text-sm text-gray-600 flex flex-col gap-1" id="customer-display-details">
                                                <!-- Customer details will be inserted here -->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
            <!-- Card 2: Items Table -->
        <section class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="px-4 sm:px-6 py-4 border-b border-gray-200 bg-gray-50/50">
                <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 lg:gap-6">
                    <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-6 lg:gap-8">
                        <h3 class="text-lg font-bold text-gray-900">Items</h3>
                        <div class="flex flex-col gap-1">
                            <label class="text-xs font-medium text-gray-500">Currency</label>
                            <div class="flex items-center gap-2">
                                <span class="material-symbols-outlined text-gray-900 text-lg">attach_money</span>
                                <select name="currency" id="currency-select" class="text-sm font-bold text-gray-900 bg-transparent border-none p-0 pr-6 focus:ring-0 cursor-pointer">
                                    @php
                                        $defaultCurrency = $localizationSettings->default_currency ?? 'USD';
                                    @endphp
                                    @foreach($currencies as $currency)
                                        <option value="{{ $currency->code }}" {{ old('currency', $defaultCurrency) == $currency->code ? 'selected' : '' }} data-symbol="{{ $currency->symbol }}" data-position="{{ $currency->symbol_position ?? 'before' }}">
                                            {{ $currency->code }} - {{ $currency->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-6">
                        <!-- Item Type -->
                        <div class="flex flex-col gap-1">
                            <label class="text-xs font-medium text-gray-500">Item Type</label>
                            <div class="flex items-center gap-3">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="item_type" value="product" checked class="text-primary focus:ring-primary" onchange="updateItemType(this.value)">
                                    <span class="text-sm font-medium text-gray-900">Product</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="item_type" value="service" class="text-primary focus:ring-primary" onchange="updateItemType(this.value)">
                                    <span class="text-sm font-medium text-gray-900">Service</span>
                                </label>
                            </div>
                        </div>
                        <!-- Products/Services Select -->
                        <div class="flex flex-col gap-1 w-full sm:w-auto">
                            <label class="text-xs font-medium text-gray-500">Products/Services</label>
                            <select id="product-service-select" class="text-sm font-medium text-gray-900 bg-white border border-gray-200 rounded-lg px-3 py-1.5 focus:ring-1 focus:ring-primary focus:border-primary cursor-pointer w-full sm:min-w-[200px]">
                                <option value="">Select from system</option>
                                <!-- Products/Services will be loaded here via JavaScript -->
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full min-w-[600px] sm:min-w-[800px] text-left border-collapse">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[35%]">Product / Service</th>
                            <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[10%]">Unit</th>
                            <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[10%]">Qty</th>
                            <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[12%]">Rate</th>
                                <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[10%]">Tax %</th>
                            <th class="p-4 text-xs font-bold text-gray-500 uppercase tracking-wider w-[10%] text-right">Amount</th>
                            <th class="p-4 w-[3%]"></th>
                        </tr>
                    </thead>
                        <tbody class="text-sm text-gray-900" id="items-tbody">
                            <tr class="group border-b border-gray-100 hover:bg-gray-50/50 transition-colors" data-index="0">
                            <td class="p-4 align-top">
                                <div class="flex flex-col gap-2">
                                        <input name="items[0][description]" required class="w-full border-none p-0 bg-transparent focus:ring-0 font-medium placeholder:text-gray-400" placeholder="Item name" type="text" value="{{ old('items.0.description', '') }}">
                                        <textarea name="items[0][notes]" class="w-full text-xs text-gray-500 border-none bg-transparent p-0 focus:ring-0 resize-none overflow-hidden" placeholder="Add description..." rows="1">{{ old('items.0.notes', '') }}</textarea>
                                </div>
                            </td>
                            <td class="p-4 align-top">
                                <select name="items[0][unit]" class="w-full border border-gray-200 rounded bg-transparent text-xs py-1 px-2 focus:ring-1 focus:ring-primary">
                                        <option value="pcs" {{ old('items.0.unit', 'pcs') == 'pcs' ? 'selected' : '' }}>pcs</option>
                                        <option value="hrs" {{ old('items.0.unit') == 'hrs' ? 'selected' : '' }}>hrs</option>
                                        <option value="days" {{ old('items.0.unit') == 'days' ? 'selected' : '' }}>days</option>
                                        <option value="kg" {{ old('items.0.unit') == 'kg' ? 'selected' : '' }}>kg</option>
                                </select>
                            </td>
                            <td class="p-4 align-top">
                                    <input name="items[0][quantity]" type="number" step="0.01" value="{{ old('items.0.quantity', '1') }}" required onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
                            </td>
                            <td class="p-4 align-top">
                                    <input name="items[0][unit_price]" type="number" step="0.01" placeholder="0.00" value="{{ old('items.0.unit_price', '0') }}" required onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
                            </td>
                            <td class="p-4 align-top">
                                    <input name="items[0][tax_rate]" type="number" step="0.01" min="0" max="100" value="{{ old('items.0.tax_rate', '0') }}" onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
                            </td>
                                <td class="p-4 align-top text-right font-medium text-gray-900">
                                    <span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span class="item-amount">0.00</span>
                            </td>
                            <td class="p-4 align-top text-center">
                                    <button type="button" onclick="removeItemRow(this)" class="text-gray-400 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100">
                                    <span class="material-symbols-outlined text-[20px]">delete</span>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="p-4 bg-gray-50/30 border-t border-gray-200 flex gap-3">
                <button type="button" onclick="addItemRow()" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-bold hover:bg-blue-600 transition-colors shadow-sm">
                    <span class="material-symbols-outlined text-[20px]">add</span>
                    Add New Line
                </button>
            </div>
        </section>
        
        <!-- Card 3 & 4: Extra Info & Totals -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Extra Info -->
            <section class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 flex flex-col gap-6">
                <!-- 2-Column Accordion -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Notes Accordion -->
                    <div class="flex flex-col">
                        <button type="button" onclick="toggleAccordion('notes-accordion')" class="flex items-center justify-between gap-2 px-4 py-3 bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 transition-colors text-left">
                            <span class="text-sm font-semibold text-gray-900">Add Notes</span>
                            <span class="material-symbols-outlined text-lg text-gray-600 accordion-icon" id="notes-accordion-icon">expand_more</span>
                        </button>
                        <div id="notes-accordion" class="hidden mt-3">
                            <textarea name="notes" class="w-full min-h-[80px] px-3 py-2 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm resize-y" placeholder="Notes displayed to the customer...">{{ old('notes', $quotationSettings->notes ?? '') }}</textarea>
                        </div>
                    </div>
                    
                    <!-- Terms & Conditions Accordion -->
                    <div class="flex flex-col">
                        <button type="button" onclick="toggleAccordion('terms-accordion')" class="flex items-center justify-between gap-2 px-4 py-3 bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 transition-colors text-left">
                            <span class="text-sm font-semibold text-gray-900">Add Terms & Conditions</span>
                            <span class="material-symbols-outlined text-lg text-gray-600 accordion-icon" id="terms-accordion-icon">expand_more</span>
                        </button>
                        <div id="terms-accordion" class="hidden mt-3">
                            <textarea name="terms" class="w-full min-h-[100px] px-3 py-2 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm resize-y" placeholder="Add terms and conditions...">{{ old('terms', $quotationSettings->terms ?? '') }}</textarea>
                        </div>
                    </div>
                    
                    <!-- Bank Details Accordion -->
                    <div class="flex flex-col">
                        <button type="button" onclick="toggleAccordion('bank-accordion')" class="flex items-center justify-between gap-2 px-4 py-3 bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 transition-colors text-left">
                            <span class="text-sm font-semibold text-gray-900">Add Bank Details</span>
                            <span class="material-symbols-outlined text-lg text-gray-600 accordion-icon" id="bank-accordion-icon">expand_more</span>
                        </button>
                        <div id="bank-accordion" class="hidden mt-3">
                            <select name="bank_account_id" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                                <option value="">Select Bank Account</option>
                                @foreach($bankAccounts ?? [] as $bankAccount)
                                    <option value="{{ $bankAccount->id }}" {{ old('bank_account_id') == $bankAccount->id ? 'selected' : '' }}>
                                        {{ $bankAccount->bank_name }} - {{ $bankAccount->account_name }} ({{ $bankAccount->account_number }})
                                    </option>
                                @endforeach
                            </select>
                            @if(($bankAccounts ?? collect())->isEmpty())
                                <p class="text-xs text-gray-500 mt-2">No bank accounts available. <a href="{{ route('admin.banking.create') }}" class="text-primary hover:underline">Add one</a></p>
                            @endif
                        </div>
                    </div>
                </div>
                
                <!-- Signature Section -->
                <div class="flex flex-col gap-2 mt-4">
                        <label class="text-sm font-semibold text-gray-900">Signature</label>
                        <select name="signature_id" id="signature-select" class="w-full h-10 px-3 rounded-lg border border-gray-200 bg-white text-gray-900 focus:ring-1 focus:ring-primary focus:border-primary text-sm">
                            <option value="">No Signature</option>
                            @foreach($signatures as $signature)
                                <option value="{{ $signature->id }}" {{ old('signature_id') == $signature->id ? 'selected' : '' }}>{{ $signature->name }}</option>
                            @endforeach
                    </select>
                        @if($signatures->count() > 0)
                            <div id="signature-preview" class="mt-4 border-2 border-dashed border-gray-200 rounded-lg p-4 bg-gray-50/50 min-h-[100px] flex items-center justify-center">
                                <p class="text-sm text-gray-500">Select a signature to preview</p>
                            </div>
                            <script>
                                const signatureData = {
                                    @foreach($signatures as $signature)
                                        {{ $signature->id }}: {
                                            name: '{{ addslashes($signature->name) }}',
                                            url: '{{ $signature->content && \Illuminate\Support\Facades\Storage::disk('public')->exists($signature->content) ? asset('storage/' . $signature->content) : '' }}'
                                        },
                                    @endforeach
                                };
                            </script>
                        @endif
                </div>
            </section>
            
            <!-- Totals -->
            <section class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 sm:p-6 flex flex-col justify-between">
                <div class="flex flex-col gap-4">
                    <div class="flex justify-between items-center text-sm text-gray-500">
                        <span>Subtotal</span>
                            <span class="font-medium text-gray-900"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="subtotal">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center text-sm text-gray-500">
                        <div class="flex items-center gap-2">
                            <span>Discount</span>
                                <select name="discount_type" id="discount-type" class="text-xs border border-gray-200 rounded px-2 py-1 bg-white text-gray-900">
                                    <option value="fixed" {{ old('discount_type', 'fixed') == 'fixed' ? 'selected' : '' }}>Fixed</option>
                                    <option value="percentage" {{ old('discount_type') == 'percentage' ? 'selected' : '' }}>%</option>
                                </select>
                                <input name="discount_amount" id="discount-amount" type="number" step="0.01" min="0" value="{{ old('discount_amount', '0') }}" onchange="calculateTotal()" class="w-20 text-right border border-gray-200 rounded px-2 py-1 text-sm focus:ring-1 focus:ring-primary text-gray-900">
                        </div>
                            <span class="font-medium text-gray-900"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="discount-display">0.00</span></span>
                    </div>
                    <div class="flex justify-between items-center text-sm text-gray-500">
                            <span>Tax</span>
                            <span class="font-medium text-gray-900"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="tax-amount">0.00</span></span>
                    </div>
                </div>
                <div class="mt-6 pt-6 border-t-2 border-gray-100">
                    <div class="flex justify-between items-end">
                            <span class="text-lg font-bold text-gray-900">Total (<span id="currency-code">{{ $defaultCurrency }}</span>)</span>
                            <span class="text-3xl font-black text-primary tracking-tight"><span class="currency-symbol">{{ $currencies->where('code', $defaultCurrency)->first()->symbol ?? '$' }}</span><span id="total">0.00</span></span>
                    </div>
                </div>
            </section>
        </div>
        </form>
    </div>
</div>

<!-- Sticky Footer Action Bar -->
<div id="quotation-footer" class="fixed bottom-0 left-0 right-0 p-3 sm:p-4 bg-white border-t border-gray-200 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1)] z-30 flex flex-col sm:flex-row justify-center items-center gap-3 sm:gap-3 transition-all duration-300">
    <div class="flex flex-col sm:flex-row items-center gap-3 sm:gap-3 w-full sm:w-auto justify-center">
        <a href="{{ route('admin.quotations.index') }}" onclick="return confirmCancel()" class="px-4 sm:px-6 py-2 sm:py-2.5 rounded-lg border border-gray-200 text-gray-900 font-bold text-sm hover:bg-gray-50 transition-colors text-center whitespace-nowrap">
            Cancel
        </a>
        <button type="button" id="save-draft-btn" onclick="saveAsDraft()" class="px-4 sm:px-6 py-2 sm:py-2.5 rounded-lg border border-gray-200 text-gray-900 font-bold text-sm hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap">
            <span id="save-draft-text">Save as Draft</span>
            <span id="save-draft-spinner" class="hidden">Saving...</span>
        </button>
        <button type="button" id="preview-btn" onclick="previewQuotation()" class="flex items-center gap-2 px-4 sm:px-6 py-2 sm:py-2.5 rounded-lg bg-primary/10 text-primary font-bold text-sm hover:bg-primary/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap">
            <span class="material-symbols-outlined text-[20px]">preview</span>
            <span id="preview-text">Preview</span>
            <span id="preview-spinner" class="hidden">Loading...</span>
        </button>
        <button type="button" id="create-btn" onclick="submitForm()" class="flex items-center justify-center gap-2 px-6 sm:px-8 py-2 sm:py-2.5 rounded-lg bg-primary text-white font-bold text-sm hover:bg-blue-600 transition-colors shadow-lg shadow-blue-500/30 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap">
            <span class="material-symbols-outlined text-[20px]">check</span>
            <span id="create-text">Create Quotation</span>
            <span id="create-spinner" class="hidden">Creating...</span>
        </button>
    </div>
</div>

<script>
// ========== COMPANY DROPDOWN (AJAX) ==========
const companySearch = document.getElementById('company-search');
const companyDropdown = document.getElementById('company-dropdown');
const companyLoading = document.getElementById('company-loading');
const companyIdInput = document.getElementById('company-id');
const companySearchContainer = document.getElementById('company-search-container');
const companyDisplay = document.getElementById('company-display');
const companyDisplayName = document.getElementById('company-display-name');
const companyDisplayDetails = document.getElementById('company-display-details');
const companyLogoContainer = document.getElementById('company-logo-container');

let companySearchTimeout;
let companyAbortController;

function displayCompany(company) {
    // If company doesn't have an id (from settings), we'll use a special identifier
    if (company.id) {
        companyIdInput.value = company.id;
    } else {
        // For company settings, we'll use a special value or leave it empty
        // The form will use company settings instead
        companyIdInput.value = '';
    }
    
    companySearch.value = company.name;
    companyDisplay.classList.remove('hidden');
    
    companyDisplayName.textContent = company.name;
    
    // Handle logo display - logo is already a full URL from the API
    if (company.logo) {
        // The logo field from API is already a full URL (Storage::url())
        const logoUrl = company.logo;
        const img = document.createElement('img');
        img.src = logoUrl;
        img.alt = company.name;
        img.className = 'w-full h-full object-cover rounded-lg';
        img.onerror = function() {
            companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
        };
        companyLogoContainer.innerHTML = '';
        companyLogoContainer.appendChild(img);
    } else if (company.logo_path) {
        // Fallback: if logo_path exists but logo doesn't, build the URL
        const logoUrl = '{{ asset("storage") }}/' + company.logo_path;
        const img = document.createElement('img');
        img.src = logoUrl;
        img.alt = company.name;
        img.className = 'w-full h-full object-cover rounded-lg';
        img.onerror = function() {
            companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
        };
        companyLogoContainer.innerHTML = '';
        companyLogoContainer.appendChild(img);
    } else {
        companyLogoContainer.innerHTML = '<span class="material-symbols-outlined text-gray-400">business</span>';
    }
    
    // Show key company contact details
    let detailsHTML = '';
    if (company.email) detailsHTML += `<p>${company.email}</p>`;
    if (company.phone) detailsHTML += `<p>${company.phone}</p>`;
    if (company.address) detailsHTML += `<p>${company.address}</p>`;
    
    companyDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
    companyDropdown.classList.add('hidden');
}

// Load company settings on page load
async function loadCompanySettings() {
    try {
        const response = await fetch('{{ route("admin.quotations.api.company-settings") }}', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
            credentials: 'same-origin',
        });
        const data = await response.json();
        
        if (data.success && data.company && data.company.name) {
            // Auto-populate company settings
            displayCompany(data.company);
        }
    } catch (error) {
        console.error('Error loading company settings:', error);
    }
}

function searchCompanies(searchTerm) {
    if (companyAbortController) {
        companyAbortController.abort();
    }
    companyAbortController = new AbortController();
    
    companyLoading.classList.remove('hidden');
    companyDropdown.classList.add('hidden');
    
    fetch('{{ route("admin.quotations.api.companies") }}?search=' + encodeURIComponent(searchTerm), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        credentials: 'same-origin',
        signal: companyAbortController.signal
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Request failed');
        }
        return response.json();
    })
    .then(data => {
        companyLoading.classList.add('hidden');
        
        if (data.success && data.companies && data.companies.length > 0) {
            companyDropdown.innerHTML = '';
            data.companies.forEach(company => {
                const option = document.createElement('div');
                option.className = 'company-option px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-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() {
        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');
        }
    });
}

// ========== CUSTOMER DROPDOWN (AJAX) ==========
const customerSearch = document.getElementById('customer-search');
const customerDropdown = document.getElementById('customer-dropdown');
const customerLoading = document.getElementById('customer-loading');
const customerIdInput = document.getElementById('customer-id');
const customerSearchContainer = document.getElementById('customer-search-container');
const customerDisplay = document.getElementById('customer-display');
const customerDisplayName = document.getElementById('customer-display-name');
const customerDisplayDetails = document.getElementById('customer-display-details');
const customerLogoContainer = document.getElementById('customer-logo-container');

let customerSearchTimeout;
let customerAbortController;

function displayCustomer(customer) {
    customerIdInput.value = customer.id;
    
    customerSearch.value = customer.name;
    customerDisplay.classList.remove('hidden');
    
    // Display name - use company name for customers if available, otherwise use name
    const displayName = customer.company || customer.name;
    customerDisplayName.textContent = displayName;
    
    if (customer.image) {
        const imageUrl = customer.image.startsWith('http') || customer.image.startsWith('/')
            ? customer.image
            : (customer.image_path ? '{{ asset("storage") }}/' + customer.image_path : customer.image);
        customerLogoContainer.innerHTML = `<img src="${imageUrl}" alt="${customer.name}" class="w-full h-full object-cover rounded-full" onerror="this.parentElement.innerHTML='<span class=\\'text-primary font-bold\\'>${(customer.name || 'N').charAt(0).toUpperCase()}</span>'">`;
    } else {
        const initial = (customer.name || 'N').charAt(0).toUpperCase();
        customerLogoContainer.innerHTML = `<span class="text-primary font-bold">${initial}</span>`;
    }
    
    let detailsHTML = '';
    if (customer.company) {
        detailsHTML += `<p><strong>Contact:</strong> ${customer.name}</p>`;
    }
    if (customer.email) detailsHTML += `<p><strong>Email:</strong> ${customer.email}</p>`;
    if (customer.phone) detailsHTML += `<p><strong>Phone:</strong> ${customer.phone}</p>`;
    if (customer.address) detailsHTML += `<p><strong>Address:</strong> ${customer.address}</p>`;
    if (customer.city || customer.state || customer.zip) {
        const location = [customer.city, customer.state, customer.zip].filter(Boolean).join(', ');
        if (location) detailsHTML += `<p>${location}</p>`;
    }
    if (customer.country) detailsHTML += `<p>${customer.country}</p>`;
    
    customerDisplayDetails.innerHTML = detailsHTML || '<p class="text-gray-500">No additional details</p>';
    customerDropdown.classList.add('hidden');
}

function searchCustomers(searchTerm) {
    if (customerAbortController) {
        customerAbortController.abort();
    }
    customerAbortController = new AbortController();
    
    customerLoading.classList.remove('hidden');
    customerDropdown.classList.add('hidden');
    
    fetch('{{ route("admin.quotations.api.customers") }}?search=' + encodeURIComponent(searchTerm), {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        credentials: 'same-origin',
        signal: customerAbortController.signal
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Request failed');
        }
        return response.json();
    })
    .then(data => {
        customerLoading.classList.add('hidden');
        
        if (data.success && data.customers && data.customers.length > 0) {
            customerDropdown.innerHTML = '';
            data.customers.forEach(customer => {
                const option = document.createElement('div');
                option.className = 'customer-option px-4 py-2 hover:bg-gray-50 cursor-pointer border-b border-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', () => displayCustomer(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(error => {
        if (error.name !== 'AbortError') {
            console.error('Error fetching customers:', error);
            customerLoading.classList.add('hidden');
        }
    });
}

if (customerSearch) {
    customerSearch.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        clearTimeout(customerSearchTimeout);
        customerSearchTimeout = setTimeout(() => searchCustomers(searchTerm), 300);
    });
    
    customerSearch.addEventListener('focus', function() {
        searchCustomers(this.value.trim());
    });
    
    document.addEventListener('click', function(e) {
        if (!customerSearch.contains(e.target) && !customerDropdown.contains(e.target) && !customerLoading.contains(e.target)) {
            customerDropdown.classList.add('hidden');
            customerLoading.classList.add('hidden');
        }
    });
}

let itemIndex = 1;
const currencySymbols = {};
const currencyPositions = {};

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

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

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

function addItemRow() {
    const tbody = document.getElementById('items-tbody');
    const row = tbody.insertRow();
    row.className = 'group border-b border-gray-100 hover:bg-gray-50/50 transition-colors';
    row.setAttribute('data-index', itemIndex);
    const symbol = document.querySelector('.currency-symbol').textContent;
    row.innerHTML = `
        <td class="p-4 align-top">
            <div class="flex flex-col gap-2">
                <input name="items[${itemIndex}][description]" required class="w-full border-none p-0 bg-transparent focus:ring-0 font-medium placeholder:text-gray-400" placeholder="Item name" type="text">
                <textarea name="items[${itemIndex}][notes]" class="w-full text-xs text-gray-500 border-none bg-transparent p-0 focus:ring-0 resize-none overflow-hidden" placeholder="Add description..." rows="1"></textarea>
            </div>
        </td>
        <td class="p-4 align-top">
            <select name="items[${itemIndex}][unit]" class="w-full border border-gray-200 rounded bg-transparent text-xs py-1 px-2 focus:ring-1 focus:ring-primary">
                <option value="pcs">pcs</option>
                <option value="hrs">hrs</option>
                <option value="days">days</option>
                <option value="kg">kg</option>
            </select>
        </td>
        <td class="p-4 align-top">
            <input name="items[${itemIndex}][quantity]" type="number" step="0.01" value="1" required onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
        </td>
        <td class="p-4 align-top">
            <input name="items[${itemIndex}][unit_price]" type="number" step="0.01" placeholder="0.00" value="0" required onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
        </td>
        <td class="p-4 align-top">
            <input name="items[${itemIndex}][tax_rate]" type="number" step="0.01" min="0" max="100" value="0" onchange="calculateRow(this)" class="w-full border border-gray-200 rounded bg-transparent py-1 px-2 text-right focus:ring-1 focus:ring-primary text-gray-900">
        </td>
        <td class="p-4 align-top text-right font-medium text-gray-900">
            ${symbol}<span class="item-amount">0.00</span>
        </td>
        <td class="p-4 align-top text-center">
            <button type="button" onclick="removeItemRow(this)" class="text-gray-400 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100">
                <span class="material-symbols-outlined text-[20px]">delete</span>
            </button>
        </td>
    `;
    itemIndex++;
}

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

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

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

function validateForm() {
    const form = document.getElementById('quotation-form');
    
    // Check if customer is selected
    const customerId = document.getElementById('customer-id').value;
    if (!customerId) {
        alert('Please select a customer.');
        document.getElementById('customer-search').focus();
        return false;
    }
    
    // Check if at least one item is added
    const itemRows = document.querySelectorAll('#items-tbody tr');
    if (itemRows.length === 0) {
        alert('Please add at least one item to the quotation.');
        return false;
    }
    
    // Validate each item
    let hasValidItem = false;
    itemRows.forEach(row => {
        const description = row.querySelector('input[name*="[description]"]')?.value.trim();
        const quantity = parseFloat(row.querySelector('input[name*="[quantity]"]')?.value) || 0;
        const unitPrice = parseFloat(row.querySelector('input[name*="[unit_price]"]')?.value) || 0;
        
        if (description && quantity > 0 && unitPrice > 0) {
            hasValidItem = true;
        }
    });
    
    if (!hasValidItem) {
        alert('Please add at least one valid item with description, quantity, and unit price.');
        return false;
    }
    
    // Check quotation date
    const issueDate = document.getElementById('issue-date').value;
    if (!issueDate) {
        alert('Please select a quotation date.');
        document.getElementById('issue-date').focus();
        return false;
    }
    
    return true;
}

function saveAsDraft() {
    if (!validateForm()) {
        return;
    }
    
    // Get signature ID if selected
    const signatureSelect = document.getElementById('signature-select');
    if (signatureSelect && signatureSelect.value) {
        document.getElementById('form-signature-id').value = signatureSelect.value;
    }
    
    setButtonLoading('save-draft-btn', true);
    document.getElementById('quotation-status').value = 'draft';
    updateStatusBadge('draft');
    
    // Submit the form
    const form = document.getElementById('quotation-form');
    if (form) {
        form.submit();
    } else {
        alert('Form not found. Please refresh the page and try again.');
        setButtonLoading('save-draft-btn', false);
    }
}

function submitForm() {
    if (!validateForm()) {
        return;
    }
    
    // Get signature ID if selected
    const signatureSelect = document.getElementById('signature-select');
    if (signatureSelect && signatureSelect.value) {
        document.getElementById('form-signature-id').value = signatureSelect.value;
    }
    
    setButtonLoading('create-btn', true);
    document.getElementById('quotation-status').value = 'sent';
    updateStatusBadge('sent');
    
    // Submit the form
    const form = document.getElementById('quotation-form');
    if (form) {
        form.submit();
    } else {
        alert('Form not found. Please refresh the page and try again.');
        setButtonLoading('create-btn', false);
    }
}

function previewQuotation() {
    if (!validateForm()) {
        return;
    }
    
    setButtonLoading('preview-btn', true);
    
    const form = document.getElementById('quotation-form');
    const formData = new FormData(form);
    
    const tempForm = document.createElement('form');
    tempForm.method = 'POST';
    tempForm.action = '{{ route("admin.quotations.preview") }}';
    tempForm.style.display = 'none';
    
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = '_token';
    csrfInput.value = '{{ csrf_token() }}';
    tempForm.appendChild(csrfInput);
    
    for (let [key, value] of formData.entries()) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = value;
        tempForm.appendChild(input);
    }
    
    document.body.appendChild(tempForm);
    tempForm.submit();
}

function updateStatusBadge(status) {
    const badge = document.getElementById('status-badge');
    if (badge) {
        const statusLabels = {
            'draft': 'Draft',
            'sent': 'Sent',
            'viewed': 'Viewed',
            'accepted': 'Accepted',
            'rejected': 'Rejected',
            'expired': 'Expired',
            'converted': 'Converted',
            'cancelled': 'Cancelled'
        };
        badge.textContent = statusLabels[status] || 'Draft';
    }
}

function setButtonLoading(buttonId, isLoading) {
    const button = document.getElementById(buttonId);
    if (!button) return;
    
    // Map button IDs to their text and spinner element IDs
    const elementMap = {
        'save-draft-btn': { text: 'save-draft-text', spinner: 'save-draft-spinner' },
        'preview-btn': { text: 'preview-text', spinner: 'preview-spinner' },
        'create-btn': { text: 'create-text', spinner: 'create-spinner' }
    };
    
    const elements = elementMap[buttonId];
    if (!elements) return;
    
    const textEl = document.getElementById(elements.text);
    const spinnerEl = document.getElementById(elements.spinner);
    
    if (isLoading) {
        button.disabled = true;
        if (spinnerEl) spinnerEl.classList.remove('hidden');
        if (textEl) textEl.classList.add('hidden');
    } else {
        button.disabled = false;
        if (spinnerEl) spinnerEl.classList.add('hidden');
        if (textEl) textEl.classList.remove('hidden');
    }
}

function confirmCancel() {
    // Check if form has been modified
    const form = document.getElementById('quotation-form');
    const formData = new FormData(form);
    let hasData = false;
    
    // Check if customer is selected
    if (document.getElementById('customer-id').value) {
        hasData = true;
    }
    
    // Check if any items exist
    const itemRows = document.querySelectorAll('#items-tbody tr');
    if (itemRows.length > 0) {
        hasData = true;
    }
    
    if (hasData) {
        return confirm('Are you sure you want to cancel? Any unsaved changes will be lost.');
    }
    
    return true;
}

// Accordion Toggle Function
function toggleAccordion(accordionId) {
    const accordion = document.getElementById(accordionId);
    const icon = document.getElementById(accordionId + '-icon');
    
    if (accordion && icon) {
        const isHidden = accordion.classList.contains('hidden');
        
        if (isHidden) {
            accordion.classList.remove('hidden');
            icon.style.transform = 'rotate(180deg)';
        } else {
            accordion.classList.add('hidden');
            icon.style.transform = 'rotate(0deg)';
        }
    }
}

// Document Title Management
function updateDocumentTitle(value) {
    document.getElementById('document-title').value = value;
    const titleInput = document.getElementById('quotation-title');
    if (titleInput) {
        titleInput.value = value === 'estimate' ? 'Estimate' : 'Quotation';
    }
}

// Item Type Management
let currentItemType = 'product';

function updateItemType(type) {
    currentItemType = type;
    // Reload products/services based on type
    loadProductsServices(type);
}

function loadProductsServices(type) {
    // This would typically fetch from an API endpoint
    // For now, we'll use a placeholder that can be enhanced
    const select = document.getElementById('product-service-select');
    if (!select) return;
    
    // Clear existing options except the first one
    select.innerHTML = '<option value="">Select from system</option>';
    
    // In a real implementation, you would fetch from:
    // fetch(`/admin/products?type=${type}`)
    //     .then(response => response.json())
    //     .then(data => {
    //         data.forEach(item => {
    //             const option = document.createElement('option');
    //             option.value = item.id;
    //             option.textContent = `${item.name} - ${item.price || item.selling_price}`;
    //             option.dataset.description = item.description || item.name;
    //             option.dataset.price = item.price || item.selling_price || 0;
    //             option.dataset.unit = item.unit || '';
    //             select.appendChild(option);
    //         });
    //     });
}

function addItemFromProduct(description, price, unit) {
    // Add a new row with the product/service details
    addItemRow();
    
    // Get the last added row
    const rows = document.querySelectorAll('#items-tbody tr');
    const lastRow = rows[rows.length - 1];
    
    // Fill in the details
    const descInput = lastRow.querySelector('input[name*="[description]"]');
    const priceInput = lastRow.querySelector('input[name*="[unit_price]"]');
    const unitInput = lastRow.querySelector('input[name*="[unit]"]');
    
    if (descInput) descInput.value = description;
    if (priceInput) {
        priceInput.value = price;
        priceInput.dispatchEvent(new Event('change'));
    }
    if (unitInput) unitInput.value = unit;
    
    // Calculate the row
    if (priceInput) {
        calculateRow(priceInput);
    }
}

// Initialize calculations and product/service selection
document.addEventListener('DOMContentLoaded', function() {
    // Load company settings first
    loadCompanySettings();
    
    // Handle product/service selection
    const productServiceSelect = document.getElementById('product-service-select');
    if (productServiceSelect) {
        productServiceSelect.addEventListener('change', function() {
            if (this.value) {
                const selectedOption = this.options[this.selectedIndex];
                const description = selectedOption.dataset.description || selectedOption.textContent;
                const price = selectedOption.dataset.price || '0';
                const unit = selectedOption.dataset.unit || '';
                
                // Add to items table
                addItemFromProduct(description, price, unit);
                
                // Reset selection
                this.value = '';
            }
        });
    }
    
    // Load initial products
    loadProductsServices('product');
    document.querySelectorAll('input[name*="[quantity]"], input[name*="[unit_price]"], input[name*="[tax_rate]"]').forEach(input => {
        input.addEventListener('change', function() {
            calculateRow(this);
        });
    });
    
    document.getElementById('discount-type').addEventListener('change', calculateTotal);
    document.getElementById('discount-amount').addEventListener('input', calculateTotal);
    
    // Customer search functionality
    const customerSearch = document.getElementById('customer-search');
    const customerDropdown = document.getElementById('customer-dropdown');
    const customerIdInput = document.getElementById('customer-id');
    const customerSearchContainer = document.getElementById('customer-search-container');
    const customerDisplay = document.getElementById('selected-customer-display');
    const customerOptions = document.querySelectorAll('.customer-option');
    // Force z-index and positioning on dropdown
    if (customerDropdown) {
        customerDropdown.style.setProperty('z-index', '99999', 'important');
        customerDropdown.style.setProperty('position', 'absolute', 'important');
        customerDropdown.style.setProperty('top', '100%', 'important');
        customerDropdown.style.setProperty('left', '0', 'important');
        customerDropdown.style.setProperty('right', '0', 'important');
        // Ensure parent container has proper stacking context
        const parentContainer = customerDropdown.closest('.relative');
        if (parentContainer) {
            parentContainer.style.setProperty('z-index', '10', 'important');
        }
    }
    
    if (customerSearch) {
        customerSearch.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            let hasResults = false;
            
            customerOptions.forEach(option => {
                const name = option.dataset.name.toLowerCase();
                const email = (option.dataset.email || '').toLowerCase();
                
                if (name.includes(searchTerm) || email.includes(searchTerm)) {
                    option.style.display = 'block';
                    hasResults = true;
                } else {
                    option.style.display = 'none';
                }
            });
            
            // Always show dropdown when there's input or when focused
            if (searchTerm) {
                customerDropdown.classList.remove('hidden');
            }
        });
        
        customerSearch.addEventListener('focus', function() {
            // Show dropdown when input is focused
            customerDropdown.classList.remove('hidden');
            // Show all options when focused
            customerOptions.forEach(option => {
                option.style.display = 'block';
            });
        });
        
        document.addEventListener('click', function(e) {
            if (!customerSearch.contains(e.target) && 
                !customerDropdown.contains(e.target) && 
                !customerDisplay.contains(e.target)) {
                customerDropdown.classList.add('hidden');
            }
        });
        
        customerOptions.forEach(option => {
            option.addEventListener('click', function() {
                const id = this.dataset.id;
                const name = this.dataset.name;
                const email = this.dataset.email || '';
                const phone = this.dataset.phone || '';
                const address = this.dataset.address || '';
                const taxId = this.dataset.taxId || '';
                
                customerIdInput.value = id;
                customerSearch.value = name;
                
                // Hide search, show customer display
                document.getElementById('customer-search-container').classList.add('hidden');
                const customerDisplay = document.getElementById('selected-customer-display');
                customerDisplay.classList.remove('hidden');
                
                // Update customer display
                document.getElementById('customer-name-display').textContent = name;
                document.getElementById('customer-initial').textContent = name.charAt(0).toUpperCase();
                
                if (address) {
                    document.getElementById('customer-address-display').textContent = address;
                    document.getElementById('customer-address-display').classList.remove('hidden');
                } else {
                    document.getElementById('customer-address-display').classList.add('hidden');
                }
                
                if (phone) {
                    document.getElementById('customer-phone-display').textContent = phone;
                    document.getElementById('customer-phone-display').classList.remove('hidden');
                } else {
                    document.getElementById('customer-phone-display').classList.add('hidden');
                }
                
                if (email) {
                    document.getElementById('customer-email-display').textContent = email;
                    document.getElementById('customer-email-display').classList.remove('hidden');
                } else {
                    document.getElementById('customer-email-display').classList.add('hidden');
                }
                
                if (taxId) {
                    document.getElementById('customer-tax-display').textContent = 'GST: ' + taxId;
                    document.getElementById('customer-tax-display').classList.remove('hidden');
                } else {
                    document.getElementById('customer-tax-display').classList.add('hidden');
                }
                
                customerDropdown.classList.add('hidden');
            });
        });
        
        @if(old('customer_id'))
            const oldCustomerId = {{ old('customer_id') }};
            customerOptions.forEach(option => {
                if (option.dataset.id == oldCustomerId) {
                    const name = option.dataset.name;
                    const email = option.dataset.email || '';
                    const phone = option.dataset.phone || '';
                    const address = option.dataset.address || '';
                    const taxId = option.dataset.taxId || '';
                    
                    customerIdInput.value = oldCustomerId;
                    customerSearch.value = name;
                    
                    // Hide search, show customer display
                    document.getElementById('customer-search-container').classList.add('hidden');
                    const customerDisplay = document.getElementById('selected-customer-display');
                    customerDisplay.classList.remove('hidden');
                    
                    // Update customer display
                    document.getElementById('customer-name-display').textContent = name;
                    document.getElementById('customer-initial').textContent = name.charAt(0).toUpperCase();
                    
                    if (address) {
                        document.getElementById('customer-address-display').textContent = address;
                        document.getElementById('customer-address-display').classList.remove('hidden');
                    }
                    if (phone) {
                        document.getElementById('customer-phone-display').textContent = phone;
                        document.getElementById('customer-phone-display').classList.remove('hidden');
                    }
                    if (email) {
                        document.getElementById('customer-email-display').textContent = email;
                        document.getElementById('customer-email-display').classList.remove('hidden');
                    }
                    if (taxId) {
                        document.getElementById('customer-tax-display').textContent = 'GST: ' + taxId;
                        document.getElementById('customer-tax-display').classList.remove('hidden');
                    }
                }
            });
        @endif
    }
    
    window.clearCustomer = function() {
        customerIdInput.value = '';
        customerSearch.value = '';
        
        // Show search, hide customer display
        document.getElementById('customer-search-container').classList.remove('hidden');
        document.getElementById('selected-customer-display').classList.add('hidden');
        
        // Clear customer display fields
        document.getElementById('customer-name-display').textContent = '';
        document.getElementById('customer-address-display').textContent = '';
        document.getElementById('customer-phone-display').textContent = '';
        document.getElementById('customer-email-display').textContent = '';
        document.getElementById('customer-tax-display').textContent = '';
        
        customerDropdown.classList.add('hidden');
        customerSearch.focus();
    };
    
    // Signature preview
    const signatureSelect = document.getElementById('signature-select');
    if (signatureSelect && typeof signatureData !== 'undefined') {
        signatureSelect.addEventListener('change', function() {
            const signatureId = this.value;
            const preview = document.getElementById('signature-preview');
            if (signatureId && preview && signatureData[signatureId]) {
                const signature = signatureData[signatureId];
                if (signature.url) {
                    preview.innerHTML = `<img src="${signature.url}" alt="${signature.name}" class="max-w-full max-h-32 object-contain">`;
                } else {
                    preview.innerHTML = `<p class="text-sm text-gray-500">${signature.name}</p>`;
                }
            } else if (preview) {
                preview.innerHTML = '<p class="text-sm text-gray-500">Select a signature to preview</p>';
            }
        });
        
        if (signatureSelect.value && signatureData[signatureSelect.value]) {
            const signature = signatureData[signatureSelect.value];
            const preview = document.getElementById('signature-preview');
            if (preview && signature.url) {
                preview.innerHTML = `<img src="${signature.url}" alt="${signature.name}" class="max-w-full max-h-32 object-contain">`;
            }
        }
    }
    
    calculateTotal();
    
    // Adjust footer position based on sidebar state
    function updateFooterPosition() {
        const footer = document.getElementById('quotation-footer');
        const sidebar = document.getElementById('sidebar');
        
        if (!footer || !sidebar) return;
        
        // Small delay to ensure sidebar state is updated
        setTimeout(() => {
            if (window.innerWidth >= 768) {
                // Desktop: account for sidebar width
                const isCollapsed = sidebar.classList.contains('sidebar-collapsed');
                const sidebarWidth = isCollapsed ? 64 : 256; // w-16 = 64px, w-64 = 256px
                footer.style.left = sidebarWidth + 'px';
                footer.style.right = '0';
            } else {
                // Mobile: full width (sidebar is hidden/overlay)
                footer.style.left = '0';
                footer.style.right = '0';
            }
        }, 50);
    }
    
    // Update on load
    updateFooterPosition();
    
    // Update on resize with debounce
    let resizeTimeout;
    window.addEventListener('resize', () => {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(updateFooterPosition, 100);
    });
    
    // Update when sidebar toggles (observe sidebar class changes)
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
        const sidebarObserver = new MutationObserver(() => {
            updateFooterPosition();
        });
        sidebarObserver.observe(sidebar, {
            attributes: true,
            attributeFilter: ['class']
        });
    }
});
</script>

<style>
/* Content Container Alignment - Ensure proper structure */
#main-content main {
    width: 100%;
    max-width: 100%;
    min-width: 0;
}

#main-content main > div {
    width: 100%;
    max-width: 100%;
    min-width: 0;
}

/* Ensure form sections are properly contained and aligned */
section.bg-white {
    width: 100%;
    min-width: 0;
    overflow-x: hidden;
    box-sizing: border-box;
    position: relative;
}

/* Responsive table container - proper alignment */
.overflow-x-auto {
    width: 100%;
    -webkit-overflow-scrolling: touch;
    box-sizing: border-box;
}

/* Ensure grid layouts are properly contained */
.grid {
    width: 100%;
    box-sizing: border-box;
}

/* Fix any absolute positioning issues within sections */
section.bg-white .relative {
    position: relative;
}

/* Ensure consistent spacing - remove conflicting margins */
.flex.flex-col.gap-6 {
    gap: 1.5rem;
}

.flex.flex-col.gap-6 > * {
    margin: 0;
}

/* Responsive grid adjustments */
@media (max-width: 640px) {
    .grid-cols-1.md\:grid-cols-3 {
        grid-template-columns: repeat(1, minmax(0, 1fr));
    }
    
    .grid-cols-1.lg\:grid-cols-2 {
        grid-template-columns: repeat(1, minmax(0, 1fr));
    }
}

/* Footer alignment and positioning */
#quotation-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    box-sizing: border-box;
}

#quotation-footer > div {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    gap: 0.75rem;
    width: auto;
    max-width: 100%;
}

#quotation-footer button,
#quotation-footer a {
    flex-shrink: 0;
    white-space: nowrap;
}

/* Footer responsive adjustments */
@media (max-width: 640px) {
    #quotation-footer {
        flex-direction: column;
        padding: 0.75rem;
    }
    
    #quotation-footer > div {
        width: 100%;
        flex-direction: column;
    }
    
    #quotation-footer button,
    #quotation-footer a {
        width: 100%;
        justify-content: center;
    }
}

/* Customer Dropdown Styling */
#customer-dropdown {
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.customer-option {
    min-height: 48px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.customer-option:hover {
    background-color: rgba(19, 127, 236, 0.08) !important;
}

.customer-option:active {
    background-color: rgba(19, 127, 236, 0.12) !important;
}

/* Ensure dropdown is above other elements */
#customer-dropdown {
    z-index: 99999 !important;
    position: absolute !important;
    top: 100% !important;
    left: 0 !important;
    right: 0 !important;
    margin-top: 4px !important;
}

/* Override any Tailwind z-50 class */
#customer-dropdown.z-50,
#customer-dropdown[class*="z-50"] {
    z-index: 99999 !important;
}

/* Ensure parent container has proper stacking context */
div.relative:has(#customer-search),
div[style*="z-index"]:has(#customer-search) {
    z-index: 10 !important;
    position: relative !important;
}

/* Scrollbar styling for dropdown */
#customer-dropdown::-webkit-scrollbar {
    width: 6px;
}

#customer-dropdown::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

#customer-dropdown::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 4px;
}

#customer-dropdown::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* Accordion Icon Transition */
.accordion-icon {
    transition: transform 0.3s ease;
}
</style>
@endsection