<?php
/**
 * Invoice Form View
 */
if (!defined('ABSPATH')) exit;
$page_title = $is_new ? __('New Invoice', 'freelance-studio') : __('Edit Invoice', 'freelance-studio');
?>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <h1><?php echo esc_html($page_title); ?></h1>
    
    <form method="post">
        <?php wp_nonce_field('fs_save_invoice', 'fs_invoice_nonce'); ?>
        <input type="hidden" name="action" value="<?php echo $is_new ? 'create' : 'update'; ?>">
        <?php if (!$is_new): ?><input type="hidden" name="invoice_id" value="<?php echo  intval( $invoice->id ); ?>"><?php endif; ?>
        
        <div class="fs-form-section">
            <h2><?php esc_html_e('Invoice Details', 'freelance-studio'); ?></h2>
            
            <div class="fs-form-row">
                <div class="fs-form-group required">
                    <label for="client_id"><?php esc_html_e('Client', 'freelance-studio'); ?></label>
                    <select name="client_id" id="client_id" required>
                        <option value=""><?php esc_html_e('Select Client', 'freelance-studio'); ?></option>
                        <?php foreach ($clients as $c): ?>
                            <option value="<?php echo  intval( $c->id ); ?>" <?php selected($invoice ? $invoice->client_id : ($selected_client_id ?? 0), $c->id); ?>><?php echo esc_html($c->company_name ?: $c->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="fs-form-group">
                    <label for="project_id"><?php esc_html_e('Project', 'freelance-studio'); ?></label>
                    <select name="project_id" id="project_id">
                        <option value=""><?php esc_html_e('No project', 'freelance-studio'); ?></option>
                        <?php if (!empty($projects)): foreach ($projects as $p): ?>
                            <option value="<?php echo  intval( $p->id ); ?>" <?php selected($invoice ? $invoice->project_id : ($selected_project_id ?? 0), $p->id); ?>><?php echo esc_html($p->name); ?></option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>
                
                <div class="fs-form-group required">
                    <label for="invoice_number"><?php esc_html_e('Invoice #', 'freelance-studio'); ?></label>
                    <input type="text" name="invoice_number" id="invoice_number" required value="<?php echo $invoice ? esc_attr($invoice->invoice_number) : esc_attr($next_invoice_number); ?>">
                </div>
            </div>
            
            <div class="fs-form-row">
                <div class="fs-form-group">
                    <label for="status"><?php esc_html_e('Status', 'freelance-studio'); ?></label>
                    <select name="status" id="status">
                        <?php foreach ($statuses as $k => $l): ?>
                            <option value="<?php echo esc_attr($k); ?>" <?php selected($invoice ? $invoice->status : 'draft', $k); ?>><?php echo esc_html($l); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description"><?php esc_html_e('Status will auto-update based on dates below', 'freelance-studio'); ?></p>
                </div>
                
                <div class="fs-form-group">
                    <label for="invoice_date"><?php esc_html_e('Date Invoice Sent', 'freelance-studio'); ?></label>
                    <input type="date" name="invoice_date" id="invoice_date" value="<?php echo $invoice ? esc_attr($invoice->invoice_date) : ''; ?>">
                    <p class="description"><?php esc_html_e('Set when invoice was/will be sent (optional)', 'freelance-studio'); ?></p>
                </div>
                
                <div class="fs-form-group">
                    <label for="paid_date"><?php esc_html_e('Date Invoice Paid', 'freelance-studio'); ?></label>
                    <input type="date" name="paid_date" id="paid_date" value="<?php echo ($invoice && isset($invoice->paid_date)) ? esc_attr($invoice->paid_date) : ''; ?>">
                    <p class="description"><?php esc_html_e('Auto-sets status to "Paid"', 'freelance-studio'); ?></p>
                </div>
            </div>
            
            <div class="fs-form-row">
                <div class="fs-form-group required">
                    <label for="due_date"><?php esc_html_e('Due Date', 'freelance-studio'); ?></label>
                    <input type="date" name="due_date" id="due_date" required value="<?php echo  esc_attr( $invoice ? esc_attr($invoice->due_date) : gmdate('Y-m-d', strtotime('+' . ($default_payment_terms ?? 30) . ' days')) ); ?>">
                </div>
                
                <div class="fs-form-group">
                    <label for="amount_paid"><?php esc_html_e('Amount Paid', 'freelance-studio'); ?></label>
                    <div class="fs-amount-paid-wrapper">
                        <input type="number" name="amount_paid" id="amount_paid" step="0.01" value="<?php echo ($invoice && $invoice->amount_paid) ? esc_attr($invoice->amount_paid) : ''; ?>">
                        <label class="fs-checkbox-inline">
                            <input type="checkbox" id="full_amount_paid" name="full_amount_paid">
                            <?php esc_html_e('Full Amount Paid', 'freelance-studio'); ?>
                        </label>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="fs-form-section">
            <h2><?php esc_html_e('Line Items', 'freelance-studio'); ?></h2>
            
            <?php if (!empty($from_time) && !empty($time_items)): ?>
                <div class="fs-info-box" style="margin-bottom: 15px; padding: 12px; background: #e7f3ff; border-left: 4px solid #2271b1; border-radius: 4px;">
                    <strong><?php esc_html_e('Invoicing Time Entries', 'freelance-studio'); ?></strong>
                    <?php /* translators: 1. count/number */ ?>
                    <p style="margin: 5px 0 0;"><?php echo wp_kses_post( sprintf( __('Creating invoice from %d unbilled time entries.', 'freelance-studio'), count($unbilled_time_entries))); ?></p>
                </div>
            <?php endif; ?>
            
            <div class="fs-invoice-items">
                <?php 
                // Use time_items if available, otherwise use invoice items or default
                if (!empty($time_items)) {
                    $items = $time_items;
                } elseif ($invoice) {
                    $items = $invoice->items;
                } else {
                    $items = array(array('description' => '', 'quantity' => 1, 'rate' => '', 'amount' => '', 'entry_ids' => array()));
                }
                foreach ($items as $i => $item): 
                    $entry_ids = isset($item['entry_ids']) ? $item['entry_ids'] : array();
                ?>
                <div class="fs-invoice-item">
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                        <input type="text" name="items[<?php echo  esc_attr( $i ); ?>][description]" class="item-description" value="<?php echo esc_attr($item['description']); ?>">
                    </div>
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Qty/Hours', 'freelance-studio'); ?></label>
                        <input type="number" name="items[<?php echo  esc_attr( $i ); ?>][quantity]" class="item-quantity" step="0.01" value="<?php echo esc_attr($item['quantity']); ?>">
                    </div>
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Rate', 'freelance-studio'); ?></label>
                        <input type="number" name="items[<?php echo  esc_attr( $i ); ?>][rate]" class="item-rate" step="0.01" value="<?php echo esc_attr($item['rate']); ?>">
                    </div>
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Amount', 'freelance-studio'); ?></label>
                        <input type="number" name="items[<?php echo  esc_attr( $i ); ?>][amount]" class="item-amount" step="0.01" readonly value="<?php echo esc_attr($item['amount']); ?>">
                    </div>
                    <?php if (!empty($entry_ids)): ?>
                        <input type="hidden" name="items[<?php echo  esc_attr( $i ); ?>][entry_ids]" value="<?php echo esc_attr(implode(',', $entry_ids)); ?>">
                    <?php endif; ?>
                    <button type="button" class="button fs-remove-item">×</button>
                </div>
                <?php endforeach; ?>
            </div>
            
            <button type="button" class="button fs-add-item"><?php esc_html_e('+ Add Line Item', 'freelance-studio'); ?></button>
            
            <div class="fs-invoice-totals">
                <table>
                    <tr><td><?php esc_html_e('Subtotal:', 'freelance-studio'); ?></td><td id="subtotal-display"><?php echo  esc_html( $invoice ? FS_View_Context::format_currency($invoice->subtotal) : '$0.00' ); ?></td></tr>
                    <tr>
                        <td>
                            <?php esc_html_e('Discount:', 'freelance-studio'); ?>
                            <select name="discount_type" id="discount_type" class="fs-inline-input">
                                <option value=""><?php esc_html_e('None', 'freelance-studio'); ?></option>
                                <option value="percentage" <?php selected($invoice ? $invoice->discount_type : '', 'percentage'); ?>>%</option>
                                <option value="fixed" <?php selected($invoice ? $invoice->discount_type : '', 'fixed'); ?>>$</option>
                            </select>
                            <input type="number" name="discount_value" id="discount_value" step="0.01" value="<?php echo $invoice ? esc_attr($invoice->discount_value) : ''; ?>" class="fs-inline-input medium">
                        </td>
                        <td id="discount-display">-$0.00</td>
                    </tr>
                    <tr>
                        <td>
                            <?php esc_html_e('Tax:', 'freelance-studio'); ?> 
                            <?php 
                            // Determine the tax rate to show
                            $default_tax_rate = 0;
                            if ($invoice) {
                                // Existing invoice - use saved rate
                                $default_tax_rate = floatval($invoice->tax_rate);
                            } elseif (get_option('fs_auto_apply_sales_tax', '0') === '1') {
                                // New invoice with auto-apply enabled - use default rate
                                $default_tax_rate = floatval(get_option('fs_default_sales_tax_rate', 0));
                            }
                            ?>
                            <input type="number" name="tax_rate" id="tax_rate" step="0.001" min="0" max="25" value="<?php echo esc_attr($default_tax_rate); ?>" class="fs-inline-input small">%
                        </td>
                        <td id="tax-display"><?php echo  esc_html( $invoice ? FS_View_Context::format_currency($invoice->tax_amount) : '$0.00' ); ?></td>
                    </tr>
                    <tr class="total-row"><td><strong><?php esc_html_e('Total:', 'freelance-studio'); ?></strong></td><td id="total-display"><strong><?php echo  esc_html( $invoice ? FS_View_Context::format_currency($invoice->total) : '$0.00' ); ?></strong></td></tr>
                    <?php if (!$is_new && $invoice->amount_paid > 0): ?>
                    <tr><td><?php esc_html_e('Paid:', 'freelance-studio'); ?></td><td><?php echo  esc_html( FS_View_Context::format_currency($invoice->amount_paid) ); ?></td></tr>
                    <tr><td><strong><?php esc_html_e('Balance:', 'freelance-studio'); ?></strong></td><td><strong><?php echo  esc_html( FS_View_Context::format_currency($invoice->balance_due) ); ?></strong></td></tr>
                    <?php endif; ?>
                </table>
            </div>
        </div>
        
        <!-- Expense Billback Section -->
        <div class="fs-form-section fs-expense-billback-section" id="fs-expense-section">
            <h2><?php esc_html_e('Billable Expenses', 'freelance-studio'); ?></h2>
            <p class="description"><?php esc_html_e('Add project expenses to bill back to the client. You can apply a markup percentage.', 'freelance-studio'); ?></p>
            
            <div class="fs-expense-options">
                <div class="fs-form-row">
                    <div class="fs-form-group">
                        <label for="expense_markup"><?php esc_html_e('Markup %', 'freelance-studio'); ?></label>
                        <input type="number" name="expense_markup" id="expense_markup" step="0.01" min="0" max="100" 
                               value="<?php echo esc_attr($invoice && isset($invoice->expense_markup) ? $invoice->expense_markup : get_option('fs_default_expense_markup', 0)); ?>" 
                               class="small-text">
                        <span class="description"><?php esc_html_e('Common: 10-15%', 'freelance-studio'); ?></span>
                    </div>
                </div>
            </div>
            
            <?php 
            // Get existing invoice expenses
            $invoice_expenses = array();
            if ($invoice && !empty($invoice->expenses)) {
                $invoice_expenses = is_string($invoice->expenses) ? json_decode($invoice->expenses, true) : $invoice->expenses;
                if (!is_array($invoice_expenses)) $invoice_expenses = array();
            }
            
            // Get unbilled expenses for the project
            $available_expenses = array();
            $project_id_for_expenses = $invoice ? $invoice->project_id : ($selected_project_id ?? 0);
            if ($project_id_for_expenses) {
                $available_expenses = FS_Expense::get_unbilled_by_project($project_id_for_expenses);
            }
            
            // Merge: include already invoiced expenses + available unbilled ones
            $all_expenses = array();
            
            // Already included expenses (from this invoice)
            $included_expense_ids = array();
            if (!empty($invoice_expenses)) {
                foreach ($invoice_expenses as $exp) {
                    $included_expense_ids[] = $exp['id'];
                    $all_expenses[] = (object) array(
                        'id' => $exp['id'],
                        'expense_date' => $exp['date'],
                        'expense_name' => $exp['description'],
                        'category' => $exp['category'],
                        'amount' => $exp['amount'],
                        'included' => true,
                        'billed_amount' => isset($exp['billed_amount']) ? $exp['billed_amount'] : $exp['amount'],
                    );
                }
            }
            
            // Add available unbilled expenses
            foreach ($available_expenses as $exp) {
                if (!in_array($exp->id, $included_expense_ids)) {
                    $exp->included = false;
                    $all_expenses[] = $exp;
                }
            }
            ?>
            
            <?php if (!empty($all_expenses)): ?>
            <table class="widefat fs-table fs-expense-table">
                <thead>
                    <tr>
                        <th class="check-column"><input type="checkbox" id="select-all-expenses"></th>
                        <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Category', 'freelance-studio'); ?></th>
                        <th class="text-right"><?php esc_html_e('Amount', 'freelance-studio'); ?></th>
                        <th class="text-right"><?php esc_html_e('With Markup', 'freelance-studio'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($all_expenses as $exp): ?>
                        <tr class="fs-expense-row <?php echo $exp->included ? 'selected' : ''; ?>">
                            <td class="check-column">
                                <input type="checkbox" name="expenses[]" value="<?php echo esc_attr($exp->id); ?>" <?php checked($exp->included); ?>>
                            </td>
                            <td><?php echo esc_html(FS_View_Context::format_date($exp->expense_date)); ?></td>
                            <td><?php echo esc_html($exp->expense_name); ?></td>
                            <td><?php echo esc_html($exp->category); ?></td>
                            <td class="text-right expense-base-amount" data-amount="<?php echo esc_attr($exp->amount); ?>">
                                <?php echo  esc_html( FS_View_Context::format_currency($exp->amount) ); ?>
                            </td>
                            <td class="text-right expense-marked-up">
                                <?php echo  esc_html( FS_View_Context::format_currency($exp->amount) ); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <div class="fs-expense-totals">
                <div class="fs-expense-total-item">
                    <label><?php esc_html_e('Base Total', 'freelance-studio'); ?></label>
                    <span class="amount" id="expense-total-base">$0.00</span>
                </div>
                <div class="fs-expense-total-item">
                    <label><?php esc_html_e('With Markup', 'freelance-studio'); ?></label>
                    <span class="amount" id="expense-total-markup">$0.00</span>
                </div>
            </div>
            <input type="hidden" name="expense_total_with_markup" id="expense_total_with_markup" value="0">
            <?php else: ?>
            <div class="fs-expense-empty">
                <p><?php esc_html_e('No billable expenses available for this project.', 'freelance-studio'); ?></p>
                <?php if ($project_id_for_expenses): ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=expenses&action=add&project_id=' . $project_id_for_expenses) ); ?>" class="button">
                        <?php esc_html_e('Add Expense', 'freelance-studio'); ?>
                    </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="fs-form-section">
            <h2><?php esc_html_e('Notes', 'freelance-studio'); ?></h2>
            <textarea name="notes" rows="3" class="large-text"><?php echo $invoice ? esc_textarea($invoice->notes) : ''; ?></textarea>
        </div>
        
        <div class="fs-form-section">
            <h2><?php esc_html_e('Payment Link', 'freelance-studio'); ?></h2>
            <input type="url" name="payment_link" id="payment_link" class="regular-text" 
                value="<?php echo $invoice ? esc_attr($invoice->payment_link ?? '') : ''; ?>" 
                placeholder="<?php echo esc_attr(get_option('fs_payment_url', 'https://paypal.me/YourName')); ?>">
            <p class="description">
                <?php 
                $global_payment_url = get_option('fs_payment_url', '');
                if (!empty($global_payment_url)) {
                    /* translators: 1. recipient name */
                    echo wp_kses_post( sprintf( __('Override the global payment link for this invoice. Leave blank to use your default: %s', 'freelance-studio'), '<code>' . esc_html($global_payment_url) . '</code>') );
                } else {
                    esc_html_e('Add a payment link to show a "Pay Now" button on the client-facing invoice. Or set a global default in Settings → Invoices.', 'freelance-studio');
                }
                ?>
            </p>
        </div>
        
        <!-- Send To Contacts Section -->
        <div class="fs-form-section fs-send-to-section" id="fs-send-to-section" style="display: none;">
            <h2><?php esc_html_e('Send To', 'freelance-studio'); ?></h2>
            <p class="description"><?php esc_html_e('Select which contacts should receive this invoice. If none selected, it will be sent to the primary client email.', 'freelance-studio'); ?></p>
            
            <div id="fs-contact-checkboxes" class="fs-contact-list">
                <!-- Populated via JavaScript when client is selected -->
            </div>
        </div>
        
        <p class="submit">
            <input type="submit" class="button button-primary" value="<?php echo  esc_attr( $is_new ? __('Create Invoice', 'freelance-studio') : __('Update Invoice', 'freelance-studio') ); ?>">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices') ); ?>" class="button"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
            <?php if (!$is_new): ?>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=view&id=' . $invoice->id) ); ?>" class="button"><?php esc_html_e('Preview', 'freelance-studio'); ?></a>
                <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=invoices&action=pdf&id=' . $invoice->id) ); ?>" class="button"><?php esc_html_e('Download PDF', 'freelance-studio'); ?></a>
            <?php endif; ?>
        </p>
    </form>
</div>

<?php 
// Get selected contacts if editing
$selected_contacts = array();
if ($invoice && !empty($invoice->send_to_contacts)) {
    $selected_contacts = json_decode($invoice->send_to_contacts, true) ?: array();
}
?>
<script>
jQuery(document).ready(function($) {
    var selectedContacts = <?php echo json_encode($selected_contacts); ?>;
    
    // Load contacts and update projects when client changes
    $('#client_id').on('change', function() {
        var clientId = $(this).val();
        var $section = $('#fs-send-to-section');
        var $container = $('#fs-contact-checkboxes');
        
        // Reload project dropdown for new client
        var $projectSelect = $('#project_id');
        var currentProjectId = $projectSelect.val();
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_get_client_projects',
                client_id: clientId,
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
            },
            success: function(response) {
                if (response.success) {
                    var html = '<option value=""><?php echo esc_js(__('No project', 'freelance-studio')); ?></option>';
                    var foundCurrent = false;
                    response.data.forEach(function(p) {
                        var sel = (p.id == currentProjectId) ? ' selected' : '';
                        if (p.id == currentProjectId) foundCurrent = true;
                        html += '<option value="' + p.id + '"' + sel + '>' + $('<span>').text(p.name).html() + '</option>';
                    });
                    $projectSelect.html(html);
                    // If previous project not in new list, reset to no project
                    if (!foundCurrent) {
                        $projectSelect.val('');
                    }
                }
            }
        });
        
        if (!clientId) {
            $section.hide();
            $container.html('');
            return;
        }
        
        // Update due date based on client's payment terms
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_get_client',
                id: clientId,
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
            },
            success: function(response) {
                if (response.success && response.data && response.data.default_payment_terms) {
                    var days = parseInt(response.data.default_payment_terms) || 30;
                    var dueDate = new Date();
                    dueDate.setDate(dueDate.getDate() + days);
                    var y = dueDate.getFullYear();
                    var m = ('0' + (dueDate.getMonth() + 1)).slice(-2);
                    var d = ('0' + dueDate.getDate()).slice(-2);
                    $('#due_date').val(y + '-' + m + '-' + d);
                }
            }
        });
        
        // Fetch contacts for this client
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_get_client_contacts',
                client_id: clientId,
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
            },
            success: function(response) {
                if (response.success && response.data.contacts && response.data.contacts.length > 0) {
                    var html = '';
                    
                    // Add primary client email if exists
                    if (response.data.primary_email) {
                        html += '<label class="fs-contact-checkbox">';
                        html += '<input type="checkbox" name="send_to_contacts[]" value="primary" checked disabled>';
                        html += '<span class="fs-contact-name">' + response.data.client_name + ' (Primary)</span>';
                        html += '<span class="fs-contact-email">' + response.data.primary_email + '</span>';
                        html += '</label>';
                    }
                    
                    response.data.contacts.forEach(function(contact) {
                        if (contact.email) {
                            var checked = selectedContacts.indexOf(parseInt(contact.id)) > -1 ? ' checked' : '';
                            html += '<label class="fs-contact-checkbox">';
                            html += '<input type="checkbox" name="send_to_contacts[]" value="' + contact.id + '"' + checked + '>';
                            html += '<span class="fs-contact-name">' + contact.name + '</span>';
                            if (contact.title) {
                                html += '<span class="fs-contact-title">' + contact.title + '</span>';
                            }
                            html += '<span class="fs-contact-email">' + contact.email + '</span>';
                            html += '</label>';
                        }
                    });
                    
                    $container.html(html);
                    $section.show();
                } else {
                    $section.hide();
                    $container.html('');
                }
            }
        });
    });
    
    // Trigger on page load if editing
    <?php if ($invoice && $invoice->client_id): ?>
    $('#client_id').trigger('change');
    <?php endif; ?>
    
    // Full Amount Paid checkbox
    $('#full_amount_paid').on('change', function() {
        if ($(this).is(':checked')) {
            // Get the current total from the total display
            var totalText = $('#total-display').text();
            var total = parseFloat(totalText.replace(/[^0-9.-]/g, '')) || 0;
            $('#amount_paid').val(total.toFixed(2));
            
            // Also set today's date for paid_date if empty
            if (!$('#paid_date').val()) {
                var today = new Date().toISOString().split('T')[0];
                $('#paid_date').val(today);
            }
        }
    });
    
    // Uncheck Full Amount Paid if amount_paid is manually changed
    $('#amount_paid').on('input', function() {
        var totalText = $('#total-display').text();
        var total = parseFloat(totalText.replace(/[^0-9.-]/g, '')) || 0;
        var amountPaid = parseFloat($(this).val()) || 0;
        
        if (Math.abs(amountPaid - total) > 0.01) {
            $('#full_amount_paid').prop('checked', false);
        }
    });
});
</script>

<script type="text/template" id="item-template">
<div class="fs-invoice-item">
    <div class="fs-form-group"><label><?php esc_html_e('Description', 'freelance-studio'); ?></label><input type="text" name="items[{index}][description]" class="item-description"></div>
    <div class="fs-form-group"><label><?php esc_html_e('Qty', 'freelance-studio'); ?></label><input type="number" name="items[{index}][quantity]" class="item-quantity" step="0.01" value="1"></div>
    <div class="fs-form-group"><label><?php esc_html_e('Rate', 'freelance-studio'); ?></label><input type="number" name="items[{index}][rate]" class="item-rate" step="0.01"></div>
    <div class="fs-form-group"><label><?php esc_html_e('Amount', 'freelance-studio'); ?></label><input type="number" name="items[{index}][amount]" class="item-amount" step="0.01" readonly></div>
    <button type="button" class="button fs-remove-item">×</button>
<?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>
</script>
