<?php
/**
 * Field mapping template partial
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get current form fields from parent scope
// These are passed from form-editor.php
$current_form_fields = isset($form_fields) ? $form_fields : array();

// Get form fields
$db_handler = new SPAI_DB_Handler();
$forms = $db_handler->get_forms(array('active' => 1));

// Get saved mappings
$monday_mapping = get_option('spai_contact_form_monday_mapping', array());
$salespartner_mapping = get_option('spai_contact_form_salespartner_mapping', array());

// Get Monday settings to check if configured
$monday_settings = get_option('spai_contact_form_monday_settings', array());
$salespartner_settings = get_option('spai_contact_form_salespartner_settings', array());
?>

<div class="spai-field-mapping-container">
    <?php if (!empty($monday_settings['enabled']) && !empty($monday_settings['board_id'])): ?>
    <div class="spai-mapping-section">
        <h3><?php _e('Monday.com Field Mapping', 'spai-contact-form'); ?></h3>
        <div id="monday-field-mapping">
            <p class="description"><?php _e('Map your form fields to Monday.com columns', 'spai-contact-form'); ?></p>
            
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php _e('Form Field', 'spai-contact-form'); ?></th>
                        <th><?php _e('Monday.com Column', 'spai-contact-form'); ?></th>
                    </tr>
                </thead>
                <tbody id="monday-mapping-rows">
                    <!-- Mapping rows will be loaded here -->
                </tbody>
            </table>
            
            <button type="button" id="load-monday-columns" class="button">
                <?php _e('Load Monday Columns', 'spai-contact-form'); ?>
            </button>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($salespartner_settings['enabled'])): ?>
    <div class="spai-mapping-section">
        <h3><?php _e('SalesPartnerAI Field Mapping', 'spai-contact-form'); ?></h3>
        <div id="salespartner-field-mapping">
            <p class="description"><?php _e('Use these exact field names when creating form fields. The Field Name (not Label) determines the mapping.', 'spai-contact-form'); ?></p>
            
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php _e('Required Field Name', 'spai-contact-form'); ?></th>
                        <th><?php _e('Maps to SalesPartnerAI Field', 'spai-contact-form'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><code>first_name</code></td>
                        <td>firstName (required)</td>
                    </tr>
                    <tr>
                        <td><code>last_name</code></td>
                        <td>lastName (required)</td>
                    </tr>
                    <tr>
                        <td><code>email</code></td>
                        <td>email (required)</td>
                    </tr>
                    <tr>
                        <td><code>phone</code></td>
                        <td>phone</td>
                    </tr>
                    <tr>
                        <td><code>street</code></td>
                        <td>address.street</td>
                    </tr>
                    <tr>
                        <td><code>city</code></td>
                        <td>address.city</td>
                    </tr>
                    <tr>
                        <td><code>state</code></td>
                        <td>address.state</td>
                    </tr>
                    <tr>
                        <td><code>zip</code></td>
                        <td>address.zipCode</td>
                    </tr>
                    <tr>
                        <td><code>country</code></td>
                        <td>address.country</td>
                    </tr>
                    <tr>
                        <td><code>message</code></td>
                        <td>metadata.onlineForm.message</td>
                    </tr>
                    <tr style="background-color: #f0f0f0;">
                        <td><em>Any other field name</em></td>
                        <td>metadata.onlineForm.[field_name]</td>
                    </tr>
                </tbody>
            </table>
            
            <p class="description">
                <strong><?php _e('Important:', 'spai-contact-form'); ?></strong> <?php _e('Field mapping is automatic based on the Field Name you set when creating form fields. Labels can be anything you want users to see.', 'spai-contact-form'); ?>
            </p>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (empty($monday_settings['enabled']) && empty($salespartner_settings['enabled'])): ?>
    <p><?php _e('Please enable and configure at least one integration first.', 'spai-contact-form'); ?></p>
    <?php endif; ?>
    
    <p class="submit">
        <button type="button" id="save-field-mapping" class="button button-primary">
            <?php _e('Save Field Mapping', 'spai-contact-form'); ?>
        </button>
    </p>
</div>

<script>
jQuery(document).ready(function($) {
    // Load Monday columns
    $('#load-monday-columns').on('click', function() {
        var $button = $(this);
        $button.prop('disabled', true).text('Loading...');
        
        $.post(ajaxurl, {
            action: 'spai_get_monday_columns',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            api_key: '<?php echo esc_js($monday_settings['api_key'] ?? ''); ?>',
            board_id: '<?php echo esc_js($monday_settings['board_id'] ?? ''); ?>'
        }, function(response) {
            if (response.success) {
                var columns = response.data;
                var html = '';
                
                // Build mapping rows
                <?php if (!empty($current_form_fields)): ?>
                    <?php 
                    foreach ($current_form_fields as $field): 
                    ?>
                    html += '<tr>';
                    html += '<td><?php echo esc_js($field['label']); ?> (<?php echo esc_js($field['name']); ?>)</td>';
                    html += '<td><select name="monday_mapping[<?php echo esc_js($field['name']); ?>]" class="monday-column-select">';
                    html += '<option value="">-- Not mapped --</option>';
                    
                    $.each(columns, function(i, column) {
                        html += '<option value="' + column.id + '">' + column.title + ' (' + column.type + ')</option>';
                    });
                    
                    html += '</select></td>';
                    html += '</tr>';
                    <?php endforeach; ?>
                <?php endif; ?>
                
                $('#monday-mapping-rows').html(html);
                $button.text('Columns Loaded!');
                
                // Restore saved mappings
                <?php foreach ($monday_mapping as $field => $column): ?>
                $('select[name="monday_mapping[<?php echo esc_js($field); ?>]"]').val('<?php echo esc_js($column); ?>');
                <?php endforeach; ?>
            } else {
                alert('Failed to load Monday columns: ' + (response.data || 'Unknown error'));
                $button.prop('disabled', false).text('Load Monday Columns');
            }
        });
    });
    
    // Save field mapping
    $('#save-field-mapping').on('click', function() {
        var mondayMapping = {};
        $('.monday-column-select').each(function() {
            var name = $(this).attr('name');
            var match = name.match(/monday_mapping\[(.+)\]/);
            if (match && $(this).val()) {
                mondayMapping[match[1]] = $(this).val();
            }
        });
        
        $.post(ajaxurl, {
            action: 'spai_save_field_mapping',
            nonce: '<?php echo wp_create_nonce('spai_admin_nonce'); ?>',
            monday_mapping: mondayMapping
        }, function(response) {
            if (response.success) {
                alert('Field mapping saved successfully!');
            } else {
                alert('Failed to save field mapping');
            }
        });
    });
    
    // Auto-load columns if settings exist
    <?php if (!empty($monday_settings['board_id'])): ?>
    $('#load-monday-columns').trigger('click');
    <?php endif; ?>
});
</script>