<?php
// Enqueue CSS and JS files
wp_enqueue_style('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/css/invoice-form.css', array(), '1.0.0');
wp_enqueue_script('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/js/invoice-form.js', array('jquery'), '1.0.0', true);

// Initialize the form manager
$form_manager = new EasyInvoice\Forms\Invoice\InvoiceFormManager();

// Get field configuration for JavaScript
$invoice_field_config = $form_manager->getFieldConfigForJavaScript();

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

$tabs = $form_manager->getTabs();
$templates = $form_manager->getTemplates();

// Create a separate array for browse templates modal with all available templates
$all_templates = apply_filters('easy_invoice_invoice_templates', [
    'standard' => [
        'name' => __('Standard', 'easy-invoice'),
        'icon' => 'fas fa-file-invoice',
        'description' => __('Clean and professional standard template', 'easy-invoice'),
        'order' => 1,
        'is_free' => true
    ],
    'legacy' => [
        'name' => __('Legacy', 'easy-invoice'),
        'icon' => 'fas fa-file-alt',
        'description' => __('Clean, minimalist design with traditional business layout', 'easy-invoice'),
        'order' => 2,
        'is_free' => true
    ],
    'professional' => [
        'name' => __('Professional', 'easy-invoice'),
        'icon' => 'fas fa-briefcase',
        'description' => __('Professional business template with modern design', 'easy-invoice'),
        'order' => 3,
        'is_free' => false
    ],
    'modern' => [
        'name' => __('Modern', 'easy-invoice'),
        'icon' => 'fas fa-rocket',
        'description' => __('Modern and sleek design template', 'easy-invoice'),
        'order' => 4,
        'is_free' => false
    ],
    'classic' => [
        'name' => __('Classic', 'easy-invoice'),
        'icon' => 'fas fa-landmark',
        'description' => __('Traditional business template', 'easy-invoice'),
        'order' => 5,
        'is_free' => false
    ],
    'minimal' => [
        'name' => __('Minimal', 'easy-invoice'),
        'icon' => 'fas fa-minus',
        'description' => __('Simple and clean minimal template', 'easy-invoice'),
        'order' => 6,
        'is_free' => false
    ],

    'corporate' => [
        'name' => __('Corporate', 'easy-invoice'),
        'icon' => 'fas fa-building',
        'description' => __('Professional corporate template', 'easy-invoice'),
        'order' => 7,
        'is_free' => false
    ],
    'elegant' => [
        'name' => __('Elegant', 'easy-invoice'),
        'icon' => 'fas fa-gem',
        'description' => __('Elegant and sophisticated design', 'easy-invoice'),
        'order' => 8,
        'is_free' => false
    ],
    'creative' => [
        'name' => __('Creative', 'easy-invoice'),
        'icon' => 'fas fa-palette',
        'description' => __('Creative and artistic design template', 'easy-invoice'),
        'order' => 9,
        'is_free' => false
    ]
]);



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

<style>
/* 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>

                <div class="bg-white shadow rounded-lg">

                    <div class="border-b border-gray-200">
                        <nav class="flex -mb-px" aria-label="<?php esc_attr_e( 'Invoice 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 font-medium 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 id="invoice-form">
                        <!-- Hidden invoice ID field for edit mode -->
                        <input type="hidden" id="invoice-id" name="invoice_id" value="<?php echo $invoice_id ? esc_attr($invoice_id) : ''; ?>">

                        <!-- Security nonce -->
                        <input type="hidden" id="invoice_nonce" name="invoice_nonce" value="<?php echo wp_create_nonce('easy_invoice_nonce'); ?>">

                        <?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'] === 'invoice-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('Invoice 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 Invoice Templates', 'easy-invoice'); ?></span>
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                </div>

                                <?php
                                // Get the current template (default to 'standard')
                                $current_template = $invoice ? $invoice->getTemplate() : 'standard';

                                if (empty($current_template)) {
                                    $current_template = 'standard';
                                }

                                // Always include the hidden input for the template field
                                ?>
                                <input type="hidden" name="invoice_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', 'professional'];
                                    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="invoice_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 = $form_manager->getFields('invoice-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'] !== 'invoice_template') {
                                                echo $form_manager->renderField($field, $invoice);
                                            }
                                        endforeach;
                                        ?>
                            </div>

                            <!-- Auto-generation notice for new invoices -->
                            <?php if (!$invoice): ?>
                            <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('Invoice number will be automatically generated when you save the invoice.', 'easy-invoice'); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Recurring Invoice Section -->
                            <?php if (easy_invoice_has_pro()): ?>
                                <?php
                                $recurring_fields = $form_manager->getFieldsBySection('invoice-tab', 'recurring');
                                if (!empty($recurring_fields)):
                                ?>
                                <div class="mt-8 border-t border-gray-200 pt-6">
                                    <h3 class="text-lg font-medium text-gray-900"><?php _e('Recurring Invoice Settings', 'easy-invoice-pro'); ?></h3>
                                    <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:col-span-6">
                                                <?php
                                                foreach ($recurring_fields as $field):
                                                    echo $form_manager->renderField($field, $invoice);
                                                endforeach;
                                                ?>
                                            </div>
                                        </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <!-- Recurring Invoice Promotion for Free Users -->
                                <div class="mt-6 border-t border-gray-200 pt-4">
                                    <div class="bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 rounded-lg p-4">
                                        <div class="flex items-start">
                                            <div class="flex-shrink-0">
                                                <div class="w-8 h-8 bg-gradient-to-r from-purple-500 to-indigo-600 rounded-lg flex items-center justify-center">
                                                    <i class="fas fa-sync-alt text-white text-sm"></i>
                                                </div>
                                            </div>
                                            <div class="ml-3 flex-1">
                                                <h3 class="text-base font-semibold text-gray-900 mb-1"><?php _e('Recurring Invoices', 'easy-invoice'); ?></h3>
                                                <p class="text-sm text-gray-600 mb-3"><?php _e('Automate your billing with recurring invoices. Set up weekly, monthly, or custom intervals to automatically generate and send invoices to your clients.', 'easy-invoice'); ?></p>
                                                <div class="flex items-center space-x-3 mb-3">
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Automated billing cycles', 'easy-invoice'); ?></span>
                                                    </div>
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Custom intervals', 'easy-invoice'); ?></span>
                                                    </div>
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Auto-send notifications', 'easy-invoice'); ?></span>
                                                    </div>
                                                </div>
                                                <button type="button" class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 transition-all duration-200" onclick="if(typeof EasyInvoiceConfirmation !== 'undefined' && EasyInvoiceConfirmation.showFeatureUpgrade) { EasyInvoiceConfirmation.showFeatureUpgrade('<?php _e('Recurring Invoices', 'easy-invoice'); ?>', '<?php _e('Automate your billing with recurring invoices. Set up weekly, monthly, or custom intervals to automatically generate and send invoices to your clients.', 'easy-invoice'); ?>'); } else { alert('<?php _e('This is a premium feature. Please upgrade to Pro to access recurring invoices.', 'easy-invoice'); ?>'); }">
                                                    <i class="fas fa-crown mr-1.5"></i>
                                                    <?php _e('Upgrade to Pro', 'easy-invoice'); ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <!-- Subscription Invoice Section -->
                            <?php if (easy_invoice_has_pro()): ?>
                                <?php
                                // Check if subscription is actually enabled
                                $subscription_enabled = get_option('easy_invoice_pro_subscription_enabled', '0');
                                if ($subscription_enabled):
                                    $subscription_fields = $form_manager->getFieldsBySection('invoice-tab', 'subscription');
                                    if (!empty($subscription_fields)):
                                    ?>
                                    <div class="mt-8 border-t border-gray-200 pt-6">
                                        <h3 class="text-lg font-medium text-gray-900"><?php _e('Subscription Settings', 'easy-invoice-pro'); ?></h3>
                                        <div class="mt-4 grid grid-cols-1 gap-y-6 gap-x-4 sm:col-span-6">
                                                    <?php
                                                    foreach ($subscription_fields as $field):
                                                        echo $form_manager->renderField($field, $invoice);
                                                    endforeach;
                                                    ?>
                                                </div>
                                            </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                            <?php else: ?>
                                <!-- Subscription Invoice Promotion for Free Users -->
                                <div class="mt-6 border-t border-gray-200 pt-4">
                                    <div class="bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 rounded-lg p-4">
                                        <div class="flex items-start">
                                            <div class="flex-shrink-0">
                                                <div class="w-8 h-8 bg-gradient-to-r from-purple-500 to-indigo-600 rounded-lg flex items-center justify-center">
                                                    <i class="fas fa-calendar-alt text-white text-sm"></i>
                                                </div>
                                            </div>
                                            <div class="ml-3 flex-1">
                                                <h3 class="text-base font-semibold text-gray-900 mb-1"><?php _e('Partial Payment', 'easy-invoice'); ?></h3>
                                                <p class="text-sm text-gray-600 mb-3"><?php _e('Accept partial payments from clients with flexible payment schedules, payment tracking, and outstanding balance management.', 'easy-invoice'); ?></p>
                                                <div class="flex items-center space-x-3 mb-3">
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Flexible payment schedules', 'easy-invoice'); ?></span>
                                                    </div>
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Payment tracking', 'easy-invoice'); ?></span>
                                                    </div>
                                                    <div class="flex items-center text-xs text-gray-500">
                                                        <i class="fas fa-check text-green-500 mr-1"></i>
                                                        <span><?php _e('Balance management', 'easy-invoice'); ?></span>
                                                    </div>
                                                </div>
                                                <button type="button" class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 transition-all duration-200" onclick="if(typeof EasyInvoiceConfirmation !== 'undefined' && EasyInvoiceConfirmation.showFeatureUpgrade) { EasyInvoiceConfirmation.showFeatureUpgrade('<?php _e('Partial Payment', 'easy-invoice'); ?>', '<?php _e('Accept partial payments from clients with flexible payment schedules, payment tracking, and outstanding balance management.', 'easy-invoice'); ?>'); } else { alert('<?php _e('This is a premium feature. Please upgrade to Pro to access partial payment functionality.', 'easy-invoice'); ?>'); }">
                                                    <i class="fas fa-crown mr-1.5"></i>
                                                    <?php _e('Upgrade to Pro', 'easy-invoice'); ?>
                                                </button>
                                            </div>
                                        </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 invoice tab fields
                                            $notes_fields = $form_manager->getFieldsBySection('invoice-tab', 'notes');
                                            foreach ($notes_fields as $field):
                                                echo $form_manager->renderField($field, $invoice);
                                            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('Invoice 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 invoice-items-container">
                                <?php
                                // If editing an existing invoice, directly output invoice items
                                if ($invoice && $invoice->getItems()) :
                                    $index = 0;
                                    foreach ($invoice->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="invoice-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 $form_manager->generateExistingItemHtml($item, $index); ?>
                                            </div>
                                        </div>
                                        <?php
                                        $index++;
                                    endforeach;
                                else:
                                    // For new invoices, render one empty item by default
                                    $index = 0;
                                    // Get the item fields config
                                    $item_fields = $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="invoice-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">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 $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="absolute z-50 w-full mt-2 bg-white border border-gray-200 rounded-lg shadow-xl max-h-80 overflow-y-auto" style="display: none;">
                                        <div id="client-search-loading" class="p-6 text-center text-gray-500" style="display: none;">
                                            <i class="fas fa-spinner fa-spin mr-2"></i>
                                            <?php _e('Searching...', 'easy-invoice'); ?>
                                        </div>
                                        <div id="client-search-empty" class="p-6 text-center text-gray-500" style="display: none;">
                                            <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 ($invoice && $invoice->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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
                                                            if ($client) {
                                                                echo esc_html($client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()));
                                                            } else {
                                                                echo esc_html__('—', 'easy-invoice');
                                                            }
                                                        } else {
                                                            echo esc_html__('—', 'easy-invoice');
                                                        }
                                                        ?>
                                                    </p>
                                                    <p id="selected-client-email" class="text-sm text-gray-600">
                                                        <?php
                                                        if ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
                                                            if ($client) {
                                                                echo esc_html($client->getEmail() ?: esc_html__('—', 'easy-invoice'));
                                                            } else {
                                                                echo esc_html__('—', 'easy-invoice');
                                                            }
                                                        } else {
                                                            echo esc_html__('—', 'easy-invoice');
                                                        }
                                                        ?>
                                                    </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
                                    // Ensure $clients is defined
                                    if (!isset($clients)) {
                                        $client_repository = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository();
                                        $clients = $client_repository->all();
                                    }

                                    // 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 Client model properties first, fallback to WordPress user fields
                                            $business_name = $client->business_client_name ?: '';
                                            $first_name = $client->first_name ?: $user->first_name ?: '';
                                            $last_name = $client->last_name ?: $user->last_name ?: '';
                                            $client_email = $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 = $invoice && $invoice->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 $invoice ? esc_attr($invoice->getClientId()) : ''; ?>">

                                <!-- Client Information Display -->
                                <div id="client-info-display" class="mt-6 <?php echo $invoice && $invoice->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=' . ($invoice && $invoice->getClientId() ? $invoice->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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
                                                                                                            if ($client) {
                                                    echo esc_html($client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()));
                                                } else {
                                                    echo esc_html__('—', 'easy-invoice');
                                                }
                                            } else {
                                                echo esc_html__('—', 'easy-invoice');
                                                        }
                                                        ?>
                                                    </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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
                                                            if ($client) {
                                                                echo esc_html($client->getBusinessClientName() ?: esc_html__('—', 'easy-invoice'));
                                                            } else {
                                                                echo esc_html__('—', 'easy-invoice');
                                                            }
                                                        } else {
                                                            echo esc_html__('—', 'easy-invoice');
                                                        }
                                                        ?>
                                                    </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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
                                                            if ($client) {
                                                                echo esc_html($client->getEmail() ?: esc_html__('—', 'easy-invoice'));
                                                            } else {
                                                                echo esc_html__('—', 'easy-invoice');
                                                            }
                                                        } else {
                                                            echo esc_html__('—', 'easy-invoice');
                                                        }
                                                        ?>
                                                    </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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->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 ($invoice && $invoice->getClientId()) {
                                                            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->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 $invoice && $invoice->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 = $form_manager->getFieldsBySection('discounts-taxes-tab', 'discount');
                                            $tax_fields = $form_manager->getFieldsBySection('discounts-taxes-tab', 'tax');
                                            $additional_tax_fields = $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 $form_manager->renderField($field, $invoice);
                                            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 = $form_manager->getFieldsBySection('payments-tab', 'payment');
                                            foreach ($payment_fields as $field):
                                                echo $form_manager->renderField($field, $invoice);
                                            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 = $form_manager->getFieldsBySection('payments-tab', 'currency');
                                                foreach ($currency_fields as $field):
                                                    echo $form_manager->renderField($field, $invoice);
                                                endforeach;
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </form>
                </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 Invoice 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 Invoice Items -->
                <template id="invoice-item-template" style="display: none;">
                    <div class="invoice-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($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">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-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 $form_manager->generateItemTemplateHtml(); ?>
                        </div>
                    </div>
                </template>

                <!-- Add Client Modal -->
                <div id="add_client_modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50">
                    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-medium text-gray-900">Add New Client</h3>
                            <button type="button" class="close-modal text-gray-400 hover:text-gray-500">
                                <span class="sr-only">Close</span>
                                <i class="fas fa-times"></i>
                            </button>
                        </div>

                        <?php
                        // Unset the $client variable from the foreach loop to ensure clean add form
                        unset($client);
                        include_once EASY_INVOICE_PLUGIN_DIR . 'templates/client-form.php';
                        ?>
                    </div>
                </div>

<?php

// Always localize script with AJAX URL and nonce
wp_localize_script('easy-invoice-form', 'easyInvoice', array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('easy_invoice_nonce'),
    'clientData' => $client_data ?: array()
));
?>

<script>
jQuery(document).ready(function($) {


    // Client search functionality for invoice form
    var searchTimeout;

    // Initialize existing client data
    var existingClientId = '<?php echo $invoice ? esc_js($invoice->getClientId()) : ''; ?>';
    var existingClientName = '<?php
        if ($invoice && $invoice->getClientId()) {
            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
            if ($client) {
                echo esc_js($client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()));
            }
        }
    ?>';
    var existingClientEmail = '<?php
        if ($invoice && $invoice->getClientId()) {
            $client = \EasyInvoice\Providers\ClientServiceProvider::getClientRepository()->find($invoice->getClientId());
            if ($client) {
                echo esc_js($client->getEmail() ?: '');
            }
        }
    ?>';
    var 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
        $('#select-client').val(existingClientId);

        // Populate the search input with the existing client name
        $('#client-search-input').val(existingClientName);


    }

    // Client search input functionality
    $('#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) {
            // Show all clients when input is cleared
            searchClients('');
            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() {
        // Show the dropdown and call AJAX to populate it
        $('#client-search-results').show();
        $('#client-search-loading').show();
        $('#client-search-empty').hide();

        // Call the AJAX method to populate the dropdown
        if (typeof easyInvoice !== 'undefined' && easyInvoice.ajaxUrl) {
            searchClients('');
        } else {
            $('#client-search-loading').hide();
            $('#client-search-empty').show();
        }
    });

    // 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
    $('#add-new-client-btn').on('click', function() {
        $('#add_client_modal').show();
    });

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

    // Functions
    function searchClients(query) {
        $('#client-search-loading').show();
        $('#client-search-empty').hide();
        $('#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) {
                $('#client-search-loading').hide();

                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-website="${(client.website || '').replace(/"/g, '&quot;')}"
                                 data-client-address="${(client.address || '').replace(/"/g, '&quot;')}"
                                 onclick="selectClientFromOption(this)">
                                <div class="font-medium text-gray-900">${client.name}</div>
                                <div class="text-sm text-gray-600">${client.email}</div>
                            </div>
                        `);

                        $('#client-search-list').append(option);
                    });
                    $('#client-search-results').show();
                } else {
                    $('#client-search-empty').show();
                    $('#client-search-results').show();
                }
            },
            error: function(xhr, status, error) {
                $('#client-search-loading').hide();
                $('#client-search-empty').show();
                $('#client-search-results').show();
            }
        });
    }

    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().removeClass('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('-');
    }

    // 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('');
    };
});
</script>

<script>
// Invoice field configuration and pre-loaded data
window.easyInvoice = window.easyInvoice || {};
<?php
$json_field_config = json_encode($invoice_field_config);
?>
window.easyInvoice.fieldConfig = <?php echo $json_field_config; ?>;
window.easyInvoice.adminUrl = '<?php echo admin_url(); ?>';
window.easyInvoice.isPro = <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>;
window.easyInvoice.translations = {
    premiumTemplates: '<?php _e('Premium Templates', 'easy-invoice'); ?>',
    premiumTemplatesDescription: '<?php _e('Access all premium templates including Modern, Professional, Classic, and more to give your invoices a unique and professional look.', 'easy-invoice'); ?>',
    premiumFeatureMessage: '<?php _e('This is a premium feature. Please upgrade to Pro to access all templates.', 'easy-invoice'); ?>',
    selectTemplateFirst: '<?php _e('Please select a template first', 'easy-invoice'); ?>'
};
<?php if ($client_data): ?>
window.easyInvoice.clientData = <?php echo json_encode($client_data); ?>;
<?php endif; ?>
</script>
