<?php
/**
 * Contract Form View
 */
if (!defined('ABSPATH')) exit;

// Ensure proposal is defined (might be null when editing existing contract)
$proposal = isset($proposal) ? $proposal : null;

$page_title = $is_new ? __('New Contract', 'freelance-studio') : __('Edit Contract', 'freelance-studio');
$services = $contract ? $contract->services : ($proposal ? $proposal->services : array());
$terms_content = $contract ? $contract->terms_content : ($default_terms ?? FS_Contract::get_default_terms());
?>
<div class="wrap fs-wrap">
    <div class="fs-page-header">
        <h1><?php echo esc_html($page_title); ?></h1>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts') ); ?>" class="button"><?php esc_html_e('← Back to Contracts', 'freelance-studio'); ?></a>
    </div>
    
    <?php if ($proposal): ?>
    <div class="notice notice-info">
        <?php /* translators: 1. date/time */ ?>
        <p><?php echo wp_kses_post( sprintf( __('Creating contract from proposal: <strong>%s</strong>', 'freelance-studio'), esc_html($proposal->title))); ?></p>
    </div>
    <?php endif; ?>
    
    <form method="post" id="fs-contract-form">
        <?php wp_nonce_field('fs_save_contract', 'fs_contract_nonce'); ?>
        <input type="hidden" name="action" value="<?php echo $is_new ? 'create' : 'update'; ?>">
        <?php if (!$is_new): ?>
            <input type="hidden" name="contract_id" value="<?php echo  intval( $contract->id ); ?>">
        <?php endif; ?>
        <?php if ($proposal): ?>
            <input type="hidden" name="proposal_id" value="<?php echo  intval( $proposal->id ); ?>">
        <?php endif; ?>
        
        <div class="fs-form-grid">
            <!-- Main Column -->
            <div class="fs-form-main">
                <!-- Basic Info -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Contract Details', 'freelance-studio'); ?></h2>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group required" style="flex: 2;">
                            <label for="title"><?php esc_html_e('Contract Title', 'freelance-studio'); ?></label>
                            <input type="text" name="title" id="title" required
                                   value="<?php echo $contract ? esc_attr($contract->title) : ($proposal ? esc_attr($proposal->title) : ''); ?>"
                                   placeholder="<?php esc_attr_e('e.g., Website Redesign Agreement', 'freelance-studio'); ?>">
                        </div>
                        <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($contract ? $contract->client_id : ($selected_client_id ?? 0), $c->id); ?>>
                                        <?php echo esc_html($c->company_name ?: $c->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Client Contact Override -->
                    <div class="fs-form-row fs-contract-contact-section" id="fs-contract-contact-section" style="<?php 
                        $show_contact_section = false;
                        if ($contract && (!empty($contract->contact_name) || !empty($contract->client_contact_id))) {
                            $show_contact_section = true;
                        } elseif ($contract && $contract->client_id) {
                            $show_contact_section = true;
                        } elseif (!empty($selected_client_id)) {
                            $show_contact_section = true;
                        }
                        echo $show_contact_section ? '' : 'display:none;'; 
                    ?>">
                        <div class="fs-form-group">
                            <label for="client_contact_id"><?php esc_html_e('Client Contact', 'freelance-studio'); ?></label>
                            <select name="client_contact_id" id="client_contact_id">
                                <option value=""><?php esc_html_e('— Use default client info —', 'freelance-studio'); ?></option>
                                <option value="custom" <?php echo ($contract && empty($contract->client_contact_id) && !empty($contract->contact_name)) ? 'selected' : ''; ?>><?php esc_html_e('✏️ Custom contact...', 'freelance-studio'); ?></option>
                                <?php
                                // Pre-populate contacts if editing an existing contract with a client
                                $preload_client_id = $contract ? $contract->client_id : ($selected_client_id ?? 0);
                                if ($preload_client_id && class_exists('FS_Client_Contact')) {
                                    $preload_contacts = FS_Client_Contact::get_by_client($preload_client_id);
                                    foreach ($preload_contacts as $pc) {
                                        $pc_label = esc_html($pc->name);
                                        if (!empty($pc->role)) $pc_label .= ' (' . esc_html($pc->role) . ')';
                                        if ($pc->is_primary) $pc_label .= ' ★';
                                        printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            '<option value="%d" %s>%s</option>',
                                            $pc->id, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                            selected($contract ? $contract->client_contact_id : 0, $pc->id, false),
                                            $pc_label // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                        );
                                    }
                                }
                                ?>
                            </select>
                            <p class="description"><?php esc_html_e('Choose who appears as the client contact on this contract. Leave as default to use the client\'s primary info.', 'freelance-studio'); ?></p>
                        </div>
                    </div>
                    
                    <div class="fs-form-row fs-contract-contact-fields" id="fs-contract-contact-fields" style="<?php echo ($contract && !empty($contract->contact_name)) ? '' : 'display:none;'; ?>">
                        <div class="fs-form-group">
                            <label for="contact_name"><?php esc_html_e('Contact Name', 'freelance-studio'); ?></label>
                            <input type="text" name="contact_name" id="contact_name"
                                   value="<?php echo $contract ? esc_attr($contract->contact_name) : ''; ?>"
                                   placeholder="<?php esc_attr_e('e.g., Jane Smith', 'freelance-studio'); ?>">
                        </div>
                        <div class="fs-form-group">
                            <label for="contact_email"><?php esc_html_e('Contact Email', 'freelance-studio'); ?></label>
                            <input type="email" name="contact_email" id="contact_email"
                                   value="<?php echo $contract ? esc_attr($contract->contact_email) : ''; ?>"
                                   placeholder="<?php esc_attr_e('e.g., jane@company.com', 'freelance-studio'); ?>">
                        </div>
                        <div class="fs-form-group">
                            <label for="contact_phone"><?php esc_html_e('Contact Phone', 'freelance-studio'); ?></label>
                            <input type="text" name="contact_phone" id="contact_phone"
                                   value="<?php echo $contract ? esc_attr($contract->contact_phone) : ''; ?>"
                                   placeholder="<?php esc_attr_e('e.g., 555-123-4567', 'freelance-studio'); ?>">
                        </div>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label for="start_date"><?php esc_html_e('Start Date', 'freelance-studio'); ?></label>
                            <input type="date" name="start_date" id="start_date"
                                   value="<?php echo $contract ? esc_attr($contract->start_date) : ($proposal ? esc_attr($proposal->start_date) : ''); ?>">
                        </div>
                        <div class="fs-form-group">
                            <label for="end_date"><?php esc_html_e('End Date', 'freelance-studio'); ?></label>
                            <input type="date" name="end_date" id="end_date"
                                   value="<?php echo $contract ? esc_attr($contract->end_date) : ''; ?>">
                        </div>
                        <div class="fs-form-group">
                            <label for="valid_until"><?php esc_html_e('Valid Until', 'freelance-studio'); ?></label>
                            <input type="date" name="valid_until" id="valid_until"
                                   value="<?php echo  esc_attr( $contract ? esc_attr($contract->valid_until) : gmdate('Y-m-d', strtotime('+' . ($default_valid_days ?? 30) . ' days')) ); ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Services -->
                <div class="fs-form-section">
                    <div class="fs-section-header">
                        <h2><?php esc_html_e('Services', 'freelance-studio'); ?></h2>
                        <button type="button" class="button fs-add-service-btn"><?php esc_html_e('+ Add Service', 'freelance-studio'); ?></button>
                    </div>
                    
                    <div id="fs-services-container">
                        <?php if (!empty($services)): ?>
                            <?php foreach ($services as $index => $service): ?>
                                <div class="fs-service-item" data-index="<?php echo  esc_attr( $index ); ?>">
                                    <div class="fs-service-header">
                                        <span class="fs-service-drag">☰</span>
                                        <input type="text" name="services[<?php echo  esc_attr( $index ); ?>][name]" 
                                               class="fs-service-name" placeholder="<?php esc_attr_e('Service name', 'freelance-studio'); ?>"
                                               value="<?php echo esc_attr($service['name']); ?>">
                                        <button type="button" class="fs-remove-service" title="<?php esc_attr_e('Remove', 'freelance-studio'); ?>">×</button>
                                    </div>
                                    <div class="fs-service-body">
                                        <textarea name="services[<?php echo  esc_attr( $index ); ?>][description]" 
                                                  class="fs-service-description" rows="2"
                                                  placeholder="<?php esc_attr_e('Description (optional)', 'freelance-studio'); ?>"><?php echo esc_textarea($service['description'] ?? ''); ?></textarea>
                                        <div class="fs-service-pricing">
                                            <select name="services[<?php echo  esc_attr( $index ); ?>][pricing_type]" class="fs-service-pricing-type">
                                                <option value="fixed" <?php selected($service['pricing_type'] ?? 'fixed', 'fixed'); ?>><?php esc_html_e('Flat fee', 'freelance-studio'); ?></option>
                                                <option value="hourly" <?php selected($service['pricing_type'] ?? '', 'hourly'); ?>><?php esc_html_e('Hourly', 'freelance-studio'); ?></option>
                                            </select>
                                            <div class="fs-pricing-fields">
                                                <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][rate]" 
                                                       class="fs-service-rate" step="0.01" min="0"
                                                       placeholder="<?php esc_attr_e('Rate', 'freelance-studio'); ?>"
                                                       value="<?php echo esc_attr($service['rate'] ?? ''); ?>">
                                                <span class="fs-pricing-separator">×</span>
                                                <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][quantity]" 
                                                       class="fs-service-quantity" step="0.01" min="0"
                                                       placeholder="<?php esc_attr_e('Qty', 'freelance-studio'); ?>"
                                                       value="<?php echo esc_attr($service['quantity'] ?? 1); ?>">
                                                <span class="fs-pricing-separator">=</span>
                                                <input type="number" name="services[<?php echo  esc_attr( $index ); ?>][amount]" 
                                                       class="fs-service-amount" step="0.01" min="0" readonly
                                                       value="<?php echo esc_attr($service['amount'] ?? ''); ?>">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <div class="fs-services-actions">
                        <button type="button" class="button fs-add-service-btn">➕ <?php esc_html_e('Add Service', 'freelance-studio'); ?></button>
                        <span class="fs-services-actions-divider">|</span>
                        <select id="fs-load-preset-service" class="fs-preset-service-select">
                            <option value=""><?php esc_html_e('— Load Preset Service —', 'freelance-studio'); ?></option>
                        </select>
                    </div>
                    
                    <div class="fs-services-total">
                        <span><?php esc_html_e('Total:', 'freelance-studio'); ?></span>
                        <span id="fs-proposal-total">$<?php echo number_format($contract ? $contract->total_amount : ($proposal ? $proposal->total_amount : 0), 2); ?></span>
                    </div>
                </div>
                
                <!-- Billing Schedule -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Billing Schedule', 'freelance-studio'); ?></h2>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label for="billing_frequency"><?php esc_html_e('Billing Frequency', 'freelance-studio'); ?></label>
                            <select name="billing_frequency" id="billing_frequency">
                                <?php foreach ($frequencies as $k => $l): ?>
                                    <option value="<?php echo esc_attr($k); ?>" <?php selected($contract ? $contract->billing_frequency : ($proposal ? $proposal->billing_frequency : 'once'), $k); ?>>
                                        <?php echo esc_html($l); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="fs-form-group fs-first-invoice-field">
                            <label for="first_invoice_date"><?php esc_html_e('First Invoice Date', 'freelance-studio'); ?></label>
                            <input type="date" name="first_invoice_date" id="first_invoice_date"
                                   value="<?php echo $contract ? esc_attr($contract->first_invoice_date) : ($proposal ? esc_attr($proposal->first_invoice_date) : ''); ?>">
                        </div>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label>
                                <input type="checkbox" name="deposit_required" id="deposit_required" value="1"
                                       <?php checked($contract ? $contract->deposit_required : ($proposal ? $proposal->deposit_required : 0), 1); ?>>
                                <?php esc_html_e('Require deposit', 'freelance-studio'); ?>
                            </label>
                        </div>
                    </div>
                    
                    <div class="fs-deposit-fields" style="<?php echo (($contract && $contract->deposit_required) || ($proposal && $proposal->deposit_required)) ? '' : 'display:none;'; ?>">
                        <div class="fs-form-row">
                            <div class="fs-form-group">
                                <label for="deposit_type"><?php esc_html_e('Deposit Type', 'freelance-studio'); ?></label>
                                <select name="deposit_type" id="deposit_type">
                                    <option value="percentage" <?php selected($contract ? $contract->deposit_type : ($proposal ? $proposal->deposit_type : 'percentage'), 'percentage'); ?>><?php esc_html_e('Percentage', 'freelance-studio'); ?></option>
                                    <option value="fixed" <?php selected($contract ? $contract->deposit_type : ($proposal ? $proposal->deposit_type : ''), 'fixed'); ?>><?php esc_html_e('Fixed Amount', 'freelance-studio'); ?></option>
                                </select>
                            </div>
                            <div class="fs-form-group">
                                <label for="deposit_value"><?php esc_html_e('Deposit Amount', 'freelance-studio'); ?></label>
                                <input type="number" name="deposit_value" id="deposit_value" step="0.01" min="0"
                                       value="<?php echo $contract ? esc_attr($contract->deposit_value) : ($proposal ? esc_attr($proposal->deposit_value) : '50'); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Terms & Conditions -->
                <div class="fs-form-section">
                    <div class="fs-section-header">
                        <h2><?php esc_html_e('Terms & Conditions', 'freelance-studio'); ?></h2>
                        <div>
                            <button type="button" class="button" id="fs-select-all-sections"><?php esc_html_e('Select All', 'freelance-studio'); ?></button>
                            <button type="button" class="button" id="fs-select-required-sections"><?php esc_html_e('Required Only', 'freelance-studio'); ?></button>
                        </div>
                    </div>
                    <p class="description"><?php esc_html_e('Select which terms and conditions sections to include in this contract. Required sections cannot be removed.', 'freelance-studio'); ?></p>
                    
                    <?php 
                    // Get all available sections
                    $all_sections = array();
                    if (class_exists('FS_Contract_Section')) {
                        $all_sections = FS_Contract_Section::get_all();
                    }
                    
                    // Get enabled sections for this contract
                    if ($contract && !empty($all_sections)) {
                        $enabled_sections = FS_Contract::get_enabled_sections($contract);
                    } elseif (!empty($all_sections)) {
                        $enabled_sections = FS_Contract::get_default_enabled_sections();
                    } else {
                        $enabled_sections = array();
                    }
                    ?>
                    
                    <?php if (empty($all_sections)): ?>
                        <div class="notice notice-warning inline">
                            <p><?php esc_html_e('Contract sections have not been set up yet. Please deactivate and reactivate the plugin, or visit the Settings page to initialize the contract template.', 'freelance-studio'); ?></p>
                        </div>
                    <?php else: ?>
                    <div class="fs-contract-sections-list">
                        <?php foreach ($all_sections as $section): 
                            $is_enabled = in_array($section->section_key, $enabled_sections);
                            $is_required = $section->is_required;
                        ?>
                            <div class="fs-contract-section-item <?php echo $is_required ? 'is-required' : ''; ?> <?php echo $is_enabled ? 'is-enabled' : ''; ?>">
                                <label class="fs-section-checkbox">
                                    <input type="checkbox" 
                                           name="enabled_sections[]" 
                                           value="<?php echo esc_attr($section->section_key); ?>"
                                           <?php checked($is_enabled); ?>
                                           <?php echo $is_required ? 'disabled' : ''; ?>>
                                    <?php if ($is_required): ?>
                                        <input type="hidden" name="enabled_sections[]" value="<?php echo esc_attr($section->section_key); ?>">
                                    <?php endif; ?>
                                    <span class="fs-section-title">
                                        <?php echo esc_html($section->title); ?>
                                        <?php if ($is_required): ?>
                                            <span class="fs-required-badge"><?php esc_html_e('Required', 'freelance-studio'); ?></span>
                                        <?php endif; ?>
                                    </span>
                                </label>
                                <button type="button" class="fs-section-preview-btn" data-section="<?php echo esc_attr($section->section_key); ?>" title="<?php esc_attr_e('Preview', 'freelance-studio'); ?>">
                                    <span class="dashicons dashicons-visibility"></span>
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="fs-section-preview-area" id="fs-section-preview" style="display: none;">
                        <div class="fs-preview-header">
                            <h4 id="fs-preview-section-title"></h4>
                            <button type="button" class="fs-close-preview">&times;</button>
                        </div>
                        <div class="fs-preview-content" id="fs-preview-section-content"></div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Notes -->
                <div class="fs-form-section">
                    <h2><?php esc_html_e('Notes', 'freelance-studio'); ?></h2>
                    
                    <div class="fs-form-group">
                        <label for="notes"><?php esc_html_e('Client-Facing Notes', 'freelance-studio'); ?></label>
                        <textarea name="notes" id="notes" rows="4" placeholder="<?php esc_attr_e('Notes that will appear on the contract...', 'freelance-studio'); ?>"><?php echo $contract ? esc_textarea($contract->notes) : ($proposal ? esc_textarea($proposal->notes) : ''); ?></textarea>
                    </div>
                    
                    <div class="fs-form-group">
                        <label for="internal_notes"><?php esc_html_e('Internal Notes', 'freelance-studio'); ?></label>
                        <textarea name="internal_notes" id="internal_notes" rows="3" placeholder="<?php esc_attr_e('Private notes (not shown to client)...', 'freelance-studio'); ?>"><?php echo $contract ? esc_textarea($contract->internal_notes) : ''; ?></textarea>
                    </div>
                </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 contract. 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>
            </div>
            
            <!-- Sidebar -->
            <div class="fs-form-sidebar">
                <div class="fs-form-section">
                    <h3><?php esc_html_e('Actions', 'freelance-studio'); ?></h3>
                    <input type="submit" class="fs-btn fs-btn-submit fs-full-width" 
                           value="<?php echo  esc_attr( $is_new ? __('Create Contract', 'freelance-studio') : __('Update Contract', 'freelance-studio') ); ?>">
                    
                    <?php if (!$is_new): ?>
                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-contracts&action=view&id=' . $contract->id) ); ?>" 
                           class="fs-btn fs-btn-secondary fs-full-width" style="margin-top: 10px;">
                            <?php esc_html_e('Preview Contract', 'freelance-studio'); ?>
                        </a>
                    <?php endif; ?>
                </div>
                
                <?php if (!$is_new): ?>
                <div class="fs-form-section">
                    <h3><?php esc_html_e('Contract Info', 'freelance-studio'); ?></h3>
                    <div class="fs-info-list">
                        <div class="fs-info-item">
                            <span class="fs-info-label"><?php esc_html_e('Contract #', 'freelance-studio'); ?></span>
                            <span class="fs-info-value"><?php echo esc_html($contract->contract_number); ?></span>
                        </div>
                        <div class="fs-info-item">
                            <span class="fs-info-label"><?php esc_html_e('Status', 'freelance-studio'); ?></span>
                            <span class="fs-info-value"><?php echo  wp_kses_post( FS_View_Context::status_badge($contract->status) ); ?></span>
                        </div>
                        <div class="fs-info-item">
                            <span class="fs-info-label"><?php esc_html_e('Created', 'freelance-studio'); ?></span>
                            <span class="fs-info-value"><?php echo  esc_html( FS_View_Context::format_date($contract->created_at) ); ?></span>
                        </div>
                        <?php if ($contract->sent_at): ?>
                        <div class="fs-info-item">
                            <span class="fs-info-label"><?php esc_html_e('Sent', 'freelance-studio'); ?></span>
                            <span class="fs-info-value"><?php echo  esc_html( FS_View_Context::format_date($contract->sent_at) ); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($contract->signed_at): ?>
                        <div class="fs-info-item">
                            <span class="fs-info-label"><?php esc_html_e('Signed', 'freelance-studio'); ?></span>
                            <span class="fs-info-value"><?php echo  esc_html( FS_View_Context::format_date($contract->signed_at) ); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="fs-form-section">
                    <h3><?php esc_html_e('Quick Summary', 'freelance-studio'); ?></h3>
                    <div class="fs-sidebar-summary">
                        <div class="fs-summary-row">
                            <span><?php esc_html_e('Services Total:', 'freelance-studio'); ?></span>
                            <strong id="fs-sidebar-total">$<?php echo number_format($contract ? $contract->total_amount : ($proposal ? $proposal->total_amount : 0), 2); ?></strong>
                        </div>
                        <div class="fs-summary-row fs-deposit-summary" style="display: none;">
                            <span><?php esc_html_e('Deposit:', 'freelance-studio'); ?></span>
                            <span id="fs-sidebar-deposit">$0.00</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- Service Template -->
<template id="fs-service-template">
    <div class="fs-service-item" data-index="__INDEX__">
        <div class="fs-service-header">
            <span class="fs-service-drag">☰</span>
            <input type="text" name="services[__INDEX__][name]" 
                   class="fs-service-name" placeholder="<?php esc_attr_e('Service name', 'freelance-studio'); ?>">
            <button type="button" class="fs-remove-service" title="<?php esc_attr_e('Remove', 'freelance-studio'); ?>">×</button>
        </div>
        <div class="fs-service-body">
            <textarea name="services[__INDEX__][description]" 
                      class="fs-service-description" rows="2"
                      placeholder="<?php esc_attr_e('Description (optional)', 'freelance-studio'); ?>"></textarea>
            <div class="fs-service-pricing">
                <select name="services[__INDEX__][pricing_type]" class="fs-service-pricing-type">
                    <option value="fixed"><?php esc_html_e('Flat fee', 'freelance-studio'); ?></option>
                    <option value="hourly"><?php esc_html_e('Hourly', 'freelance-studio'); ?></option>
                </select>
                <div class="fs-pricing-fields">
                    <input type="number" name="services[__INDEX__][rate]" 
                           class="fs-service-rate" step="0.01" min="0"
                           placeholder="<?php esc_attr_e('Rate', 'freelance-studio'); ?>">
                    <span class="fs-pricing-separator">×</span>
                    <input type="number" name="services[__INDEX__][quantity]" 
                           class="fs-service-quantity" step="0.01" min="0" value="1"
                           placeholder="<?php esc_attr_e('Qty', 'freelance-studio'); ?>">
                    <span class="fs-pricing-separator">=</span>
                    <input type="number" name="services[__INDEX__][amount]" 
                           class="fs-service-amount" step="0.01" min="0" readonly>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
jQuery(document).ready(function($) {
    // Section data for previews
    var sectionData = <?php 
        $section_data = array();
        if (!empty($all_sections)) {
            foreach ($all_sections as $section) {
                $section_data[$section->section_key] = array(
                    'title' => $section->title,
                    'content' => $section->content,
                );
            }
        }
        echo json_encode($section_data);
    ?>;
    
    // Select all sections
    $('#fs-select-all-sections').on('click', function(e) {
        e.preventDefault();
        $('.fs-contract-section-item input[type="checkbox"]:not(:disabled)').prop('checked', true);
        updateSectionStates();
    });
    
    // Select required only
    $('#fs-select-required-sections').on('click', function(e) {
        e.preventDefault();
        $('.fs-contract-section-item input[type="checkbox"]:not(:disabled)').prop('checked', false);
        updateSectionStates();
    });
    
    // Update visual states
    function updateSectionStates() {
        $('.fs-contract-section-item').each(function() {
            var $item = $(this);
            var $checkbox = $item.find('input[type="checkbox"]');
            if ($checkbox.is(':checked') || $checkbox.is(':disabled')) {
                $item.addClass('is-enabled');
            } else {
                $item.removeClass('is-enabled');
            }
        });
    }
    
    // Toggle checkbox
    $('.fs-contract-section-item input[type="checkbox"]').on('change', function() {
        updateSectionStates();
    });
    
    // Preview section - must use event delegation since buttons are inside form
    $(document).on('click', '.fs-section-preview-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var sectionKey = $(this).data('section');
        var section = sectionData[sectionKey];
        
        if (section) {
            $('#fs-preview-section-title').text(section.title);
            $('#fs-preview-section-content').html(section.content);
            $('#fs-section-preview').slideDown(200);
            
            // Scroll to preview
            $('html, body').animate({
                scrollTop: $('#fs-section-preview').offset().top - 100
            }, 300);
        }
    });
    
    // Close preview
    $(document).on('click', '.fs-close-preview', function(e) {
        e.preventDefault();
        $('#fs-section-preview').slideUp(200);
    });

    // === Client Contact Override ===
    
    // When client changes, load their contacts into the contact selector
    $('#client_id').on('change', function() {
        var clientId = $(this).val();
        var $section = $('#fs-contract-contact-section');
        var $select = $('#client_contact_id');
        var $fields = $('#fs-contract-contact-fields');
        
        // Clear existing contact options (keep default + custom)
        $select.find('option').not('[value=""], [value="custom"]').remove();
        
        // Clear the override fields
        $('#contact_name, #contact_email, #contact_phone').val('');
        $fields.hide();
        $select.val('');
        
        if (!clientId) {
            $section.hide();
            return;
        }
        
        // Load contacts for this client
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_get_client_contacts',
                client_id: clientId,
                nonce: fs_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data.contacts && response.data.contacts.length > 0) {
                    $.each(response.data.contacts, function(i, contact) {
                        var label = contact.name;
                        if (contact.title) label += ' (' + contact.title + ')';
                        if (contact.is_primary == 1) label += ' ★';
                        $select.append(
                            $('<option></option>').val(contact.id).text(label)
                                .data('name', contact.name)
                                .data('email', contact.email)
                                .data('phone', contact.phone)
                        );
                    });
                }
                $section.show();
            }
        });
    });
    
    // When contact selector changes
    $('#client_contact_id').on('change', function() {
        var val = $(this).val();
        var $fields = $('#fs-contract-contact-fields');
        
        if (val === '') {
            // Default client info — hide and clear fields
            $fields.hide();
            $('#contact_name, #contact_email, #contact_phone').val('');
        } else if (val === 'custom') {
            // Custom — show empty fields for manual entry
            $fields.show();
            $('#contact_name, #contact_email, #contact_phone').val('');
            $('#contact_name').focus();
        } else {
            // Existing contact — show fields populated with contact data
            $fields.show();
            var $option = $(this).find('option:selected');
            $('#contact_name').val($option.data('name') || '');
            $('#contact_email').val($option.data('email') || '');
            $('#contact_phone').val($option.data('phone') || '');
        }
    });
    
    // If editing with a client already selected, show the section
    <?php if (($contract && $contract->client_id) || ($selected_client_id ?? 0)): ?>
    (function() {
        var $section = $('#fs-contract-contact-section');
        var $select = $('#client_contact_id');
        // Attach data attributes to pre-populated options
        $select.find('option').not('[value=""], [value="custom"]').each(function() {
            // These will be re-populated by AJAX if client changes, but for initial load we need data attrs
        });
        $section.show();
        
        // If there are existing contact override values, ensure the fields are visible
        <?php if ($contract && !empty($contract->contact_name)): ?>
        $('#fs-contract-contact-fields').show();
        <?php endif; ?>
    })();
    <?php endif; ?>
    
    // Trigger initial contact load to attach data attributes if client is pre-selected
    <?php if (($contract && $contract->client_id) || ($selected_client_id ?? 0)): ?>
    (function() {
        var clientId = $('#client_id').val();
        if (!clientId) return;
        var savedContactId = '<?php echo $contract ? esc_js($contract->client_contact_id) : ''; ?>';
        var savedContactName = '<?php echo $contract ? esc_js($contract->contact_name) : ''; ?>';
        
        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_get_client_contacts',
                client_id: clientId,
                nonce: fs_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data.contacts && response.data.contacts.length > 0) {
                    var $select = $('#client_contact_id');
                    $select.find('option').not('[value=""], [value="custom"]').remove();
                    $.each(response.data.contacts, function(i, contact) {
                        var label = contact.name;
                        if (contact.title) label += ' (' + contact.title + ')';
                        if (contact.is_primary == 1) label += ' ★';
                        $select.append(
                            $('<option></option>').val(contact.id).text(label)
                                .data('name', contact.name)
                                .data('email', contact.email)
                                .data('phone', contact.phone)
                        );
                    });
                    // Restore saved selection
                    if (savedContactId) {
                        $select.val(savedContactId);
                    } else if (savedContactName) {
                        $select.val('custom');
                    }
                }
            }
        });
    })();
    <?php endif; ?>
});
</script>
