<?php

// Exit if accessed directly.
if (! defined('ABSPATH')) {
    exit;
}

include INTEGRAZO_WCZO_PLUGIN_DIR . 'src/util/advanced-fields.php';

// Group CRM fields
$general_fields = [];
$custom_fields = [];
$premium_fields = [];
global $integrazo_wczo_premium_fields_list;
$integrazo_wczo_premium_fields_list = $integrazo_wczo_advanced_fields[$to_product] ?? [];
foreach ($crm_fields as $field) {
    if (!empty($field['is_custom'])) {
        $custom_fields[] = $field;
    } elseif (in_array($field['api_name'], $integrazo_wczo_premium_fields_list, true)) {
        $premium_fields[] = $field;
    } else {
        $general_fields[] = $field;
    }
}


function render_crm_field_options($fields, $selected_value = '', $force_disable = false)
{
    global $integrazo_wczo_premium_fields_list;
    $session = integrazo_wczo_session();
    foreach ($fields as $field) {
        $is_premium     = in_array($field['api_name'], $integrazo_wczo_premium_fields_list, true);
        $should_disable = ! $session && ($is_premium || $force_disable);
?>
        <option
            value="<?php echo esc_attr($field['api_name']); ?>"
            data-type="<?php echo esc_attr($field['data_type']); ?>"
            data-picklist='<?php echo esc_attr(wp_json_encode($field['pick_list_values'] ?? [])); ?>'
            data-mandatory="<?php echo ! empty($field['system_mandatory']) ? '1' : '0'; ?>"
            <?php selected($field['api_name'], $selected_value); ?>
            <?php if (! $should_disable) : ?>
            style="color: blue;"
            <?php endif; ?>
            <?php if ($should_disable) : ?>
            title="<?php echo esc_attr__('Upgrade to Pro to use this field.', 'integrazo-wc-zoho-integration'); ?>"
            data-premium="true"
            disabled="disabled"
            <?php endif; ?>>
            <?php echo esc_html($field['field_label']); ?>
        </option>
    <?php
    }
}



function render_form_field_options($form_fields, $selected_value_input, $selected_source)
{
    $selected_value = (string) $selected_value_input;

    ?>
    <optgroup label="Form Fields">
        <?php foreach ($form_fields['form_fields'] as $form_field): ?>
            <option style="color: blue;" value="<?php echo esc_attr($form_field['name']); ?>" data-type="<?php echo esc_attr($form_field['data_type']); ?>"
                <?php echo (in_array($selected_source, ['form_field', 'option_map_form_field']) && (string) $form_field['name'] === $selected_value) ? 'selected' : ''; ?>>
                <?php echo esc_html($form_field['label']); ?>
            </option>
        <?php endforeach; ?>
    </optgroup>
    <optgroup label="System Fields">
        <?php foreach ($form_fields['system_fields'] as $sys_field): ?>
            <?php
            if (
                ($selected_value === '__map_form_field__' || $selected_source === 'option_map_form_field') &&
                $sys_field['name'] === 'custom_value'
            ) {
                continue;
            }
            ?>
            <option style="color: blue;" value="<?php echo esc_attr($sys_field['name']); ?>" data-type="system_field"
                <?php echo (
                    ($sys_field['name'] === 'custom_value' && $selected_source === 'custom_value') ||
                    ($sys_field['name'] === $selected_value && $selected_source === 'system_field')
                ) ? 'selected' : ''; ?>>
                <?php echo esc_html($sys_field['label']); ?>
            </option>
        <?php endforeach; ?>

    </optgroup>
<?php
}

function render_combined_mapping_block($mapping, $form_fields, $general_fields, $custom_fields, $premium_fields)
{
    $mapping_value = $mapping['value'] ?? '';
    $mapping_source = $mapping['source'] ?? '';
    $product_field = $mapping['product_field'] ?? '';

    $all_fields = array_merge($general_fields, $custom_fields, $premium_fields);
    $current_crm_field = null;
    foreach ($all_fields as $field) {
        if ($field['api_name'] === $product_field) {
            $current_crm_field = $field;
            break;
        }
    }

    $has_picklist = !empty($current_crm_field['pick_list_values']);

    $show_textarea = in_array($mapping_source, ['custom_value', 'option_custom_value']) || $mapping_value === '__custom_value__';
    $show_form_field = $mapping_value === '__map_form_field__' || $mapping_source === 'option_map_form_field';

?>
    <div class="integrazo-wczo-mapping-row">
        <div class="integrazo-wczo-field-left">
            <div class="integrazo-wczo-picklist-combined" style="<?php echo $has_picklist ? 'display:block;' : 'display:none;'; ?>">
                <select class="integrazo-wczo-picklist-select" name="picklist_combined[]">
                    <option value="">Select</option>
                    <?php foreach ($current_crm_field['pick_list_values'] ?? [] as $option): ?>
                        <option value="<?php echo esc_attr($option['actual_value']); ?>"
                            <?php echo ($mapping_source === 'option_value' && trim((string)$mapping_value) === trim((string)$option['actual_value'])) ? 'selected' : ''; ?>>
                            <?php echo esc_html($option['display_value']); ?>
                        </option>
                    <?php endforeach; ?>
                    <option disabled>────────────</option>
                    <option value="__custom_value__" <?php echo ($mapping_value === '__custom_value__' || $mapping_source === 'option_custom_value' || $mapping_source === 'custom_value') ? 'selected' : ''; ?>>Use a Custom Value</option>
                    <option value="__map_form_field__" <?php echo ($mapping_value === '__map_form_field__' || $mapping_source === 'option_map_form_field') ? 'selected' : ''; ?>>Map to Form Field</option>
                </select>
            </div>

            <div class="integrazo-wczo-form-field-wrapper" id="integrazo-wczo-form-field-wrapper" style="<?php echo ($has_picklist && !$show_form_field) ? 'display:none;' : ''; ?>">
                <select class="integrazo-wczo-form-field-select" name="form_fields[]">
                    <option value="">Select</option>
                    <?php render_form_field_options($form_fields, $mapping_value, $mapping_source); ?>
                </select>
            </div>

            <div class="integrazo-wczo-custom-textarea" style="<?php echo ($show_textarea) ? 'display:block;' : 'display:none;'; ?>">
                <textarea name="custom_values[]" placeholder="Enter custom value..."><?php
                                                                                        echo ($mapping_source === 'custom_value' || $mapping_source === 'option_custom_value') ? esc_textarea($mapping_value) : '';
                                                                                        ?></textarea>
            </div>


        </div>

        <div class="integrazo-wczo-field-right">
            <div class="integrazo-wczo-form-field-wrapper" style="display: flex; align-items: center; gap: 8px;">
                <select class="integrazo-wczo-crm-field-select" name="crm_fields[]" style="width: 100%;">
                    <option value="">Select</option>
                    <?php if (!empty($general_fields)): ?>
                        <optgroup label="General Fields">
                            <?php render_crm_field_options($general_fields, $product_field); ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (!empty($custom_fields)): ?>
                        <optgroup label="Custom Fields">
                            <?php render_crm_field_options($custom_fields, $product_field, true); ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (!empty($premium_fields)): ?>
                        <optgroup label="Premium Fields">
                            <?php render_crm_field_options($premium_fields, $product_field); ?>
                        </optgroup>
                    <?php endif; ?>
                </select>

                <div class="integrazo-wczo-helpicon-help-icon-wrapper integrazo-wczo-crm-help" style="<?php echo $has_picklist ? 'display:block;' : 'display:none;'; ?>">
                    <span class="integrazo-wczo-helpicon-help-icon">?</span>
                    <div class="integrazo-wczo-helpicon-help-tooltip">
                        <p><strong>This field has default options.</strong></p>
                        <p>How to use it:</p>
                        <ol>
                            <li>Choose a value from the <strong>left dropdown</strong>.</li>
                            <li>If the value you need isn’t available, scroll down and pick one of these:
                                <ul>
                                    <li><strong>Custom Value</strong> — type your own value.</li>
                                    <li><strong>Map to Form Field</strong> — link this field to one of your form fields.</li>
                                </ul>
                            </li>
                        </ol>
                        <p>You can use the ready-made options or customize as needed.</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="integrazo-wczo-actions">
            <span class="integrazo-wczo-add-row">+</span>
            <span class="integrazo-wczo-remove-field">&ndash;</span>
        </div>
    </div>
<?php
}
?>

<div class="integrazo-wczo-mapping-section">

    <div class="integrazo-wczo-mapping-table">

        <div class="integrazo-wczo-mapping-header">
            <div><?php esc_html_e('Source Field', 'integrazo-wc-zoho-integration'); ?></div>
            <div><?php esc_html_e('Target Field', 'integrazo-wc-zoho-integration'); ?></div>

        </div>
        <div id="integrazo-wczo-mapping-container">

            <!-- Mandatory Fields -->
            <?php
            foreach ($crm_fields as $crm_field):
                if (empty($crm_field['system_mandatory'])) continue;
                $selected_form_field = '';
                $selected_source = '';
                if (!empty($mandatory_mappings)) {
                    foreach ($mandatory_mappings as $mapping) {
                        if ($mapping['product_field'] === $crm_field['api_name']) {
                            $selected_form_field = $mapping['value'];
                            $selected_source = $mapping['source'];
                            break;
                        }
                    }
                }
                $mapping = [
                    'product_field' => $crm_field['api_name'],
                    'value' => $selected_form_field,
                    'source' => $selected_source
                ];
                render_combined_mapping_block($mapping, $form_fields, $general_fields, $custom_fields, $premium_fields);
            endforeach;
            ?>

            <!-- Non-Mandatory Mappings -->
            <?php
            if (!empty($non_mandatory_mappings)) {
                foreach ($non_mandatory_mappings as $mapping) {
                    render_combined_mapping_block($mapping, $form_fields, $general_fields, $custom_fields, $premium_fields);
                }
            }
            ?>

            <!-- Template Row -->
            <div class="integrazo-wczo-mapping-row" id="integrazo-wczo-template-row" style="display:none;">
                <div class="integrazo-wczo-field-left">
                    <div class="integrazo-wczo-picklist-combined" style="display:none;">
                        <select class="integrazo-wczo-picklist-select" name="picklist_combined[]"></select>
                    </div>
                    <div class="integrazo-wczo-form-field-wrapper" id="integrazo-wczo-form-field-wrapper">
                        <select class="integrazo-wczo-form-field-select" name="form_fields[]">
                            <option value="">Select</option>
                            <?php render_form_field_options($form_fields, $mapping_value, $mapping_source); ?>
                        </select>
                    </div>
                    <div class="integrazo-wczo-custom-textarea" style="display:none;">
                        <textarea name="custom_values[]" placeholder="Enter custom value..."></textarea>
                    </div>
                </div>
                <div class="integrazo-wczo-field-right">
                    <div class="integrazo-wczo-form-field-wrapper" style="display: flex; align-items: center; gap: 8px;">
                        <select class="integrazo-wczo-crm-field-select" name="crm_fields[]" style="width: 100%;">
                            <option value="">Select</option>
                            <?php if (!empty($general_fields)): ?>
                                <optgroup label="General Fields">
                                    <?php render_crm_field_options($general_fields); ?>
                                </optgroup>
                            <?php endif; ?>
                            <?php if (!empty($custom_fields)): ?>
                                <optgroup label="Custom Fields">
                                    <?php render_crm_field_options($custom_fields, '', true); ?>
                                </optgroup>
                            <?php endif; ?>
                            <?php if (!empty($premium_fields)): ?>
                                <optgroup label="Premium Fields">
                                    <?php render_crm_field_options($premium_fields); ?>
                                </optgroup>
                            <?php endif; ?>
                        </select>

                        <div class="integrazo-wczo-helpicon-help-icon-wrapper integrazo-wczo-crm-help" style="display: none !important">
                            <span class="integrazo-wczo-helpicon-help-icon">?</span>
                            <div class="integrazo-wczo-helpicon-help-tooltip">
                                <p><strong>This field has default options.</strong></p>
                                <p>How to use it:</p>
                                <ol>
                                    <li>Choose a value from the <strong>left dropdown</strong>.</li>
                                    <li>If the value you need isn’t available, scroll down and pick one of these:
                                        <ul>
                                            <li><strong>Custom Value</strong> — type your own value.</li>
                                            <li><strong>Map to Form Field</strong> — link this field to one of your form fields.</li>
                                        </ul>
                                    </li>
                                </ol>
                                <p>You can use the ready-made options or customize as needed.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="integrazo-wczo-actions">
                    <span class="integrazo-wczo-add-row">+</span>
                    <span class="integrazo-wczo-remove-field">&ndash;</span>
                </div>
            </div>

        </div>
    </div>
</div>