<?php
/**
 * Quote Form Template
 *
 * @package     EasyInvoice
 * @since       1.0.0
 */

// Only enqueue scripts if not loaded via AJAX
if (!wp_doing_ajax()) {
    // Enqueue CSS and JS files
    wp_enqueue_style('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/css/invoice-form.css', array(), EASY_INVOICE_VERSION);
    wp_enqueue_script('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/js/invoice-form.js', array('jquery'), EASY_INVOICE_VERSION, true);
    wp_enqueue_script('easy-invoice-builder', plugin_dir_url(__FILE__) . '../../assets/js/invoice-builder.js', array('jquery', 'easy-invoice-form'), EASY_INVOICE_VERSION, true);
    wp_enqueue_script('easy-invoice-payment', plugin_dir_url(__FILE__) . '../../assets/js/payment-manager.js', array('jquery'), EASY_INVOICE_VERSION, true);
    wp_enqueue_script('easy-quote-save', plugin_dir_url(__FILE__) . '../../assets/js/quote-save.js', array('jquery', 'easy-invoice-form', 'easy-invoice-payment'), EASY_INVOICE_VERSION, true);
}

// Trigger form initialization to allow pro version to register new elements
do_action('easy_invoice_form_init');

// Initialize payment manager with quote settings
wp_localize_script('easy-invoice-payment', 'easyInvoicePayment', array(
    'discountType' => $quote ? $quote->getDiscountType() : 'percentage',
    'discountValue' => $quote ? $quote->getDiscountValue() : 0,
    'taxRate' => $quote ? $quote->getTaxRate() : easy_invoice_get_tax_rate(),
    'calculationMethod' => $quote ? $quote->getCalculationMethod() : 'before_tax',
    'currency' => $quote ? $quote->getCurrencyCode() : 'USD',
    'currencySymbol' => $quote ? $quote->getCurrencySymbol() : '$'
));

// Get tabs from form manager and override labels for quotes
$tabs = $quote_form_manager->getTabs();

// Deduplicate tabs by ID to prevent duplicate tabs in UI
$unique_tabs = [];
foreach ($tabs as $tab) {
    $unique_tabs[$tab['id']] = $tab;
}
$tabs = array_values($unique_tabs);

// Override tab labels for quotes
foreach ($tabs as &$tab) {
    switch ($tab['id']) {
        case 'quote-tab':
            $tab['label'] = __('Quote Details', 'easy-invoice');
            break;
        case 'items-tab':
            $tab['label'] = __('Items', 'easy-invoice');
            break;
        case 'client-tab':
            $tab['label'] = __('Client', 'easy-invoice');
            break;
        case 'discounts-taxes-tab':
            $tab['label'] = __('Discounts & Taxes', 'easy-invoice');
            break;
        case 'payments-tab':
            $tab['label'] = __('Payments', 'easy-invoice');
            break;
    }
}
unset($tab);

$templates = $quote_form_manager->getTemplates();

// Use the actual templates from the quote form manager
$all_templates = $templates;



// Load client data directly in PHP if quote has a client
$client_data = null;
if ($quote && $quote->getClientId()) {
    $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
    if ($client) {
        $client_data = array(
            'name' => $client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()),
            'email' => $client->getEmail() ?: '',
            'phone' => $client->getExtraInfo() ?: '',
            'company' => $client->getBusinessClientName() ?: '',
            'address' => $client->getAddress() ?: '',
            'website' => $client->getWebsite() ?: '',
        );
    }
}
?>

<style>
/* Quote Item Collapse/Expand Styling - Exact copy of invoice styling */
.quote-item.collapsed-item {
    padding: 8px !important;
    margin-bottom: 8px !important;
    border: 1px solid #e5e7eb !important;
    border-radius: 0.375rem;
    background-color: #f9fafb;
    transition: all 0.2s ease;
}

.quote-item.collapsed-item .flex.items-center.justify-between {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
    border-bottom: none !important;
}

.quote-item.collapsed-item .item-collapsed-summary {
    display: inline-flex !important;
    align-items: center;
    font-size: 0.875rem;
    color: #6b7280;
}

.quote-item .item-content {
    transition: all 0.3s ease-in-out;
}

.quote-item.collapsed-item .item-content {
    display: none;
}

/* Additional styling for quote items to match invoice behavior */
.quote-item .item-collapsed-summary {
    display: none;
    background-color: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 9999px;
    padding: 0.25rem 0.75rem;
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
}

.quote-item.collapsed-item .item-collapsed-summary {
    display: inline-flex !important;
}

.quote-item .fill-sample-data-btn {
    transition: opacity 0.2s ease-in-out;
}

.quote-item.collapsed-item .fill-sample-data-btn {
    opacity: 0;
    pointer-events: none;
}

/* Smooth transitions for collapse/expand */
.quote-item .item-collapse-toggle {
    transition: all 0.2s ease-in-out;
}

.quote-item .item-collapse-toggle:hover {
    color: #4f46e5 !important;
    transform: scale(1.1);
}

/* Premium Template Styling */
.premium-template-blurred {
    position: relative;
    opacity: 0.8;
    transition: all 0.4s ease;
    cursor: pointer;
    border: 2px solid #e5e7eb;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    transform: scale(0.98);
}

.premium-template-blurred::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
    border-radius: 0.5rem;
    z-index: 1;
    pointer-events: none;
}

.premium-template-blurred::after {
    content: 'PRO';
    position: absolute;
    top: 8px;
    right: 8px;
    background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
    color: white;
    font-size: 10px;
    font-weight: 700;
    padding: 2px 6px;
    border-radius: 4px;
    z-index: 2;
    box-shadow: 0 2px 4px rgba(139, 92, 246, 0.3);
    letter-spacing: 0.5px;
}

.premium-template-blurred:hover {
    opacity: 0.95;
    transform: scale(1.02);
    border-color: #8b5cf6;
    box-shadow: 0 8px 25px rgba(139, 92, 246, 0.15);
}

.premium-template-blurred:hover::after {
    background: linear-gradient(135deg, #7c3aed 0%, #9333ea 100%);
    box-shadow: 0 4px 8px rgba(139, 92, 246, 0.4);
}

.premium-template-blurred .template-radio {
    pointer-events: none;
}

.premium-template-blurred > div {
    position: relative;
    z-index: 3;
}
</style>

<?php if (wp_doing_ajax()): ?>
<form id="quote-form" method="post">
    <input type="hidden" id="quote-id" name="quote_id" value="<?php echo $quote_id ? esc_attr($quote_id) : ''; ?>">
<?php endif; ?>

<div class="bg-white shadow rounded-lg">
    <!-- Tab Navigation -->
    <div class="border-b border-gray-200">
        <nav class="flex -mb-px" aria-label="<?php esc_attr_e( 'Quote form sections', 'easy-invoice' ); ?>">
            <?php foreach ($tabs as $tab): ?>
                <button type="button" 
                        class="tab-button whitespace-nowrap py-3 px-6 border-b-2 <?php echo $tab['active'] ? 'border-indigo-500 text-sm text-indigo-600' : 'border-transparent font-medium text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300'; ?> flex flex-col items-center" 
                        data-tab="<?php echo esc_attr($tab['id']); ?>">
                    <i class="<?php echo esc_attr($tab['icon']); ?> mb-1 text-lg"></i>
                    <span><?php echo esc_html($tab['label']); ?></span>
                </button>
            <?php endforeach; ?>
        </nav>
    </div>
    
    <!-- Form content starts here (form tag removed to avoid nesting) -->
    
    <?php foreach ($tabs as $tab): ?>
        <div class="tab-content <?php echo $tab['active'] ? 'active' : 'hidden'; ?> px-6 py-5" id="<?php echo esc_attr($tab['id']); ?>">
            <?php if ($tab['id'] === 'quote-tab'): ?>
                <!-- Template Selection Section -->
                <div class="mb-8 pb-6 border-b border-gray-200">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-gray-900"><?php _e('Quote Template', 'easy-invoice'); ?></h3>
                        <button type="button" id="browse-all-templates" class="text-sm text-indigo-600 hover:text-indigo-800 flex items-center">
                            <span class="mr-1"><?php _e('Browse Quote Templates', 'easy-invoice'); ?></span>
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                    
                    <?php
                    // Get the current template (default to 'standard')
                    $current_template = $quote ? $quote->getTemplate() : 'standard';
                    
                    if (empty($current_template)) {
                        $current_template = 'standard';
                    }
                    
                    // Always include the hidden input for the template field
                    ?>
                    <input type="hidden" name="quote_template" value="<?php echo esc_attr($current_template); ?>">
                    <?php
                    
                    // Check if this is the free version
                    $is_free_version = !easy_invoice_has_pro();
                    
                    
                    
                    // Show all templates grid
                    ?>
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-4" id="main-templates-grid">
                        <?php
                        // Build the main grid templates array - always include current template plus 2 others
                        $main_grid_templates = [];
                        
                        // First, add the current template if it exists in all_templates
                        if (isset($all_templates[$current_template])) {
                            // For free users, if current template is premium, default to standard
                            if ($is_free_version && isset($all_templates[$current_template]['is_free']) && !$all_templates[$current_template]['is_free']) {
                                $current_template = 'standard';
                                $main_grid_templates['standard'] = $all_templates['standard'];
                            } else {
                                $main_grid_templates[$current_template] = $all_templates[$current_template];
                            }
                        }
                        
                        // Add other templates to fill up to 3, prioritizing standard templates
                        $default_templates = ['standard', 'legacy', 'modern'];
                        foreach ($default_templates as $template_id) {
                            if (count($main_grid_templates) >= 3) break;
                            if ($template_id !== $current_template && isset($all_templates[$template_id])) {
                                $main_grid_templates[$template_id] = $all_templates[$template_id];
                            }
                        }
                        
                        // If we still don't have 3 templates, add any remaining templates
                        foreach ($all_templates as $template_id => $template) {
                            if (count($main_grid_templates) >= 3) break;
                            if (!isset($main_grid_templates[$template_id])) {
                                $main_grid_templates[$template_id] = $template;
                            }
                        }
                        
                        // Display the main grid templates
                        foreach ($main_grid_templates as $template_id => $template) :
                            $checked = ($current_template === $template_id) ? 'checked' : '';
                            $selected_class = ($current_template === $template_id) ? 'selected' : '';
                            
                            // Check if this template is premium (not free)
                            $is_premium = isset($template['is_free']) && !$template['is_free'];
                            
                            // Add premium overlay classes
                            $premium_classes = '';
                            if ($is_free_version && $is_premium) {
                                $premium_classes = 'premium-template-blurred';
                            }
                        ?>
                            <div class="template-card <?php echo $selected_class . ' ' . $premium_classes; ?>" data-template-id="<?php echo esc_attr($template_id); ?>" data-is-premium="<?php echo $is_premium ? 'true' : 'false'; ?>">
                                <input type="radio" id="template-<?php echo esc_attr($template_id); ?>" name="quote_template" value="<?php echo esc_attr($template_id); ?>" class="template-radio" <?php echo $checked; ?> <?php echo ($is_free_version && $is_premium) ? 'disabled' : ''; ?>>
                                <div class="p-4 border rounded-lg">
                                    <div class="flex items-center mb-2">
                                        <i class="<?php echo esc_attr($template['icon']); ?> text-indigo-600 mr-2"></i>
                                        <span class="text-sm font-medium"><?php echo esc_html($template['name']); ?></span>
                                    </div>
                                    <p class="text-sm text-gray-600"><?php echo esc_html($template['description']); ?></p>
                                    <div class="mt-2 flex-grow">
                                        <div class="template-preview bg-gray-100 rounded h-16 flex items-center justify-center <?php echo esc_attr($template_id); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            
                <!-- Dynamic Fields Section -->
                <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                    <?php 
                    $main_fields = $quote_form_manager->getFields('quote-tab');
                    
                    
                    
                    foreach ($main_fields as $field): 
                        // Skip fields that have a section (like notes) - they're rendered separately
                        // Also skip the template field as it's rendered manually in the template selection section
                        if (!isset($field['section']) && $field['name'] !== 'quote_template') {
                            
                            echo $quote_form_manager->renderField($field, $quote);
                        }
                    endforeach; 
                    ?>
                </div>
                
                <!-- Auto-generation notice for new quotes -->
                <?php if (!$quote): ?>
                <div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-blue-400"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-blue-700">
                                <?php _e('Quote number will be automatically generated when you save the quote.', 'easy-invoice'); ?>
                            </p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Notes & Terms Section -->
                <div class="mt-8 border-t border-gray-200 pt-6">
                    <h3 class="text-lg font-medium text-gray-900"><?php _e('Notes & Terms', 'easy-invoice'); ?></h3>
                    <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:col-span-6">
                        <?php 
                        // Only render notes and terms fields, not all quote tab fields
                        $notes_fields = $quote_form_manager->getFieldsBySection('quote-tab', 'notes');
                        foreach ($notes_fields as $field): 
                            echo $quote_form_manager->renderField($field, $quote);
                        endforeach; 
                        ?>
                    </div>
                </div>
                
            <?php elseif ($tab['id'] === 'items-tab'): ?>
                <!-- Items Tab Content -->
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-lg font-medium text-gray-900"><?php _e('Quote Items', 'easy-invoice'); ?></h2>
                    <button type="button" id="collapse-all-items" class="text-sm text-indigo-600 hover:text-indigo-800 flex items-center">
                        <i class="fas fa-chevron-down mr-1"></i>
                        <span><?php _e('Collapse All', 'easy-invoice'); ?></span>
                    </button>
                </div>

                <div class="space-y-4 quote-items-container">
                    <?php 
                    // If editing an existing quote, directly output quote items
                    if ($quote && $quote->getItems()) :
                        $index = 0;
                        foreach ($quote->getItems() as $item) :
                            // Generate a unique ID for the item
                            $item_id = 'item_' . time() . '_' . $index . '_' . rand(1000, 9999);
                            
                            // Get display title for header using dynamic field access
                            $title = $item->getName();
                            
            
                            if (empty($title) && method_exists($item, 'getData')) {
                                $item_data = $item->getData();
                                if (is_array($item_data) && isset($item_data['title'])) {
                                    $title = $item_data['title'];
                                }
                            }
                            
                            $display_title = !empty($title) ? $title : sprintf(__('Item #%d', 'easy-invoice'), $index + 1);
                            $short_title = strlen($display_title) > 30 ? substr($display_title, 0, 30) . '...' : $display_title;
                            ?>
                            <div class="quote-item p-6 rounded-xl shadow-sm border border-blue-100 hover:shadow-md transition-all duration-200 mb-6" style="background-color: #f8fbff;" id="<?php echo $item_id; ?>">
                                <div class="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
                                    <div class="flex items-center">
                                        <button type="button" class="item-collapse-toggle mr-3 text-gray-400 hover:text-indigo-600 focus:outline-none transition-colors">
                                            <i class="fas fa-chevron-down text-sm"></i>
                                        </button>
                                        <h3 class="text-base font-normal text-gray-800 flex-1">
                                            <?php
                                            echo !empty($title) ? esc_html($title) : __('New Item', 'easy-invoice');
                                            ?>
                                        </h3>
                                    </div>
                                    <div class="flex items-center gap-3">
                                        <div class="item-collapsed-summary hidden text-sm text-gray-600 bg-gray-50 px-3 py-1 rounded-full">
                                            <span class="quantity-summary"><?php echo esc_html($item->getQuantity()); ?></span> × $<span class="price-summary"><?php echo esc_html(number_format(floatval($item->getPrice()), 2)); ?></span>
                                            = $<span class="total-summary font-medium"><?php echo esc_html(number_format($item->getAmount(), 2)); ?></span>
                                        </div>
                                        <button type="button" class="fill-sample-data-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Fill this item with sample data', 'easy-invoice'); ?>">
                                            <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                                <path d="M2 2a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H2zm0 1h16v14H2V3z"/>
                                                <path d="M4 5h12v1.5H4V5zm0 3h10v1.5H4V8zm0 3h11v1.5H4V11zm0 3h8v1.5H4V14z"/>
                                                <path d="M14 14l3 3-3 3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
                                                <path d="M14 17h3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/>
                                            </svg>
                                        </button>
                                        <?php if (class_exists('EasyInvoicePro\\Services\\ItemLibraryService')): ?>
                                        <button type="button" class="item-library-btn text-gray-400 hover:text-blue-600 p-2 rounded-lg hover:bg-blue-50 transition-all duration-200" data-tooltip="<?php _e('Select from Item Library', 'easy-invoice'); ?>">
                                            <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                                <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z"/>
                                            </svg>
                                        </button>
                                        <button type="button" class="save-to-library-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Save to Item Library', 'easy-invoice'); ?>" data-item-index="<?php echo $index; ?>" data-nonce="<?php echo wp_create_nonce('easy_invoice_pro_item_library'); ?>">
                                            <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                                <path d="M7.707 10.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V6h5a2 2 0 012 2v7a2 2 0 01-2 2H4a2 2 0 01-2-2V8a2 2 0 012-2h5v5.586l-1.293-1.293zM9 4a1 1 0 012 0v2H9V4z"/>
                                            </svg>
                                        </button>
                                        <?php endif; ?>
                                        <button type="button" class="remove-item text-gray-400 hover:text-red-600 hover:bg-red-50 p-2 rounded-lg transition-all duration-200 text-sm font-medium">
                                            <i class="fas fa-trash-alt mr-1"></i> <?php _e('Remove', 'easy-invoice'); ?>
                                        </button>
                                    </div>
                                </div>
                                <div class="item-content">
                                    <?php echo $quote_form_manager->generateExistingItemHtml($item, $index); ?>
                                </div>
                            </div>
                            <?php
                            $index++;
                        endforeach;
                    else:
                        // For new quotes, render one empty item by default
                        $index = 0;
                        // Get the item fields config
                        $item_fields = $quote_form_manager->getItemFields();
                        $title_placeholder = '';
                        foreach ($item_fields as $field) {
                            if ($field['name'] === 'title') {
                                $title_placeholder = $field['placeholder'] ?? __('Item', 'easy-invoice');
                                break;
                            }
                        }
                        // Try to get the value from POST (if form was submitted and errored)
                        $item_title = isset($_POST['items'][0]['title']) ? trim($_POST['items'][0]['title']) : '';
                        ?>
                        <div class="quote-item p-6 rounded-xl shadow-sm border border-blue-100 hover:shadow-md transition-all duration-200 mb-6" style="background-color: #f8fbff;">
                            <div class="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
                                <div class="flex items-center">
                                    <button type="button" class="item-collapse-toggle mr-3 text-gray-400 hover:text-indigo-600 focus:outline-none transition-colors">
                                        <i class="fas fa-chevron-down text-sm"></i>
                                    </button>
                                    <h3 class="text-base font-normal text-gray-800 flex-1">
                                        <?php
                                        echo !empty($item_title) ? esc_html($item_title) : esc_html($title_placeholder);
                                        ?>
                                    </h3>
                                </div>
                                <div class="flex items-center gap-3">
                                    <div class="item-collapsed-summary hidden text-sm text-gray-600 bg-gray-50 px-3 py-1 rounded-full">
                                        <span class="quantity-summary">0</span> × $<span class="price-summary">0.00</span>
                                        = $<span class="total-summary font-medium">0.00</span>
                                    </div>
                                    <button type="button" class="fill-sample-data-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Fill this item with sample data', 'easy-invoice'); ?>">
                                        <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                            <path d="M2 2a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H2zm0 1h16v14H2V3z"/>
                                            <path d="M4 5h12v1.5H4V5zm0 3h10v1.5H4V8zm0 3h11v1.5H4V11zm0 3h8v1.5H4V14z"/>
                                            <path d="M14 14l3 3-3 3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M14 17h3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/>
                                        </svg>
                                    </button>
                                    <?php if (class_exists('EasyInvoicePro\\Services\\ItemLibraryService')): ?>
                                    <button type="button" class="item-library-btn text-gray-400 hover:text-blue-600 p-2 rounded-lg hover:bg-blue-50 transition-all duration-200" data-tooltip="<?php _e('Select from Item Library', 'easy-invoice'); ?>">
                                        <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                            <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z"/>
                                        </svg>
                                    </button>
                                    <button type="button" class="save-to-library-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Save to Item Library', 'easy-invoice'); ?>" data-item-index="0" data-nonce="<?php echo wp_create_nonce('easy_invoice_pro_item_library'); ?>">
                                        <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                                            <path d="M7.707 10.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V6h5a2 2 0 012 2v7a2 2 0 01-2 2H4a2 2 0 01-2-2V8a2 2 0 012-2h5v5.586l-1.293-1.293zM9 4a1 1 0 012 0v2H9V4z"/>
                                        </svg>
                                    </button>
                                    <?php endif; ?>
                                    <button type="button" class="remove-item text-gray-400 hover:text-red-600 hover:bg-red-50 p-2 rounded-lg transition-all duration-200 text-sm font-medium">
                                        <i class="fas fa-trash-alt mr-1"></i> <?php _e('Remove', 'easy-invoice'); ?>
                                    </button>
                                </div>
                            </div>
                            <div class="item-content">
                                <?php echo $quote_form_manager->generateItemTemplateHtml(); ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
                 
                <div class="mt-6">
                    <button type="button" class="add-item-button w-full flex justify-center items-center px-6 py-4 bg-white border border-blue-100 rounded-xl text-indigo-700 hover:bg-blue-50 hover:border-blue-200 hover:shadow-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 group">
                        <div class="flex items-center">
                            <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center mr-3 group-hover:bg-indigo-200 transition-colors">
                                <i class="fas fa-plus text-indigo-600 text-lg"></i>
                            </div>
                            <div class="text-left">
                                <span class="font-semibold text-base"><?php _e('Add Another Item', 'easy-invoice'); ?></span>
                                <p class="text-sm text-indigo-600 mt-0.5"><?php _e('Click to add a new line item', 'easy-invoice'); ?></p>
                            </div>
                        </div>
                    </button>
                </div>
                
            <?php elseif ($tab['id'] === 'client-tab'): ?>
                <!-- Client Tab Content -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-3"><?php _e('Select Existing Client', 'easy-invoice'); ?></label>
                    
                    <!-- Client Search and Selection -->
                    <div class="relative">
                        <div class="flex items-center space-x-3">
                            <div class="relative flex-grow">
                                <div class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                                    <i class="fas fa-search text-gray-400"></i>
                                </div>
                                <input 
                                    type="text" 
                                    id="client-search-input" 
                                    class="block w-full rounded-md border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm py-2 px-3 pl-10"
                                    placeholder="<?php _e('Search clients by name, email, or company...', 'easy-invoice'); ?>"
                                    autocomplete="off"
                                >
                            </div>
                            <button type="button" id="add-new-client-btn" class="inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                                <i class="fas fa-plus -ml-1 mr-2"></i>
                                <?php _e('New Client', 'easy-invoice'); ?>
                            </button>
                        </div>
                        
                        <!-- Search Results Dropdown -->
                        <div id="client-search-results" class="hidden absolute z-50 w-full mt-2 bg-white border border-gray-200 rounded-lg shadow-xl max-h-80 overflow-y-auto">
                            <div id="client-search-loading" class="hidden p-6 text-center text-gray-500">
                                <i class="fas fa-spinner fa-spin mr-2"></i>
                                <?php _e('Searching...', 'easy-invoice'); ?>
                            </div>
                            <div id="client-search-empty" class="hidden p-6 text-center text-gray-500">
                                <i class="fas fa-search mr-2"></i>
                                <?php _e('No clients found', 'easy-invoice'); ?>
                            </div>
                            <div id="client-search-list" class="py-2">
                                <!-- Client options will be populated here -->
                            </div>
                        </div>
                        
                        <!-- Selected Client Display -->
                        <div id="selected-client-display" class="mt-4 p-4 bg-gradient-to-r from-indigo-50 to-blue-50 border border-indigo-200 rounded-lg shadow-sm <?php echo ($quote && $quote->getClientId()) ? '' : 'hidden'; ?>">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0">
                                        <div class="w-10 h-10 bg-gradient-to-br from-indigo-500 to-indigo-600 rounded-full flex items-center justify-center shadow-sm">
                                            <i class="fas fa-user text-white text-sm"></i>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <p id="selected-client-name" class="text-sm font-semibold text-gray-900">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()));
                                                } else {
                                                    echo '-';
                                                }
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </p>
                                        <p id="selected-client-email" class="text-sm text-gray-600">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getEmail() ?: '-');
                                                } else {
                                                    echo '-';
                                                }
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                                <button type="button" id="clear-client-selection" class="text-gray-400 hover:text-gray-600 transition-colors p-2 rounded-full hover:bg-white hover:shadow-sm">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Hidden select for form submission -->
                    <select id="select-client" class="hidden">
                        <option value=""><?php _e('-- Select a client --', 'easy-invoice'); ?></option>
                        <?php 
                        // Output client options
                        if (!empty($clients)) {
                            foreach ($clients as $client) {
                                // Get the WordPress user data directly
                                $user = get_user_by('id', $client->getId());
                                if (!$user) {
                                    continue;
                                }
                                
                                // Use standard WordPress user fields
                                $business_name = $client->business_client_name ?: '';
                                $first_name = $user->first_name ?: '';
                                $last_name = $user->last_name ?: '';
                                $client_email = $user->user_email ?: '';
                                
                                // Create display name
                                $client_name = $business_name ?: ($first_name . ' ' . $last_name);
                                if (empty(trim($client_name))) {
                                    $client_name = $user->display_name ?: 'User ' . $client->getId();
                                }
                                
                                $selected = $quote && $quote->getClientId() == $client->getId() ? 'selected' : '';
                                printf(
                                    '<option value="%s" %s data-name="%s" data-email="%s">%s (%s)</option>',
                                    esc_attr($client->getId()),
                                    $selected,
                                    esc_attr($client_name),
                                    esc_attr($client_email),
                                    esc_html($client_name),
                                    esc_html($client_email)
                                );
                            }
                        }
                        ?>
                    </select>
                </div>

                <div class="border-t border-gray-200 pt-4 mt-4">
                    <input type="hidden" name="client_id" id="client-id" value="<?php echo $quote ? esc_attr($quote->getClientId()) : ''; ?>">
                    
                    <!-- Client Information Display -->
                    <div id="client-info-display" class="mt-6 <?php echo $quote && $quote->getClientId() ? '' : 'hidden'; ?>">
                        <div class="bg-white p-6 rounded-xl border border-gray-200 shadow-sm">
                            <div class="flex items-center justify-between pb-4 border-b border-gray-200 mb-4">
                                <h4 class="text-lg font-semibold text-gray-800 flex items-center">
                                    <i class="fas fa-user-check text-indigo-500 mr-3"></i>
                                    <span><?php _e('Client Information', 'easy-invoice'); ?></span>
                                </h4>
                                <a href="<?php echo admin_url('admin.php?page=easy-invoice-client-edit&client_id=' . ($quote && $quote->getClientId() ? $quote->getClientId() : '')); ?>" 
                                   id="edit-selected-client" 
                                   class="text-sm text-indigo-600 hover:text-indigo-800 font-medium"
                                   target="_blank">
                                    <i class="fas fa-pen mr-1"></i>
                                    <?php _e('Edit', 'easy-invoice'); ?>
                                </a>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 pt-2">
                                <!-- Client Name -->
                                <div class="flex items-start group">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-user-tie text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Name', 'easy-invoice'); ?></label>
                                        <p id="display-client-name" class="text-sm font-semibold text-gray-800 mt-1">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()));
                                                } else {
                                                    echo '-';
                                                }
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                                
                                <!-- Company Name -->
                                <div class="flex items-start group">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-building text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Company', 'easy-invoice'); ?></label>
                                        <p id="display-client-company" class="text-sm font-semibold text-gray-800 mt-1">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getBusinessClientName() ?: '-');
                                                } else {
                                                    echo '-';
                                                }
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                                
                                <!-- Email -->
                                <div class="flex items-start group">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-envelope text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Email', 'easy-invoice'); ?></label>
                                        <p id="display-client-email" class="text-sm text-gray-800 mt-1 break-all">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getEmail() ?: '-');
                                                } else {
                                                    echo '-';
                                                }
                                            } else {
                                                echo '-';
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>

                                <!-- Phone -->
                                <div class="flex items-start group">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-phone-alt text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Phone', 'easy-invoice'); ?></label>
                                        <p id="display-client-phone" class="text-sm text-gray-800 mt-1">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getExtraInfo() ?: esc_html__('—', 'easy-invoice'));
                                                } else {
                                                    echo esc_html__('—', 'easy-invoice');
                                                }
                                            } else {
                                                echo esc_html__('—', 'easy-invoice');
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                                
                                <!-- Website -->
                                <div class="flex items-start group md:col-span-2">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-globe-americas text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Website', 'easy-invoice'); ?></label>
                                        <p id="display-client-website" class="text-sm text-gray-800 mt-1">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getWebsite() ?: esc_html__('—', 'easy-invoice'));
                                                } else {
                                                    echo esc_html__('—', 'easy-invoice');
                                                }
                                            } else {
                                                echo esc_html__('—', 'easy-invoice');
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                                
                                <!-- Address -->
                                <div class="flex items-start group md:col-span-2">
                                    <div class="flex-shrink-0 w-8 text-center pt-1"><i class="fas fa-map-marker-alt text-gray-400 group-hover:text-indigo-500 transition-colors"></i></div>
                                    <div class="ml-3">
                                        <label class="block text-xs font-medium text-gray-500 uppercase tracking-wider"><?php _e('Address', 'easy-invoice'); ?></label>
                                        <p id="display-client-address" class="text-sm text-gray-800 mt-1 whitespace-pre-wrap">
                                            <?php 
                                            if ($quote && $quote->getClientId()) {
                                                $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($quote->getClientId());
                                                if ($client) {
                                                    echo esc_html($client->getAddress() ?: esc_html__('—', 'easy-invoice'));
                                                } else {
                                                    echo esc_html__('—', 'easy-invoice');
                                                }
                                            } else {
                                                echo esc_html__('—', 'easy-invoice');
                                            }
                                            ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- No Client Selected Message -->
                    <div id="no-client-message" class="mt-4 text-center py-6 border-2 border-dashed border-gray-300 rounded-lg <?php echo $quote && $quote->getClientId() ? 'hidden' : ''; ?>">
                        <p class="text-gray-600"><?php _e('Select a client from the dropdown above to view their information.', 'easy-invoice'); ?></p>
                    </div>
                </div>
                
            <?php elseif ($tab['id'] === 'discounts-taxes-tab'): ?>
                <!-- Discount & Tax Tab Content -->
                <div>
                    <h3 class="text-lg font-medium text-gray-900"><?php _e('Discount & Tax Settings', 'easy-invoice'); ?></h3>
                    
                    <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <?php 
                        // Get all discount and tax fields
                        $discount_fields = $quote_form_manager->getFieldsBySection('discounts-taxes-tab', 'discount');
                        $tax_fields = $quote_form_manager->getFieldsBySection('discounts-taxes-tab', 'tax');
                        $additional_tax_fields = $quote_form_manager->getFieldsBySection('discounts-taxes-tab', 'additional_tax');
                        
                        // Combine and sort by order
                        $all_fields = array_merge($discount_fields, $tax_fields, $additional_tax_fields);
                        usort($all_fields, function($a, $b) {
                            return ($a['order'] ?? 0) - ($b['order'] ?? 0);
                        });
                        
                        foreach ($all_fields as $field): 
                            echo $quote_form_manager->renderField($field, $quote);
                        endforeach; 
                        ?>
                    </div>
                </div>
                
            <?php elseif ($tab['id'] === 'payments-tab'): ?>
                <!-- Payment Tab Content -->
                <div>
                    <h3 class="text-lg font-medium text-gray-900"><?php _e('Payment Information', 'easy-invoice'); ?></h3>
                    <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <?php 
                        $payment_fields = $quote_form_manager->getFieldsBySection('payments-tab', 'payment');
                        foreach ($payment_fields as $field): 
                            echo $quote_form_manager->renderField($field, $quote);
                        endforeach; 
                        ?>
                    </div>
                    
                    <!-- Currency Section -->
                    <div class="mt-8 border-t border-gray-200 pt-6">
                        <h3 class="text-lg font-medium text-gray-900"><?php _e('Currency', 'easy-invoice'); ?></h3>
                        <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                            <?php 
                            $currency_fields = $quote_form_manager->getFieldsBySection('payments-tab', 'currency');
                            foreach ($currency_fields as $field): 
                                echo $quote_form_manager->renderField($field, $quote);
                            endforeach; 
                            ?>
                        </div>
                    </div>
                </div>
                
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</div>

<!-- Template Gallery Modal -->
<div id="template-gallery-modal" style="display: none;" class="fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50 flex items-center justify-center">
    <div class="mx-auto p-6 border w-full md:w-4/5 max-w-4xl shadow-lg rounded-md bg-white max-h-[80vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-medium text-gray-900"><?php _e('Browse Quote Templates', 'easy-invoice'); ?></h3>
            <button type="button" class="close-gallery-modal text-gray-400 hover:text-gray-500 focus:outline-none">
                <span class="sr-only"><?php _e('Close', 'easy-invoice'); ?></span>
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <div class="templates-grid grid grid-cols-2 md:grid-cols-3 gap-4 mb-4 max-h-[45vh] overflow-y-auto p-2">
            <?php
            // Display all template options in the modal
            foreach ($all_templates as $template_id => $template) :
                $is_current = ($current_template === $template_id);
                $selected_class = $is_current ? 'selected' : '';
            ?>
                <div class="gallery-template-card <?php echo $selected_class; ?>" data-template-id="<?php echo esc_attr($template_id); ?>" data-is-premium="<?php echo isset($template['is_free']) && !$template['is_free'] ? 'true' : 'false'; ?>">
                    <div class="p-4 border rounded-lg">
                        <div class="flex items-center mb-2">
                            <i class="<?php echo esc_attr($template['icon']); ?> text-indigo-600 mr-2"></i>
                            <span class="text-sm font-medium"><?php echo esc_html($template['name']); ?></span>
                        </div>
                        <p class="text-sm text-gray-600"><?php echo esc_html($template['description']); ?></p>
                        <div class="mt-2 flex-grow">
                            <div class="template-preview bg-gray-100 rounded h-16 flex items-center justify-center <?php echo esc_attr($template_id); ?>">
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="flex justify-end mt-4 space-x-3">
            <button type="button" id="apply-selected-template" class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <?php _e('Apply', 'easy-invoice'); ?>
            </button>
            <button type="button" class="gallery-close-btn inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <?php _e('Close', 'easy-invoice'); ?>
            </button>
        </div>
    </div>
</div>

<!-- Hidden Template for Quote Items -->
<template id="quote-item-template" style="display: none;">
    <div class="quote-item p-6 rounded-xl shadow-sm border border-blue-100 hover:shadow-md transition-all duration-200 mb-6" style="background-color: #f8fbff;">
        <div class="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
            <div class="flex items-center">
                <button type="button" class="item-collapse-toggle mr-3 text-gray-400 hover:text-indigo-600 focus:outline-none transition-colors">
                    <i class="fas fa-chevron-down text-sm"></i>
                </button>
                <h3 class="text-base font-normal text-gray-800 flex-1">
                    <?php _e('New Item', 'easy-invoice'); ?>
                </h3>
            </div>
            <div class="flex items-center gap-3">
                <div class="item-collapsed-summary hidden text-sm text-gray-600 bg-gray-50 px-3 py-1 rounded-full">
                    <span class="quantity-summary">0</span> × $<span class="price-summary">0.00</span>
                    = $<span class="total-summary">0.00</span>
                </div>
                <button type="button" class="fill-sample-data-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Fill this item with sample data', 'easy-invoice'); ?>">
                    <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                        <path d="M2 2a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H2zm0 1h16v14H2V3z"/>
                        <path d="M4 5h12v1.5H4V5zm0 3h10v1.5H4V8zm0 3h11v1.5H4V11zm0 3h8v1.5H4V14z"/>
                        <path d="M14 14l3 3-3 3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M14 17h3" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"/>
                    </svg>
                </button>
                <?php if (class_exists('EasyInvoicePro\\Services\\ItemLibraryService')): ?>
                <button type="button" class="item-library-btn text-gray-400 hover:text-blue-600 p-2 rounded-lg hover:bg-blue-50 transition-all duration-200" data-tooltip="<?php _e('Select from Item Library', 'easy-invoice'); ?>">
                    <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                        <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z"/>
                    </svg>
                </button>
                <button type="button" class="save-to-library-btn text-gray-400 hover:text-green-600 p-2 rounded-lg hover:bg-green-50 transition-all duration-200" data-tooltip="<?php _e('Save to Item Library', 'easy-invoice'); ?>" data-item-index="" data-nonce="<?php echo wp_create_nonce('easy_invoice_pro_item_library'); ?>">
                    <svg width="18" height="18" viewBox="0 0 20 20" fill="currentColor" class="inline-block">
                        <path d="M7.707 10.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V6h5a2 2 0 012 2v7a2 2 0 01-2 2H4a2 2 0 01-2-2V8a2 2 0 012-2h5v5.586l-1.293-1.293zM9 4a1 1 0 012 0v2H9V4z"/>
                    </svg>
                </button>
                <?php endif; ?>
                <button type="button" class="remove-item text-gray-400 hover:text-red-600 hover:bg-red-50 p-2 rounded-lg transition-all duration-200 text-sm font-medium">
                    <i class="fas fa-trash-alt mr-1"></i> <?php _e('Remove', 'easy-invoice'); ?>
                </button>
            </div>
        </div>
        <div class="item-content">
            <?php echo $quote_form_manager->generateItemTemplateHtml(); ?>
        </div>
    </div>
</template>

<script>
// Set Pro detection early
window.easyInvoice = window.easyInvoice || {};
window.easyInvoice.isPro = <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>;

jQuery(document).ready(function($) {
    // Set flag to indicate this is a quote form
    window.isQuoteForm = true;
    
    // Function to get URL parameter
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    
    // Function to switch to a specific tab
    function switchToTab(tabId) {
        if (tabId && $('#' + tabId).length) {
            // Remove active state from all tabs
            $('.tab-button').removeClass('border-indigo-500 text-indigo-600').addClass('border-transparent text-gray-500');
            $('.tab-content').addClass('hidden');
            
            // Activate the specified tab
            $('.tab-button[data-tab="' + tabId + '"]').addClass('border-indigo-500 text-indigo-600');
            $('#' + tabId).removeClass('hidden');
            
            // Update URL without page reload
            var url = new URL(window.location);
            url.searchParams.set('tab', tabId);
            window.history.replaceState({}, '', url);
        }
    }
    
    // Check for tab parameter on page load
    var initialTab = getUrlParameter('tab');
    if (initialTab) {
        switchToTab(initialTab);
    }
    
    // Tab switching
    $('.tab-button').on('click', function() {
        var tabId = $(this).data('tab');
        switchToTab(tabId);
    });

    // Template gallery functionality
    $('#browse-all-templates, #browse-templates-btn').on('click', function() {
        // Check if this is the free version
        const isFreeVersion = !window.easyInvoice || !window.easyInvoice.isPro;
        
        if (isFreeVersion) {
            // Show premium upgrade modal for free users
            if (typeof EasyInvoiceConfirmation !== 'undefined' && EasyInvoiceConfirmation.showFeatureUpgrade) {
                EasyInvoiceConfirmation.showFeatureUpgrade('<?php _e('Premium Templates', 'easy-invoice'); ?>', '<?php _e('Access all premium templates including Modern, Professional, Classic, and more to give your quotes a unique and professional look. Browse through our complete template library and find the perfect design for your business.', 'easy-invoice'); ?>');
            } else {
                alert('<?php _e('This is a premium feature. Please upgrade to Pro to access all templates.', 'easy-invoice'); ?>');
            }
        } else {
            // Pro users can browse all templates
            $('#template-gallery-modal').show();
        }
    });

    $('.close-gallery-modal, .gallery-close-btn').on('click', function() {
        $('#template-gallery-modal').hide();
    });

    // Gallery template card click handler
    $(document).on('click', '.gallery-template-card', function() {
        $('.gallery-template-card').removeClass('selected');
        $(this).addClass('selected');
    });

    // Template card click handler
    $(document).on('click', '.template-card', function(e) {
        const templateId = $(this).data('template-id');
        
        // Check if this is a premium template in free version
        const isPremium = $(this).attr('data-is-premium') === 'true';
        const isFreeVersion = !window.easyInvoice || !window.easyInvoice.isPro;
        
        if (isPremium && isFreeVersion) {
            // Show premium upgrade modal instead of selecting the template
            if (typeof EasyInvoiceConfirmation !== 'undefined' && EasyInvoiceConfirmation.showFeatureUpgrade) {
                EasyInvoiceConfirmation.showFeatureUpgrade('<?php _e('Premium Templates', 'easy-invoice'); ?>', '<?php _e('Access all premium templates including Modern, Professional, Classic, and more to give your quotes a unique and professional look.', 'easy-invoice'); ?>');
            } else {
                alert('<?php _e('This is a premium feature. Please upgrade to Pro to access all templates.', 'easy-invoice'); ?>');
            }
            return;
        }
        
        // Select the template
        $('.template-card').removeClass('selected');
        $(this).addClass('selected');
        $('input[name="quote_template"]').val(templateId);
        $('input[name="quote_template"][value="' + templateId + '"]').prop('checked', true);
        
        // Update the live preview
        if (typeof updateLivePreview === 'function') {
            updateLivePreview(templateId);
        }
    });

    // Apply selected template
    $('#apply-selected-template').on('click', function() {
        const selectedTemplate = $('.gallery-template-card.selected').data('template-id');
        if (selectedTemplate) {
            $('.template-card').removeClass('selected');
            $('.template-card[data-template-id="' + selectedTemplate + '"]').addClass('selected');
            $('input[name="quote_template"]').val(selectedTemplate);
            $('input[name="quote_template"][value="' + selectedTemplate + '"]').prop('checked', true);
            $('#template-gallery-modal').hide();
            
            // Update the live preview
            if (typeof updateLivePreview === 'function') {
                updateLivePreview(selectedTemplate);
            }
        }
    });





    // Quote Items functionality
    let itemIndex = $('.quote-item').length;

    // Initialize existing items with correct indices
    $('.quote-item').each(function(index) {
        const $item = $(this);
        
        // Update all input fields - match both items[0][fieldname] and items[-1][fieldname]
        $item.find('input[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + index + '][');
            $(this).attr('name', newName);
        });
        
        // Update all textarea fields - match both items[0][fieldname] and items[-1][fieldname]
        $item.find('textarea[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + index + '][');
            $(this).attr('name', newName);
        });
        
        // Update all select fields - match both items[0][fieldname] and items[-1][fieldname]
        $item.find('select[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + index + '][');
            $(this).attr('name', newName);
        });
        
        // Update field IDs to be unique (handle both _-1 and _0)
        $item.find('[id*="_-1"], [id*="_0"]').each(function() {
            var oldId = $(this).attr('id');
            var newId = oldId.replace(/_(?:-1|0)/, '_' + index);
            $(this).attr('id', newId);
            // Update corresponding label for attribute
            var $label = $item.find('label[for="' + oldId + '"]');
            if ($label.length) {
                $label.attr('for', newId);
            }
        });
    });

    // Add new item
    $('.add-item-button').on('click', function() {
        addNewQuoteItem();
    });

    // Remove item
    $(document).on('click', '.remove-item', function() {
        const itemContainer = $(this).closest('.quote-item');
        if ($('.quote-item').length > 1) {
            itemContainer.remove();
            updateItemNumbers();
            calculateTotals();
        } else {
            // If it's the last item, just clear the fields
            itemContainer.find('input, textarea').val('');
            itemContainer.find('select').prop('selectedIndex', 0);
        }
    });

    // Item collapse toggle
    $(document).on('click', '.item-collapse-toggle', function() {
        const itemContainer = $(this).closest('.quote-item');
        const content = itemContainer.find('.item-content');
        const summary = itemContainer.find('.item-collapsed-summary');
        const sampleButton = itemContainer.find('.fill-sample-data-btn');
        const icon = $(this).find('i');
        
        if (content.is(':visible')) {
            // Collapsing - update summary and change icon
            updateQuoteItemSummary(itemContainer);
            content.slideUp(200);
            summary.slideDown(200);
            sampleButton.hide(); // Hide sample button when collapsed
            icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
            // Add compact styling to the collapsed item
            itemContainer.addClass('collapsed-item');
        } else {
            // Expanding - hide summary and change icon
            content.slideDown(200);
            summary.slideUp(200);
            sampleButton.show(); // Show sample button when expanded
            icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
            // Remove compact styling from the expanded item
            itemContainer.removeClass('collapsed-item');
        }
        
        // Update totals if payment manager is available
        if (window.EasyInvoicePayment && typeof window.EasyInvoicePayment.updateTotals === 'function') {
            window.EasyInvoicePayment.updateTotals();
        } else if (typeof updatePreview === 'function') {
            updatePreview();
        }
    });

    // Fill sample data
    $(document).on('click', '.fill-sample-data-btn', function() {
        const itemContainer = $(this).closest('.quote-item');
        fillQuoteItemWithSampleData(itemContainer);
    });

    // Collapse all items
    $('#collapse-all-items').on('click', function() {
        const $button = $(this);
        let allCollapsed = true;
        
        // Check if all items are already collapsed
        $('.quote-item').each(function() {
            const $item = $(this);
            const itemContent = $item.find('.item-content');
            if (itemContent.is(':visible')) {
                allCollapsed = false;
                return false; // Break the loop if we find an expanded item
            }
        });
        
        if (allCollapsed) {
            // If all items are collapsed, expand them
            $button.html('<i class="fas fa-chevron-down mr-1"></i> <?php _e('Collapse All', 'easy-invoice'); ?>');
            $('.quote-item').each(function() {
                const $item = $(this);
                const itemContent = $item.find('.item-content');
                const summaryElement = $item.find('.item-collapsed-summary');
                const sampleButton = $item.find('.fill-sample-data-btn');
                const icon = $item.find('.item-collapse-toggle i');
                
                // Only toggle if it's currently collapsed
                if (!itemContent.is(':visible')) {
                    itemContent.slideDown(200);
                    summaryElement.slideUp(200);
                    sampleButton.show(); // Show sample button when expanded
                    icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
                    // Remove collapsed item styling
                    $item.removeClass('collapsed-item');
                }
            });
        } else {
            // If any items are expanded, collapse them all
            $button.html('<i class="fas fa-chevron-right mr-1"></i> <?php _e('Expand All', 'easy-invoice'); ?>');
            $('.quote-item').each(function() {
                const $item = $(this);
                const itemContent = $item.find('.item-content');
                const summaryElement = $item.find('.item-collapsed-summary');
                const sampleButton = $item.find('.fill-sample-data-btn');
                const icon = $item.find('.item-collapse-toggle i');
                
                // Only toggle if it's currently expanded
                if (itemContent.is(':visible')) {
                    // Update the summary before collapsing
                    updateQuoteItemSummary($item);
                    itemContent.slideUp(200);
                    summaryElement.slideDown(200);
                    sampleButton.hide(); // Hide sample button when collapsed
                    icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
                    // Add collapsed item styling
                    $item.addClass('collapsed-item');
                }
            });
        }
        
        // Update totals if payment manager is available
        if (window.EasyInvoicePayment && typeof window.EasyInvoicePayment.updateTotals === 'function') {
            window.EasyInvoicePayment.updateTotals();
        } else if (typeof updatePreview === 'function') {
            updatePreview();
        }
    });

    // Client search functionality
    let searchTimeout;
    let isSearching = false;
    $('#client-search-input').on('input', function() {
        const query = $(this).val().trim();
        clearTimeout(searchTimeout);
        
        // Don't hide results immediately for short queries - let the search function handle it
        if (query.length === 0) {
            // Don't call searchClients here to avoid duplicate calls with click event
            return;
        }
        
        searchTimeout = setTimeout(function() {
            searchClients(query);
        }, 300);
    });

    // Focus on search input - ensure client tab is active
    $('#client-search-input').on('focus', function() {
        // Switch to client tab first to ensure the search results are visible
        if (window.switchToTab) {
            window.switchToTab('client-tab');
        } else {
            // Fallback: manually switch tabs
            $('.tab-button').removeClass('border-indigo-500 text-indigo-600').addClass('border-transparent text-gray-500');
            $('.tab-content').addClass('hidden');
            $('.tab-button[data-tab="client-tab"]').addClass('border-indigo-500 text-indigo-600');
            $('#client-tab').removeClass('hidden');
        }
    });

    // Click on search input to show all clients
    $("#client-search-input").on("click", function() {

        
        // Switch to client tab first to ensure the search results are visible
        if (window.switchToTab) {
            window.switchToTab('client-tab');
        } else {
            // Fallback: manually switch tabs
            $('.tab-button').removeClass('border-indigo-500 text-indigo-600').addClass('border-transparent text-gray-500');
            $('.tab-content').addClass('hidden');
            $('.tab-button[data-tab="client-tab"]').addClass('border-indigo-500 text-indigo-600');
            $('#client-tab').removeClass('hidden');
        }
        
        // Always show all clients when clicking the search input
        searchClients('');
    });

    // Client selection
    $(document).on('click', '.client-option', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const clientId = $(this).data('client-id');
        const clientName = $(this).data('client-name');
        const clientEmail = $(this).data('client-email');
        const clientCompany = $(this).data('client-company');
        const clientPhone = $(this).data('client-phone');
        const clientWebsite = $(this).data('client-website');
        const clientAddress = $(this).data('client-address');
        
        // Create client data object with all available information
        const clientData = {
            name: clientName,
            email: clientEmail,
            company: clientCompany,
            phone: clientPhone,
            website: clientWebsite,
            address: clientAddress
        };
        
        selectClient(clientId, clientName, clientEmail, clientData);
        $('#client-search-results').hide();
        $('#client-search-input').val('');
    });
    
    // Alternative click handler for client options
    $('#client-search-list').on('click', '.client-option', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const clientId = $(this).data('client-id');
        const clientName = $(this).data('client-name');
        const clientEmail = $(this).data('client-email');
        const clientCompany = $(this).data('client-company');
        const clientPhone = $(this).data('client-phone');
        const clientWebsite = $(this).data('client-website');
        const clientAddress = $(this).data('client-address');
        
        // Create client data object with all available information
        const clientData = {
            name: clientName,
            email: clientEmail,
            company: clientCompany,
            phone: clientPhone,
            website: clientWebsite,
            address: clientAddress
        };
        
        selectClient(clientId, clientName, clientEmail, clientData);
        $('#client-search-results').hide();
        $('#client-search-input').val('');
    });

    // Clear client selection
    $('#clear-client-selection').on('click', function() {
        clearClientSelection();
    });

    // Add new client button - handled by client-manager.js
    // $('#add-new-client-btn').on('click', function() {
    //     $('#add_client_modal').show();
    // });

    // Close modal - handled by client-manager.js
    // $('.close-modal').on('click', function() {
    //     $('#add_client_modal').hide();
    // });

    // Functions
    function addNewQuoteItem() {
        const template = $('#quote-item-template').html();
        const newItem = $(template);
        
        // Update field names with new index using the same pattern as invoice builder
        newItem.find('input[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + itemIndex + '][');
            $(this).attr('name', newName);
        });
        
        newItem.find('textarea[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + itemIndex + '][');
            $(this).attr('name', newName);
        });
        
        newItem.find('select[name*="items["]').each(function() {
            var oldName = $(this).attr('name');
            var newName = oldName.replace(/items\[(?:-1|0)\]\[/, 'items[' + itemIndex + '][');
            $(this).attr('name', newName);
        });
        
        // Update field IDs to be unique (handle both _-1 and _0)
        newItem.find('[id*="_-1"], [id*="_0"]').each(function() {
            var oldId = $(this).attr('id');
            var newId = oldId.replace(/_(?:-1|0)/, '_' + itemIndex);
            $(this).attr('id', newId);
            // Update corresponding label for attribute
            var $label = newItem.find('label[for="' + oldId + '"]');
            if ($label.length) {
                $label.attr('for', newId);
            }
        });
        
        $('.quote-items-container').append(newItem);
        itemIndex++;
        updateItemNumbers();
    }

    function updateItemNumbers() {
        $('.quote-item').each(function(index) {
            const title = $(this).find('h3');
            if (title.text().includes('Item #')) {
                title.text('Item #' + (index + 1));
            }
        });
    }

    function fillQuoteItemWithSampleData(itemContainer) {
        const samples = [
            {
                'title': 'Website Design',
                'description': 'Complete design and layout for a responsive business website.',
                'quantity': 1,
                'price': 1200.00,
                'taxable': true
            },
            {
                'title': 'Consultation Session',
                'description': 'One-hour business strategy consultation.',
                'quantity': 2,
                'price': 150.00,
                'taxable': true
            },
            {
                'title': 'Logo Design',
                'description': 'Custom logo design with 3 initial concepts and 2 revisions.',
                'quantity': 1,
                'price': 350.00,
                'taxable': true
            },
            {
                'title': 'SEO Optimization',
                'description': 'On-page and off-page SEO optimization for better search rankings.',
                'quantity': 1,
                'price': 500.00,
                'taxable': true
            },
            {
                'title': 'Content Writing',
                'description': 'Professional content writing for 5 web pages.',
                'quantity': 5,
                'price': 80.00,
                'taxable': true
            },
            {
                'title': 'Annual Hosting',
                'description': 'One year of premium website hosting.',
                'quantity': 1,
                'price': 200.00,
                'taxable': false
            }
        ];
        const sampleData = samples[Math.floor(Math.random() * samples.length)];

        itemContainer.find('input[name*="[title]"]').val(sampleData.title);
        itemContainer.find('textarea[name*="[description]"]').val(sampleData.description);
        itemContainer.find('input[name*="[quantity]"]').val(sampleData.quantity);
        itemContainer.find('input[name*="[price]"]').val(sampleData.price);
        itemContainer.find('input[name*="[taxable]"]').prop('checked', sampleData.taxable);

        // Update the item title in the header
        itemContainer.find('h3').text(sampleData.title);

        // Trigger calculations
        calculateTotals();
    }

    // Update the collapsed summary of a quote item
    function updateQuoteItemSummary(itemContainer) {
        const quantity = parseFloat(itemContainer.find('input[name*="[quantity]"]').val()) || 0;
        const price = parseFloat(itemContainer.find('input[name*="[price]"]').val()) || 0;
        const total = quantity * price;
        itemContainer.find('.quantity-summary').text(quantity);
        itemContainer.find('.price-summary').text(price.toFixed(2));
        itemContainer.find('.total-summary').text(total.toFixed(2));
        itemContainer.find('input[name*="[total]"]').val(total.toFixed(2));
    }

    function searchClients(query) {

        
        // Prevent multiple simultaneous requests
        if (isSearching) {
            return;
        }
        
        // Clear any existing timeout to prevent multiple requests
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        
        isSearching = true;
        
        $('#client-search-loading').show().removeClass('hidden');
        $('#client-search-empty').hide().addClass('hidden');
        $('#client-search-list').empty();
        
        // If query is empty or less than 2 characters, show all clients
        if (!query || query.trim().length < 2) {
            query = ''; // Set to empty string to get all clients
        }
        

        
        $.ajax({
            url: easyInvoice.ajaxUrl,
            type: 'POST',
            data: {
                action: 'easy_invoice_search_clients',
                query: query,
                nonce: easyInvoice.nonce
            },

            success: function(response) {

                isSearching = false;
                $('#client-search-loading').hide().addClass('hidden');
                
                if (response.success && response.data.length > 0) {
    
                    response.data.forEach(function(client) {
                        const option = $(`
                            <div class="client-option px-4 py-3 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-b-0" 
                                 data-client-id="${client.id}" 
                                 data-client-name="${(client.name || '').replace(/"/g, '&quot;')}" 
                                 data-client-email="${(client.email || '').replace(/"/g, '&quot;')}"
                                 data-client-company="${(client.company || '').replace(/"/g, '&quot;')}"
                                 data-client-phone="${(client.phone || '').replace(/"/g, '&quot;')}"
                                 data-client-address="${(client.address || '').replace(/"/g, '&quot;')}"
                                 onclick="selectClientFromOption(this)">
                                <div class="font-medium text-gray-900">${client.name || 'No Name'}</div>
                                <div class="text-sm text-gray-600">${client.email || 'No Email'}</div>
                            </div>
                        `);
                        $('#client-search-list').append(option);
                    });
                    $('#client-search-results').show().removeClass('hidden');
                    
                } else {
                    $('#client-search-empty').show().removeClass('hidden');
                    $('#client-search-results').show().removeClass('hidden');
                }
            },
            error: function(xhr, status, error) {
                console.error('Quote form: AJAX error:', error);
                console.error('Quote form: Status:', status);
                console.error('Quote form: Response:', xhr.responseText);
                isSearching = false;
                $('#client-search-loading').hide().addClass('hidden');
                $('#client-search-empty').show().removeClass('hidden');
                $('#client-search-results').show().removeClass('hidden');
            }
        });
    }

    function selectClient(clientId, clientName, clientEmail, clientData = null) {
        $('#select-client').val(clientId);
        $('#client-id').val(clientId);
        $('#selected-client-name').text(clientName);
        $('#selected-client-email').text(clientEmail);
        
        $('#selected-client-display').show().removeClass('hidden');
        $('#client-info-display').show().removeClass('hidden');
        $('#no-client-message').hide().addClass('hidden');
        
        // Update the edit client button URL
        $('#edit-selected-client').attr('href', '<?php echo admin_url('admin.php?page=easy-invoice-client-edit&client_id='); ?>' + clientId);
        
        // If we have full client data, populate all fields directly
        if (clientData) {
            $('#display-client-name').text(clientData.name || clientName || '-');
            $('#display-client-company').text(clientData.company || '-');
            $('#display-client-email').text(clientData.email || clientEmail || '-');
            $('#display-client-phone').text(clientData.phone || '-');
            $('#display-client-website').text(clientData.website || '-');
            $('#display-client-address').text(clientData.address || '-');
        } else {
            // Fallback to just the basic info we have
            $('#display-client-name').text(clientName);
            $('#display-client-email').text(clientEmail);
            $('#display-client-company').text('-');
            $('#display-client-phone').text('-');
            $('#display-client-website').text('-');
            $('#display-client-address').text('-');
        }
    }

    function clearClientSelection() {
        $('#select-client').val('');
        $('#client-id').val('');
        $('#selected-client-display').hide();
        $('#client-info-display').hide();
        $('#no-client-message').show();
        
        // Clear display fields
        $('#display-client-name, #display-client-email, #display-client-company, #display-client-phone, #display-client-website, #display-client-address').text('-');
    }

    function calculateTotals() {
        let subtotal = 0;
        let taxableSubtotal = 0;
        $('.quote-item').each(function() {
            const quantity = parseFloat($(this).find('input[name*="[quantity]"]').val()) || 0;
            const price = parseFloat($(this).find('input[name*="[price]"]').val()) || 0;
            let adjustPercentage = 0;
            // Only apply adjust percentage if the adjust field is enabled
            if (window.easyInvoice && window.easyInvoice.showAdjustField) {
                adjustPercentage = parseFloat($(this).find('input[name*="[adjust_percentage]"]').val()) || 0;
            }
            const isTaxable = $(this).find('input[name*="[taxable]"]').is(':checked');
            const baseTotal = quantity * price;
            const total = baseTotal * (1 + adjustPercentage / 100);
            $(this).find('.total-summary').text(total.toFixed(2));
            $(this).find('input[name*="[total]"]').val(total.toFixed(2));
            subtotal += total;
            if (isTaxable) {
                taxableSubtotal += total;
            }
        });
        $('input[name="subtotal"]').val(subtotal.toFixed(2));
        calculateTaxAndDiscount(subtotal, taxableSubtotal);
    }

    function calculateTaxAndDiscount(subtotal, taxableSubtotal) {
        subtotal = (subtotal !== undefined) ? subtotal : (parseFloat($('input[name="subtotal"]').val()) || 0);
        taxableSubtotal = (taxableSubtotal !== undefined) ? taxableSubtotal : subtotal;

        const discountValue = parseFloat($('input[name="discount_value"]').val()) || 0;
        const discountType = $('select[name="discount_type"]').val();
        const calculationMethod = $('select[name="discount_calculation_method"]').val() || 'before_tax';
        const taxRate = parseFloat($('input[name="tax_rate"]').val()) || 0;
        const pricesIncludeTax = $('select[name="prices_include_tax"]').val() === 'yes';

        // Calculate discount
        let discountAmount = 0;
        if (discountType === 'percentage') {
            discountAmount = subtotal * (discountValue / 100);
        } else if (discountType === 'fixed') {
            discountAmount = Math.min(discountValue, subtotal);
        }
        // discountType === 'none': discountAmount stays 0

        const afterDiscountAmount = subtotal - discountAmount;
        const discountRatio = (subtotal > 0) ? (discountAmount / subtotal) : 0;

        // Calculate tax
        let taxAmount = 0;
        let total = 0;

        if (pricesIncludeTax && taxRate > 0) {
            // Extract tax from taxable portion (reverse calculation)
            const taxableAfterDiscount = taxableSubtotal * (1 - discountRatio);
            taxAmount = taxableAfterDiscount - (taxableAfterDiscount / (1 + taxRate / 100));
            total = afterDiscountAmount;
        } else if (taxRate > 0) {
            if (calculationMethod === 'before_tax') {
                // Discount first, then tax on remaining taxable amount
                const taxableAfterDiscount = taxableSubtotal * (1 - discountRatio);
                taxAmount = taxableAfterDiscount * (taxRate / 100);
            } else {
                // after_tax: Tax first on full taxable subtotal, then discount
                taxAmount = taxableSubtotal * (taxRate / 100);
                if (discountType === 'percentage') {
                    const totalBeforeDiscount = subtotal + taxAmount;
                    discountAmount = totalBeforeDiscount * (discountValue / 100);
                }
            }
            total = (subtotal - discountAmount) + taxAmount;
        } else {
            total = afterDiscountAmount;
        }

        $('input[name="discount_amount"]').val(discountAmount.toFixed(2));
        $('input[name="tax_amount"]').val(taxAmount.toFixed(2));
        $('input[name="total"]').val(total.toFixed(2));
    }

    // Initialize calculations on page load
    calculateTotals();
    
    // Initialize existing client data on page load
    const existingClientId = $('#client-id').val();
    const existingClientName = $('#selected-client-name').text().trim();
    const existingClientEmail = $('#selected-client-email').text().trim();
    
    // Get existing client data from PHP
    const existingClientData = <?php echo json_encode($client_data); ?>;
    
    if (existingClientId && existingClientName && existingClientName !== '-') {
        // Show the selected client display and client info display
        $('#selected-client-display').show();
        $('#client-info-display').show();
        $('#no-client-message').hide();
        
        // Set the select client dropdown value without triggering change event
        // Use a flag to prevent AJAX calls during initialization
        window.isInitializingClient = true;
        $('#select-client').val(existingClientId);
        setTimeout(function() {
            window.isInitializingClient = false;
        }, 1000);
        
        // Populate the search input with the existing client name
        $('#client-search-input').val(existingClientName);
        
        // Client initialized successfully
    }
    
    // Bind calculation events
    $(document).on('input', 'input[name*="[quantity]"], input[name*="[price]"], input[name*="[adjust_percentage]"]', function() {
        calculateTotals();
    });

    $(document).on('change', 'input[name*="[taxable]"]', function() {
        calculateTotals();
    });
    
    $(document).on('input', 'input[name="discount_value"], input[name="tax_rate"]', function() {
        calculateTotals();
    });
    
    $(document).on('change', 'select[name="discount_type"], select[name="discount_calculation_method"], select[name="prices_include_tax"]', function() {
        calculateTotals();
    });

    // Click on search input to show all clients
    $("#client-search-input").on("click", function() {
        // Only show all clients if the search results are not already visible
        if (!$('#client-search-results').is(':visible')) {
            searchClients('');
        }
    });
    
    // Global function for inline onclick
    window.selectClientFromOption = function(element) {
        const $element = $(element);
        const clientId = $element.data('client-id');
        const clientName = $element.data('client-name');
        const clientEmail = $element.data('client-email');
        const clientCompany = $element.data('client-company');
        const clientPhone = $element.data('client-phone');
        const clientWebsite = $element.data('client-website');
        const clientAddress = $element.data('client-address');
        
        // Create client data object with all available information
        const clientData = {
            name: clientName,
            email: clientEmail,
            company: clientCompany,
            phone: clientPhone,
            website: clientWebsite,
            address: clientAddress
        };
        
        selectClient(clientId, clientName, clientEmail, clientData);
        $('#client-search-results').hide();
        $('#client-search-input').val('');
    };
});

// Quote field configuration and pre-loaded data
</script>

<?php if (wp_doing_ajax()): ?>
    <!-- Save Button Section for Modal -->
    <div class="mt-8 pt-6 border-t border-gray-200">
        <div class="flex justify-end space-x-3">
            <button type="button" id="cancel-quote-btn" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300">
                Cancel
            </button>
            <button type="submit" id="save-quote-btn" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <i class="fas fa-save mr-2"></i>
                <span>Save Quote</span>
            </button>
        </div>
    </div>
</form>
<?php endif; ?> 