<?php
/**
 * Recurring Invoice Form View
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

$is_edit = !empty($recurring);
$page_title = $is_edit ? __('Edit Recurring Invoice', 'freelance-studio') : __('New Recurring Invoice', 'freelance-studio');
?>

<?php if (empty($GLOBALS['fs_in_finances'])): ?>
<div class="wrap fs-wrap">
<?php endif; ?>
    <div class="fs-breadcrumb">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring') ); ?>"><?php esc_html_e('Recurring Invoices', 'freelance-studio'); ?></a>
        <span>/</span>
        <span><?php echo  esc_html( $is_edit ? esc_html($recurring->name) : __('New', 'freelance-studio') ); ?></span>
    </div>

    <h1><?php echo  esc_html( $page_title ); ?></h1>

    <form method="post" action="" class="fs-form">
        <?php wp_nonce_field('fs_save_recurring', 'fs_recurring_nonce'); ?>
        <input type="hidden" name="recurring_id" value="<?php echo  esc_attr( $is_edit ? $recurring->id : 0 ); ?>">

        <div class="fs-form-container">
            <div class="fs-form-main">
                <!-- Basic Info -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Recurring Invoice Details', 'freelance-studio'); ?></h2>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group required">
                            <label for="name"><?php esc_html_e('Name', 'freelance-studio'); ?></label>
                            <input type="text" name="name" id="name" value="<?php echo $is_edit ? esc_attr($recurring->name) : ''; ?>" required placeholder="<?php esc_attr_e('e.g., Monthly Retainer - ABC Corp', 'freelance-studio'); ?>">
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="frequency"><?php esc_html_e('Frequency', 'freelance-studio'); ?></label>
                            <select name="frequency" id="frequency">
                                <?php foreach ($frequencies as $value => $label): ?>
                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($is_edit ? $recurring->frequency : 'monthly', $value); ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <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 $value => $label): ?>
                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($is_edit ? $recurring->status : 'active', $value); ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <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 $client): ?>
                                    <option value="<?php echo esc_attr($client->id); ?>" <?php selected($is_edit ? $recurring->client_id : '', $client->id); ?>>
                                        <?php echo esc_html($client->company_name ?: $client->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="project_id"><?php esc_html_e('Project (Optional)', 'freelance-studio'); ?></label>
                            <select name="project_id" id="project_id">
                                <option value=""><?php esc_html_e('No Project', 'freelance-studio'); ?></option>
                                <?php foreach ($projects as $project): ?>
                                    <option value="<?php echo esc_attr($project->id); ?>" <?php selected($is_edit ? $recurring->project_id : '', $project->id); ?>>
                                        <?php echo esc_html($project->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label for="next_invoice_date"><?php esc_html_e('Next Invoice Date', 'freelance-studio'); ?></label>
                            <input type="date" name="next_invoice_date" id="next_invoice_date" value="<?php echo  esc_attr( $is_edit && $recurring->next_invoice_date ? esc_attr($recurring->next_invoice_date) : gmdate('Y-m-d') ); ?>">
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="end_date"><?php esc_html_e('End Date (Optional)', 'freelance-studio'); ?></label>
                            <input type="date" name="end_date" id="end_date" value="<?php echo $is_edit && $recurring->end_date ? esc_attr($recurring->end_date) : ''; ?>">
                            <p class="description"><?php esc_html_e('Leave blank for no end date', 'freelance-studio'); ?></p>
                        </div>
                        
                        <div class="fs-form-group">
                            <label>&nbsp;</label>
                            <label class="fs-checkbox-label">
                                <input type="checkbox" name="auto_send" value="1" <?php checked($is_edit ? $recurring->auto_send : 0, 1); ?>>
                                <?php esc_html_e('Auto-send invoice when generated', 'freelance-studio'); ?>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Time Entry Auto-Population -->
                <div class="fs-form-section" id="fs-recurring-time-section">
                    <h2><?php esc_html_e('Billable Time', 'freelance-studio'); ?></h2>
                    <p class="description"><?php esc_html_e('Automatically include unbilled time entries when each invoice is generated.', 'freelance-studio'); ?></p>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label class="fs-checkbox-label">
                                <input type="checkbox" name="include_time_entries" id="include_time_entries" value="1" <?php checked($is_edit && !empty($recurring->include_time_entries), 1); ?>>
                                <?php esc_html_e('Include unbilled time entries from the billing period', 'freelance-studio'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('When the invoice is generated, all unbilled time entries for the selected project from the previous billing period will be added as line items, grouped by task.', 'freelance-studio'); ?></p>
                        </div>
                    </div>
                    
                    <div class="fs-time-entry-options" id="fs-time-entry-options" style="<?php echo ($is_edit && !empty($recurring->include_time_entries)) ? '' : 'display:none;'; ?>">
                        <div class="fs-form-row">
                            <div class="fs-form-group">
                                <label for="time_grouping"><?php esc_html_e('Group time entries by', 'freelance-studio'); ?></label>
                                <select name="time_grouping" id="time_grouping">
                                    <option value="task" <?php selected($is_edit ? ($recurring->time_grouping ?? 'task') : 'task', 'task'); ?>><?php esc_html_e('Task', 'freelance-studio'); ?></option>
                                    <option value="activity" <?php selected($is_edit ? ($recurring->time_grouping ?? '') : '', 'activity'); ?>><?php esc_html_e('Activity type', 'freelance-studio'); ?></option>
                                    <option value="entry" <?php selected($is_edit ? ($recurring->time_grouping ?? '') : '', 'entry'); ?>><?php esc_html_e('Individual entry', 'freelance-studio'); ?></option>
                                </select>
                            </div>
                            <div class="fs-form-group">
                                <label class="fs-checkbox-label" style="margin-top: 28px;">
                                    <input type="checkbox" name="mark_time_invoiced" value="1" <?php checked($is_edit ? ($recurring->mark_time_invoiced ?? 1) : 1, 1); ?>>
                                    <?php esc_html_e('Mark time entries as invoiced', 'freelance-studio'); ?>
                                </label>
                            </div>
                        </div>
                        
                        <div class="fs-info-notice">
                            <span class="dashicons dashicons-info"></span>
                            <?php esc_html_e('A project must be selected above for time entries to be included. The billing period is calculated from the invoice frequency (e.g., monthly = last 30 days).', 'freelance-studio'); ?>
                        </div>
                    </div>
                </div>

                <!-- Static Line Items -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Invoice Items', 'freelance-studio'); ?></h2>
                    <p class="description"><?php esc_html_e('These static items are included on every generated invoice. Time entries (if enabled above) are added in addition to these items.', 'freelance-studio'); ?></p>
                    
                    <div class="fs-invoice-items" id="items-container">
                        <?php 
                        if (empty($items)) {
                            $items = array(array('description' => '', 'quantity' => 1, 'rate' => '', 'amount' => 0));
                        }
                        foreach ($items as $index => $item): 
                        ?>
                        <div class="fs-invoice-item">
                            <div class="fs-form-group">
                                <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                                <input type="text" name="item_description[]" class="item-description" value="<?php echo esc_attr($item['description']); ?>" placeholder="<?php esc_attr_e('Item description', 'freelance-studio'); ?>">
                            </div>
                            <div class="fs-form-group">
                                <label><?php esc_html_e('Qty', 'freelance-studio'); ?></label>
                                <input type="number" name="item_quantity[]" class="item-qty" value="<?php echo esc_attr($item['quantity']); ?>" min="0" step="0.01">
                            </div>
                            <div class="fs-form-group">
                                <label><?php esc_html_e('Rate', 'freelance-studio'); ?></label>
                                <input type="number" name="item_rate[]" class="item-rate" value="<?php echo esc_attr($item['rate']); ?>" min="0" step="0.01" placeholder="0.00">
                            </div>
                            <div class="fs-form-group">
                                <label><?php esc_html_e('Amount', 'freelance-studio'); ?></label>
                                <span class="item-amount"><?php echo  esc_html( FS_View_Context::format_currency($item['amount'] ?? 0) ); ?></span>
                            </div>
                            <button type="button" class="button fs-remove-item">&times;</button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <button type="button" class="button" id="add-item">
                        <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Item', 'freelance-studio'); ?>
                    </button>
                    
                    <div class="fs-invoice-totals">
                        <table>
                            <tr class="totals-row">
                                <td><strong><?php esc_html_e('Total', 'freelance-studio'); ?></strong></td>
                                <td><strong id="invoice-total"><?php echo  esc_html( FS_View_Context::format_currency($is_edit ? $recurring->amount : 0) ); ?></strong></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <div class="fs-form-sidebar">
                <div class="fs-sidebar-section">
                    <h3><?php esc_html_e('Summary', 'freelance-studio'); ?></h3>
                    
                    <div class="fs-summary-item">
                        <span class="label"><?php esc_html_e('Frequency', 'freelance-studio'); ?></span>
                        <span class="value" id="summary-frequency"><?php echo  esc_html( $is_edit ? esc_html($frequencies[$recurring->frequency]) : __('Monthly', 'freelance-studio') ); ?></span>
                    </div>
                    
                    <div class="fs-summary-item">
                        <span class="label"><?php esc_html_e('Amount', 'freelance-studio'); ?></span>
                        <span class="value" id="summary-amount"><?php echo  esc_html( FS_View_Context::format_currency($is_edit ? $recurring->amount : 0) ); ?></span>
                    </div>
                    
                    <?php if ($is_edit && $recurring->invoices_generated > 0): ?>
                        <div class="fs-summary-item">
                            <span class="label"><?php esc_html_e('Invoices Generated', 'freelance-studio'); ?></span>
                            <span class="value"><?php echo intval($recurring->invoices_generated); ?></span>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="fs-sidebar-actions">
                    <button type="submit" class="fs-btn fs-btn-submit">
                        <?php echo  esc_html( $is_edit ? __('Update Recurring Invoice', 'freelance-studio') : __('Create Recurring Invoice', 'freelance-studio') ); ?>
                    </button>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-finances&tab=recurring') ); ?>" class="fs-btn fs-btn-secondary">
                        <?php esc_html_e('Cancel', 'freelance-studio'); ?>
                    </a>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
jQuery(document).ready(function($) {
    var currencySymbol = '<?php echo esc_js(get_option("fs_currency_symbol", "$")); ?>';
    
    function formatCurrency(amount) {
        return currencySymbol + parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    }
    
    function calculateTotals() {
        var total = 0;
        
        $('.fs-invoice-item').each(function() {
            var qty = parseFloat($(this).find('.item-qty').val()) || 0;
            var rate = parseFloat($(this).find('.item-rate').val()) || 0;
            var amount = qty * rate;
            
            $(this).find('.item-amount').text(formatCurrency(amount));
            total += amount;
        });
        
        $('#invoice-total').text(formatCurrency(total));
        $('#summary-amount').text(formatCurrency(total));
    }
    
    // Calculate on input change
    $(document).on('input', '.item-qty, .item-rate', calculateTotals);
    
    // Add item row
    $('#add-item').on('click', function() {
        var newRow = `
            <div class="fs-invoice-item">
                <div class="fs-form-group">
                    <label><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                    <input type="text" name="item_description[]" class="item-description" placeholder="<?php esc_attr_e('Item description', 'freelance-studio'); ?>">
                </div>
                <div class="fs-form-group">
                    <label><?php esc_html_e('Qty', 'freelance-studio'); ?></label>
                    <input type="number" name="item_quantity[]" class="item-qty" value="1" min="0" step="0.01">
                </div>
                <div class="fs-form-group">
                    <label><?php esc_html_e('Rate', 'freelance-studio'); ?></label>
                    <input type="number" name="item_rate[]" class="item-rate" min="0" step="0.01" placeholder="0.00">
                </div>
                <div class="fs-form-group">
                    <label><?php esc_html_e('Amount', 'freelance-studio'); ?></label>
                    <span class="item-amount">${currencySymbol}0.00</span>
                </div>
                <button type="button" class="button fs-remove-item">&times;</button>
            <?php if (empty($GLOBALS['fs_in_finances'])): ?>
</div>
<?php endif; ?>
        `;
        $('#items-container').append(newRow);
    });
    
    // Remove item row
    $(document).on('click', '.fs-remove-item', function() {
        if ($('.fs-invoice-item').length > 1) {
            $(this).closest('.fs-invoice-item').remove();
            calculateTotals();
        }
    });
    
    // Update frequency summary
    $('#frequency').on('change', function() {
        $('#summary-frequency').text($(this).find('option:selected').text());
    });
    
    // Initial calculation
    calculateTotals();
    
    // Toggle time entry options visibility
    $('#include_time_entries').on('change', function() {
        if ($(this).is(':checked')) {
            $('#fs-time-entry-options').slideDown(200);
            // Warn if no project selected
            if (!$('#project_id').val()) {
                $('#fs-time-no-project-warning').show();
            }
        } else {
            $('#fs-time-entry-options').slideUp(200);
        }
    });
    
    // Show/hide project warning when project changes
    $('#project_id').on('change', function() {
        if (!$(this).val() && $('#include_time_entries').is(':checked')) {
            $('#fs-time-no-project-warning').show();
        } else {
            $('#fs-time-no-project-warning').hide();
        }
    });
});
</script>
