<?php
/**
 * Client Form View (Add/Edit)
 *
 * @package Freelance_Studio
 */

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

$page_title = $is_new ? __('Add New Client', 'freelance-studio') : __('Edit Client', 'freelance-studio');

$messages = array(
    'created' => __('Client created successfully.', 'freelance-studio'),
    'updated' => __('Client updated successfully.', 'freelance-studio'),
    'error' => __('An error occurred. Please try again.', 'freelance-studio'),
);
?>

<div class="wrap fs-wrap">
    <h1><?php echo esc_html($page_title); ?></h1>
    
    <?php if ($message && isset($messages[$message])): ?>
        <div class="notice notice-<?php echo $message === 'error' ? 'error' : 'success'; ?> is-dismissible">
            <p><?php echo esc_html($messages[$message]); ?></p>
        </div>
    <?php endif; ?>
    
    <form method="post" action="">
        <?php wp_nonce_field('fs_save_client', 'fs_client_nonce'); ?>
        <input type="hidden" name="action" value="<?php echo $is_new ? 'create' : 'update'; ?>">
        <?php if (!$is_new): ?>
            <input type="hidden" name="client_id" value="<?php echo  intval( $client->id ); ?>">
        <?php endif; ?>
        
        <!-- Company Information -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Company Information', 'freelance-studio'); ?></h2>
            
            <div class="fs-form-row">
                <div class="fs-form-group fs-client-logo-group">
                    <label><?php esc_html_e('Client Logo', 'freelance-studio'); ?></label>
                    <div class="fs-logo-upload-wrapper">
                        <?php 
                        $logo_url = '';
                        if ($client) {
                            if (!empty($client->logo_url)) {
                                $logo_url = $client->logo_url;
                            } elseif (!empty($client->logo_id)) {
                                $logo_url = wp_get_attachment_image_url($client->logo_id, 'thumbnail');
                            }
                        }
                        ?>
                        <div class="fs-logo-preview <?php echo $logo_url ? 'has-logo' : ''; ?>" id="client-logo-preview">
                            <?php if ($logo_url): ?>
                                <img src="<?php echo esc_url($logo_url); ?>" alt="<?php esc_attr_e('Client logo', 'freelance-studio'); ?>">
                            <?php else: ?>
                                <span class="fs-logo-placeholder">
                                    <span class="dashicons dashicons-building"></span>
                                </span>
                            <?php endif; ?>
                        </div>
                        <div class="fs-logo-actions">
                            <button type="button" class="button fs-upload-logo-btn" id="upload-logo-btn">
                                <?php echo  esc_html( $logo_url ? __('Change Logo', 'freelance-studio') : __('Upload Logo', 'freelance-studio') ); ?>
                            </button>
                            <?php if ($logo_url): ?>
                                <button type="button" class="button fs-remove-logo-btn" id="remove-logo-btn">
                                    <?php esc_html_e('Remove', 'freelance-studio'); ?>
                                </button>
                            <?php endif; ?>
                        </div>
                        <input type="hidden" name="logo_id" id="logo_id" value="<?php echo $client && $client->logo_id ? esc_attr($client->logo_id) : ''; ?>">
                        <p class="description" style="margin-top: 10px;"><?php esc_html_e('Or enter a URL directly:', 'freelance-studio'); ?></p>
                        <input type="url" name="logo_url" id="logo_url" class="regular-text" value="<?php echo $client && !empty($client->logo_url) ? esc_attr($client->logo_url) : ''; ?>" placeholder="https://example.com/logo.png">
                    </div>
                </div>
            </div>
            
            <div class="fs-form-row">
                <div class="fs-form-group required fs-field-wide">
                    <label for="company_name"><?php esc_html_e('Company / Client Name', 'freelance-studio'); ?></label>
                    <input type="text" name="company_name" id="company_name" required
                           value="<?php echo $client ? esc_attr($client->company_name) : ''; ?>"
                           placeholder="<?php esc_attr_e('e.g., Acme Corporation or John Smith', 'freelance-studio'); ?>">
                    <p class="description"><?php esc_html_e('For individual clients without a company, enter their name here.', 'freelance-studio'); ?></p>
                </div>
                
                <div class="fs-form-group">
                    <label for="website"><?php esc_html_e('Website', 'freelance-studio'); ?></label>
                    <input type="url" name="website" id="website" placeholder="https://"
                           value="<?php echo $client ? esc_attr($client->website) : ''; ?>">
                </div>
            </div>
        </div>
        
        <!-- Address -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Address', 'freelance-studio'); ?></h2>
            
            <div class="fs-form-row">
                <div class="fs-form-group fs-field-wide">
                    <label for="address"><?php esc_html_e('Street Address', 'freelance-studio'); ?></label>
                    <input type="text" name="address" id="address"
                           value="<?php echo $client ? esc_attr($client->address) : ''; ?>">
                </div>
                
                <div class="fs-form-group fs-field-narrow">
                    <label for="address_2"><?php esc_html_e('Apt/Unit', 'freelance-studio'); ?></label>
                    <input type="text" name="address_2" id="address_2"
                           value="<?php echo $client && isset($client->address_2) ? esc_attr($client->address_2) : ''; ?>"
                           placeholder="<?php esc_attr_e('Suite 100', 'freelance-studio'); ?>">
                </div>
            </div>
            
            <div class="fs-form-row">
                <div class="fs-form-group">
                    <label for="city"><?php esc_html_e('City', 'freelance-studio'); ?></label>
                    <input type="text" name="city" id="city"
                           value="<?php echo $client ? esc_attr($client->city) : ''; ?>">
                </div>
                
                <div class="fs-form-group">
                    <label for="state"><?php esc_html_e('State/Province', 'freelance-studio'); ?></label>
                    <input type="text" name="state" id="state"
                           value="<?php echo $client ? esc_attr($client->state) : ''; ?>">
                </div>
                
                <div class="fs-form-group">
                    <label for="zip"><?php esc_html_e('ZIP/Postal Code', 'freelance-studio'); ?></label>
                    <input type="text" name="zip" id="zip"
                           value="<?php echo $client ? esc_attr($client->zip) : ''; ?>">
                </div>
                
                <div class="fs-form-group">
                    <label for="country"><?php esc_html_e('Country', 'freelance-studio'); ?></label>
                    <input type="text" name="country" id="country"
                           value="<?php echo $client ? esc_attr($client->country) : 'United States'; ?>">
                </div>
            </div>
        </div>
        
        <!-- Billing Defaults -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Billing Defaults', 'freelance-studio'); ?></h2>
            
            <div class="fs-form-row">
                <div class="fs-form-group">
                    <label for="default_hourly_rate"><?php esc_html_e('Default Hourly Rate', 'freelance-studio'); ?></label>
                    <input type="number" name="default_hourly_rate" id="default_hourly_rate" step="0.01" min="0"
                           value="<?php echo $client && $client->default_hourly_rate ? esc_attr($client->default_hourly_rate) : ''; ?>"
                           placeholder="<?php echo esc_attr(get_option('fs_default_hourly_rate', 75)); ?>">
                    <p class="description"><?php esc_html_e('Leave blank to use global default', 'freelance-studio'); ?></p>
                </div>
                
                <div class="fs-form-group">
                    <label for="payment_terms_preset"><?php esc_html_e('Payment Terms', 'freelance-studio'); ?></label>
                    <?php
                    $current_terms = $client ? intval($client->default_payment_terms) : 30;
                    $preset_options = array(7, 14, 15, 21, 30, 45, 60, 90);
                    $is_custom = !in_array($current_terms, $preset_options);
                    ?>
                    <select name="payment_terms_preset" id="payment_terms_preset">
                        <?php foreach ($preset_options as $days): ?>
                            <option value="<?php echo  esc_attr( $days ); ?>" <?php selected(!$is_custom && $current_terms === $days); ?>>
                                <?php
                                if ($days === 7) {
                                    esc_html_e('Due on Receipt (7 days)', 'freelance-studio');
                                } else {
                                    /* translators: 1. count/number */
                                    echo esc_html( sprintf( __( 'Net %d', 'freelance-studio'), $days) );
                                }
                                ?>
                            </option>
                        <?php endforeach; ?>
                        <option value="custom" <?php selected($is_custom); ?>><?php esc_html_e('Custom', 'freelance-studio'); ?></option>
                    </select>
                    <input type="number" name="default_payment_terms" id="default_payment_terms" min="0" max="365"
                           value="<?php echo esc_attr($current_terms); ?>"
                           class="fs-payment-terms-custom <?php echo $is_custom ? '' : 'fs-hidden'; ?>"
                           placeholder="<?php esc_attr_e('Days', 'freelance-studio'); ?>">
                </div>
                
                <div class="fs-form-group">
                    <label for="status"><?php esc_html_e('Status', 'freelance-studio'); ?></label>
                    <select name="status" id="status">
                        <option value="active" <?php selected($client ? $client->status : 'active', 'active'); ?>>
                            <?php esc_html_e('Active', 'freelance-studio'); ?>
                        </option>
                        <option value="inactive" <?php selected($client ? $client->status : '', 'inactive'); ?>>
                            <?php esc_html_e('Inactive', 'freelance-studio'); ?>
                        </option>
                    </select>
                </div>
            </div>
        </div>
        
        <!-- Contacts -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Contacts', 'freelance-studio'); ?></h2>
            <p class="description"><?php esc_html_e('Add contacts for this client. Mark one contact as "Primary" for invoices and contracts.', 'freelance-studio'); ?></p>
            
            <div class="fs-contacts-list">
                <?php if (!empty($contacts)): ?>
                    <?php foreach ($contacts as $i => $contact): ?>
                        <div class="fs-contact-item">
                            <input type="hidden" name="contacts[<?php echo  esc_attr( $i ); ?>][id]" value="<?php echo  intval( $contact->id ); ?>">
                            
                            <div class="fs-form-row">
                                <div class="fs-form-group">
                                    <label><?php esc_html_e('Name', 'freelance-studio'); ?></label>
                                    <input type="text" name="contacts[<?php echo  esc_attr( $i ); ?>][name]" value="<?php echo esc_attr($contact->name); ?>" required>
                                </div>
                                <div class="fs-form-group">
                                    <label><?php esc_html_e('Email', 'freelance-studio'); ?></label>
                                    <input type="email" name="contacts[<?php echo  esc_attr( $i ); ?>][email]" value="<?php echo esc_attr($contact->email); ?>">
                                </div>
                                <div class="fs-form-group">
                                    <label><?php esc_html_e('Phone', 'freelance-studio'); ?></label>
                                    <input type="tel" name="contacts[<?php echo  esc_attr( $i ); ?>][phone]" value="<?php echo esc_attr($contact->phone); ?>">
                                </div>
                                <div class="fs-form-group">
                                    <label><?php esc_html_e('Role', 'freelance-studio'); ?></label>
                                    <input type="text" name="contacts[<?php echo  esc_attr( $i ); ?>][role]" value="<?php echo esc_attr($contact->role); ?>" placeholder="e.g., Project Manager">
                                </div>
                            </div>
                            
                            <div class="fs-contact-badges">
                                <label class="fs-contact-badge-primary">
                                    <input type="radio" name="primary_contact_radio" value="<?php echo  esc_attr( $i ); ?>" <?php checked($contact->is_primary, 1); ?>>
                                    <input type="hidden" name="contacts[<?php echo  esc_attr( $i ); ?>][is_primary]" value="<?php echo  esc_attr( $contact->is_primary ? '1' : '0' ); ?>">
                                    <?php esc_html_e('Primary Contact', 'freelance-studio'); ?>
                                </label>
                                <label>
                                    <input type="checkbox" name="contacts[<?php echo  esc_attr( $i ); ?>][is_billing_contact]" value="1" <?php checked($contact->is_billing_contact, 1); ?>>
                                    <?php esc_html_e('Billing', 'freelance-studio'); ?>
                                </label>
                                <label>
                                    <input type="checkbox" name="contacts[<?php echo  esc_attr( $i ); ?>][is_project_contact]" value="1" <?php checked($contact->is_project_contact, 1); ?>>
                                    <?php esc_html_e('Project', 'freelance-studio'); ?>
                                </label>
                                <a href="#" class="fs-remove-contact">
                                    <?php esc_html_e('Remove', 'freelance-studio'); ?>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <!-- Show empty state prompting to add first contact -->
                    <div class="fs-contacts-empty-state">
                        <span class="dashicons dashicons-groups fs-empty-icon-lg"></span>
                        <p><?php esc_html_e('No contacts added yet. Add at least one contact for this client.', 'freelance-studio'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
            
            <button type="button" class="button fs-add-contact fs-mt-md">
                <?php esc_html_e('+ Add Contact', 'freelance-studio'); ?>
            </button>
        </div>
        
        <!-- Notes -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Notes', 'freelance-studio'); ?></h2>
            <div class="fs-form-group">
                <textarea name="notes" id="notes" rows="4" placeholder="<?php esc_attr_e('Internal notes about this client...', 'freelance-studio'); ?>"><?php echo $client ? esc_textarea($client->notes) : ''; ?></textarea>
            </div>
        </div>
        
        <!-- Portal Settings -->
        <div class="fs-form-section">
            <h2><?php esc_html_e('Client Portal', 'freelance-studio'); ?></h2>
            <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
                <div class="fs-pro-overlay-wrapper fs-pro-overlay-compact">
                    <div class="fs-pro-overlay">
                        <div class="fs-pro-overlay-content">
                            <span class="fs-upgrade-badge">PRO</span>
                            <p><?php esc_html_e( 'Client portals are available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                            <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                                <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                            </a>
                        </div>
                    </div>
                    <div class="fs-form-group" aria-hidden="true" style="opacity:0.5; pointer-events:none;">
                        <label>
                            <input type="checkbox" disabled>
                            <?php esc_html_e('Enable client portal access', 'freelance-studio'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('When enabled, clients can view their invoices and projects via a secure link.', 'freelance-studio'); ?></p>
                    </div>
                </div>
            <?php else: ?>
            <div class="fs-form-group">
                <label>
                    <input type="checkbox" name="portal_enabled" value="1" <?php checked($client ? $client->portal_enabled : 1, 1); ?>>
                    <?php esc_html_e('Enable client portal access', 'freelance-studio'); ?>
                </label>
                <p class="description"><?php esc_html_e('When enabled, clients can view their invoices and projects via a secure link.', 'freelance-studio'); ?></p>
            </div>
            
            <?php if (!$is_new && $client->portal_token): ?>
                <p>
                    <strong><?php esc_html_e('Portal Link:', 'freelance-studio'); ?></strong><br>
                    <code><?php echo esc_url(home_url('/client-portal/' . $client->portal_token)); ?></code>
                </p>
            <?php endif; ?>
            <?php endif; ?>
        </div>
        
        <!-- Advanced Settings -->
        <?php if (get_option('fs_internal_tracking_enabled', '0') === '1'): ?>
        <div class="fs-form-section">
            <h2><?php esc_html_e('Advanced', 'freelance-studio'); ?></h2>
            <div class="fs-form-group">
                <?php 
                $is_internal = $client && isset($client->is_internal) ? $client->is_internal : 0;
                $is_auto_internal = $client && $is_internal && FS_Client::get_internal_client() && FS_Client::get_internal_client()->id === $client->id;
                ?>
                <label>
                    <input type="checkbox" name="is_internal" value="1" <?php checked($is_internal, 1); ?> <?php echo $is_auto_internal ? 'disabled' : ''; ?>>
                    <?php esc_html_e('This is an internal/business client', 'freelance-studio'); ?>
                    <?php if ($is_auto_internal): ?>
                        <input type="hidden" name="is_internal" value="1">
                    <?php endif; ?>
                </label>
                <p class="description">
                    <?php esc_html_e('Internal clients are excluded from dashboard metrics and can be filtered in reports. Use for tracking admin tasks, professional development, or non-client work.', 'freelance-studio'); ?>
                    <?php if ($is_auto_internal): ?>
                        <br><em><?php esc_html_e('This is the auto-created internal client and cannot be changed.', 'freelance-studio'); ?></em>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <?php endif; ?>
        
        <p class="submit">
            <input type="submit" name="submit" id="submit" class="fs-btn fs-btn-submit" value="<?php echo  esc_attr( $is_new ? __('Create Client', 'freelance-studio') : __('Update Client', 'freelance-studio') ); ?>">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients') ); ?>" class="fs-btn fs-btn-secondary"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
        </p>
    </form>
</div>

<!-- Contact Template -->
<script type="text/template" id="contact-template">
    <div class="fs-contact-item">
        <div class="fs-form-row">
            <div class="fs-form-group">
                <label><?php esc_html_e('Name', 'freelance-studio'); ?></label>
                <input type="text" name="contacts[{index}][name]" value="" required>
            </div>
            <div class="fs-form-group">
                <label><?php esc_html_e('Email', 'freelance-studio'); ?></label>
                <input type="email" name="contacts[{index}][email]" value="">
            </div>
            <div class="fs-form-group">
                <label><?php esc_html_e('Phone', 'freelance-studio'); ?></label>
                <input type="tel" name="contacts[{index}][phone]" value="">
            </div>
            <div class="fs-form-group">
                <label><?php esc_html_e('Role', 'freelance-studio'); ?></label>
                <input type="text" name="contacts[{index}][role]" value="" placeholder="e.g., Project Manager">
            </div>
        </div>
        
        <div class="fs-contact-badges">
            <label class="fs-contact-badge-primary">
                <input type="radio" name="primary_contact_radio" value="{index}">
                <input type="hidden" name="contacts[{index}][is_primary]" value="0">
                <?php esc_html_e('Primary Contact', 'freelance-studio'); ?>
            </label>
            <label>
                <input type="checkbox" name="contacts[{index}][is_billing_contact]" value="1">
                <?php esc_html_e('Billing', 'freelance-studio'); ?>
            </label>
            <label>
                <input type="checkbox" name="contacts[{index}][is_project_contact]" value="1">
                <?php esc_html_e('Project', 'freelance-studio'); ?>
            </label>
            <a href="#" class="fs-remove-contact">
                <?php esc_html_e('Remove', 'freelance-studio'); ?>
            </a>
        </div>
    </div>
</script>

<script>
jQuery(document).ready(function($) {
    var mediaUploader;
    
    // Upload logo button
    $('#upload-logo-btn').on('click', function(e) {
        e.preventDefault();
        
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        
        mediaUploader = wp.media({
            title: '<?php esc_html_e('Select Client Logo', 'freelance-studio'); ?>',
            button: {
                text: '<?php esc_html_e('Use as Logo', 'freelance-studio'); ?>'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });
        
        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            
            $('#logo_id').val(attachment.id);
            $('#logo_url').val(''); // Clear URL when using Media Library
            
            var imgUrl = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            $('#client-logo-preview').addClass('has-logo').html('<img src="' + imgUrl + '" alt="<?php esc_attr_e('Client logo', 'freelance-studio'); ?>">');
            
            $('#upload-logo-btn').text('<?php esc_html_e('Change Logo', 'freelance-studio'); ?>');
            
            if ($('#remove-logo-btn').length === 0) {
                $('#upload-logo-btn').after('<button type="button" class="button fs-remove-logo-btn" id="remove-logo-btn"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>');
            }
        });
        
        mediaUploader.open();
    });
    
    // Remove logo button
    $(document).on('click', '#remove-logo-btn', function(e) {
        e.preventDefault();
        
        $('#logo_id').val('');
        $('#logo_url').val('');
        $('#client-logo-preview').removeClass('has-logo').html('<span class="fs-logo-placeholder"><span class="dashicons dashicons-building"></span></span>');
        $('#upload-logo-btn').text('<?php esc_html_e('Upload Logo', 'freelance-studio'); ?>');
        $(this).remove();
    });
    
    // Handle URL input changes
    $('#logo_url').on('change', function() {
        var url = $(this).val();
        if (url) {
            $('#logo_id').val(''); // Clear attachment ID when using URL
            $('#client-logo-preview').addClass('has-logo').html('<img src="' + url + '" alt="<?php esc_attr_e('Client logo', 'freelance-studio'); ?>">');
            $('#upload-logo-btn').text('<?php esc_html_e('Change Logo', 'freelance-studio'); ?>');
            if ($('#remove-logo-btn').length === 0) {
                $('#upload-logo-btn').after('<button type="button" class="button fs-remove-logo-btn" id="remove-logo-btn"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>');
            }
        } else if (!$('#logo_id').val()) {
            // Only reset preview if no attachment either
            $('#client-logo-preview').removeClass('has-logo').html('<span class="fs-logo-placeholder"><span class="dashicons dashicons-building"></span></span>');
            $('#upload-logo-btn').text('<?php esc_html_e('Upload Logo', 'freelance-studio'); ?>');
            $('#remove-logo-btn').remove();
        }
    });
    
    // Handle primary contact radio button changes
    $(document).on('change', 'input[name="primary_contact_radio"]', function() {
        // Reset all is_primary hidden fields to 0
        $('.fs-contact-item input[name$="[is_primary]"]').val('0');
        
        // Set the selected one to 1
        var $contactItem = $(this).closest('.fs-contact-item');
        $contactItem.find('input[name$="[is_primary]"]').val('1');
    });
    
    // Add contact button handler
    $(document).on('click', '.fs-add-contact', function(e) {
        e.preventDefault();
        
        // Hide empty state if present
        $('.fs-contacts-empty-state').hide();
        
        var template = $('#contact-template').html();
        var index = $('.fs-contact-item').length;
        template = template.replace(/\{index\}/g, index);
        
        $('.fs-contacts-list').append(template);
        
        // If this is the first contact, auto-select as primary
        if (index === 0) {
            var $newContact = $('.fs-contact-item').last();
            $newContact.find('input[name="primary_contact_radio"]').prop('checked', true).trigger('change');
        }
    });
    
    // Remove contact handler
    $(document).on('click', '.fs-remove-contact', function(e) {
        e.preventDefault();
        
        var $contactItem = $(this).closest('.fs-contact-item');
        var wasPrimary = $contactItem.find('input[name="primary_contact_radio"]').is(':checked');
        
        $contactItem.remove();
        
        // If this was the primary contact, set the first remaining contact as primary
        if (wasPrimary) {
            var $firstContact = $('.fs-contact-item').first();
            if ($firstContact.length) {
                $firstContact.find('input[name="primary_contact_radio"]').prop('checked', true).trigger('change');
            }
        }
        
        // Show empty state if no contacts left
        if ($('.fs-contact-item').length === 0) {
            $('.fs-contacts-empty-state').show();
        }
    });

    // Payment terms preset/custom toggle
    $('#payment_terms_preset').on('change', function() {
        var val = $(this).val();
        var $custom = $('#default_payment_terms');
        if (val === 'custom') {
            $custom.removeClass('fs-hidden').focus();
        } else {
            $custom.addClass('fs-hidden').val(val);
        }
    });

    // Ensure hidden field is synced before form submit
    $('form').on('submit', function() {
        var preset = $('#payment_terms_preset').val();
        if (preset !== 'custom') {
            $('#default_payment_terms').val(preset);
        }
    });
});
</script>
