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

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

global $integrazo_wz_premium_fields_list;
$integrazo_wz_premium_fields_list = $integrazo_wz_advanced_fields[$integrazo_wz_to_product] ?? [];

/**
 * Render form field options
 *
 * @param array  $form_fields       Form and system fields.
 * @param string $selected_value    Selected field value.
 * @param string $selected_source   Selected source type.
 */
function integrazo_wz_render_form_field_options($form_fields, $selected_value, $selected_source)
{
    if (!empty($form_fields['form_fields'])) {
        echo '<optgroup label="Form Fields">';
        foreach ($form_fields['form_fields'] as $form_field) {
            $selected = (
                in_array($selected_source, ['form_field', 'option_map_form_field'], true) &&
                $form_field['name'] === $selected_value
            ) ? 'selected' : '';

            echo '<option style="color: blue;" value="' . esc_attr($form_field['name']) . '" data-type="' . esc_attr($form_field['data_type']) . '" ' . esc_attr($selected) . '>' .
                esc_html($form_field['label']) .
                '</option>';
        }
        echo '</optgroup>';
    }

    if (!empty($form_fields['system_fields'])) {
        echo '<optgroup label="System Fields">';
        foreach ($form_fields['system_fields'] as $sys_field) {
            $selected = (
                ('custom_value' === $sys_field['name'] && 'custom_value' === $selected_source) ||
                ($sys_field['name'] === $selected_value && 'system_field' === $selected_source)
            ) ? 'selected' : '';

            echo '<option style="color: blue;" value="' . esc_attr($sys_field['name']) . '" ' . esc_attr($selected) . '>' .
                esc_html($sys_field['label']) .
                '</option>';
        }
        echo '</optgroup>';
    }
}

/**
 * Render left picklist + special options for a CRM field that has pick_list_values.
 *
 * @param array  $crm_field        Current CRM field (with pick_list_values).
 * @param string $selected_value   Selected value ('' | actual_value | '__custom_value__' | '__map_form_field__').
 * @param string $selected_source  Selected source ('' | 'option_value' | 'option_custom_value' | 'option_map_form_field' | 'custom_value' | 'form_field' | 'system_field').
 */
function integrazo_wz_render_left_picklist($crm_field, $selected_value = '', $selected_source = '')
{
    $opts = $crm_field['pick_list_values'] ?? array();
?>
    <select class="integrazo-wz-picklist-select" name="picklist_combined[]">
        <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>
        <?php foreach ($opts as $o):
            $actual  = (string) ($o['actual_value'] ?? '');
            $display = (string) ($o['display_value'] ?? $actual);
            $is_sel  = ($selected_source === 'option_value' && trim((string)$selected_value) === trim($actual));
        ?>
            <option value="<?php echo esc_attr($actual); ?>" <?php selected($is_sel); ?>>
                <?php echo esc_html($display); ?>
            </option>
        <?php endforeach; ?>
        <option disabled>────────────</option>
        <option value="__custom_value__" <?php selected(($selected_value === '__custom_value__' || $selected_source === 'option_custom_value' || $selected_source === 'custom_value')); ?>>
            <?php esc_html_e('Use a Custom Value', 'integrazo-integration-for-zoho-apps'); ?>
        </option>
        <option value="__map_form_field__" <?php selected(($selected_value === '__map_form_field__' || $selected_source === 'option_map_form_field')); ?>>
            <?php esc_html_e('Map to Form Field', 'integrazo-integration-for-zoho-apps'); ?>
        </option>
    </select>
<?php
}
?>
<div class="integrazo-wz-mapping-section">
    <div class="integrazo-wz-mapping-table">
        <div class="integrazo-wz-mapping-header">
            <div><?php esc_html_e('Source Field', 'integrazo-integration-for-zoho-apps'); ?></div>
            <div><?php esc_html_e('Target Field', 'integrazo-integration-for-zoho-apps'); ?></div>
        </div>

        <div id="integrazo-wz-mapping-container">
            <?php
            $integrazo_wz_has_mandatory = array_filter($integrazo_wz_crm_fields, function ($f) {
                return !empty($f['system_mandatory']);
            });

            if (! empty($integrazo_wz_crm_fields)) :
                foreach ($integrazo_wz_crm_fields as $integrazo_wz_index => $integrazo_wz_crm_field) :
                    // If there are mandatory fields, skip non-mandatory ones
                    if ($integrazo_wz_has_mandatory && empty($integrazo_wz_crm_field['system_mandatory'])) {
                        continue;
                    }

                    // If no mandatory fields, allow only the first field
                    if (!$integrazo_wz_has_mandatory && $integrazo_wz_index > 0) {
                        continue;
                    }

                    // Safe defaults for first-time (before save)
                    $integrazo_wz_mapping_value  = '';
                    $integrazo_wz_mapping_source = '';

                    $integrazo_wz_has_picklist = ! empty($integrazo_wz_crm_field['pick_list_values']);
                    $integrazo_wz_show_left_picklist = $integrazo_wz_has_picklist; // show picklist if CRM field has defaults
                    $integrazo_wz_show_left_form     = !$integrazo_wz_has_picklist || $integrazo_wz_mapping_value === '__map_form_field__' || $integrazo_wz_mapping_source === 'option_map_form_field';
                    $integrazo_wz_show_left_textarea = ($integrazo_wz_mapping_source === 'custom_value' || $integrazo_wz_mapping_source === 'option_custom_value' || $integrazo_wz_mapping_value === '__custom_value__');
            ?>
                    <div class="integrazo-wz-mapping-row integrazo-wz-mandatory-row">
                        <div class="integrazo-wz-field-left">
                            <div class="integrazo-wz-picklist-combined" style="<?php echo $integrazo_wz_show_left_picklist ? 'display:block;' : 'display:none;'; ?>">
                                <?php
                                if ($integrazo_wz_show_left_picklist) {
                                    integrazo_wz_render_left_picklist($integrazo_wz_crm_field, $integrazo_wz_mapping_value, $integrazo_wz_mapping_source);
                                } else {
                                    // Keep an empty select in DOM to preserve structure if needed.
                                    echo '<select class="integrazo-wz-picklist-select" name="picklist_combined[]"></select>';
                                }
                                ?>
                            </div>

                            <div class="integrazo-wz-form-field-wrapper" id="integrazo-wz-form-field-wrapper" style="<?php echo $integrazo_wz_show_left_form ? '' : 'display:none;'; ?>">
                                <select class="integrazo-wz-form-field-select" name="form_fields[]">
                                    <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>
                                    <?php
                                    // Blank defaults on fresh load (no undefined vars)
                                    integrazo_wz_render_form_field_options($integrazo_wz_form_fields, '', '');
                                    ?>
                                </select>
                            </div>

                            <div class="integrazo-wz-custom-textarea" style="<?php echo $integrazo_wz_show_left_textarea ? 'display:block;' : 'display:none;'; ?>">
                                <textarea name="custom_values[]" placeholder="<?php esc_attr_e('Enter custom value...', 'integrazo-integration-for-zoho-apps'); ?>"></textarea>
                            </div>
                        </div>

                        <div class="integrazo-wz-field-right">
                            <div class="integrazo-wz-form-field-wrapper" style="display: flex; align-items: center; gap: 8px;">
                                <?php $integrazo_wz_is_editable = (!$integrazo_wz_has_mandatory && $integrazo_wz_index === 0); ?>
                                <select class="integrazo-wz-crm-field-select" name="crm_fields[]" style="width: 100%;" <?php echo $integrazo_wz_is_editable ? '' : 'disabled'; ?>>
                                    <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>
                                    <optgroup label="<?php esc_attr_e('General Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                        <?php foreach ($integrazo_wz_crm_fields as $integrazo_wz_field) :
                                            $integrazo_wz_selected = ($integrazo_wz_crm_field['api_name'] === $integrazo_wz_field['api_name']) ? 'selected' : '';
                                        ?>
                                            <option
                                                value="<?php echo esc_attr($integrazo_wz_field['api_name']); ?>"
                                                data-type="<?php echo esc_attr($integrazo_wz_field['data_type']); ?>"
                                                data-picklist='<?php echo esc_attr(wp_json_encode($integrazo_wz_field['pick_list_values'] ?? array())); ?>'
                                                data-mandatory="<?php echo ! empty($integrazo_wz_field['system_mandatory']) ? '1' : '0'; ?>"
                                                <?php echo esc_attr($integrazo_wz_selected); ?>>
                                                <?php echo esc_html($integrazo_wz_field['field_label']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                </select>

                                <div class="integrazo-wz-helpicon-help-icon-wrapper integrazo-wz-crm-help" style="<?php echo $integrazo_wz_has_picklist ? 'display:block;' : 'display:none;'; ?>">
                                    <span class="integrazo-wz-helpicon-help-icon">?</span>
                                    <div class="integrazo-wz-helpicon-help-tooltip">
                                        <p><strong><?php esc_html_e('This field has default options.', 'integrazo-integration-for-zoho-apps'); ?></strong></p>
                                        <p><?php esc_html_e('How to use it:', 'integrazo-integration-for-zoho-apps'); ?></p>
                                        <ol>
                                            <li><?php esc_html_e('Choose a value from the left dropdown.', 'integrazo-integration-for-zoho-apps'); ?></li>
                                            <li><?php esc_html_e("If not available, pick 'Use a Custom Value' or 'Map to Form Field'.", 'integrazo-integration-for-zoho-apps'); ?></li>
                                        </ol>
                                        <p><?php esc_html_e('You can use the ready-made options or customize as needed.', 'integrazo-integration-for-zoho-apps'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="integrazo-wz-actions">
                            <span class="integrazo-wz-add-row">+</span>
                            <span class="integrazo-wz-remove-field integrazo-wz-disabled-remove">&ndash;</span>
                        </div>
                    </div>
            <?php
                endforeach;
            endif;
            ?>

            <div class="integrazo-wz-mapping-row" style="display:none;" id="integrazo-wz-template-row">
                <div class="integrazo-wz-field-left">
                    <div class="integrazo-wz-picklist-combined" style="display:none;">
                        <select class="integrazo-wz-picklist-select" name="picklist_combined[]"></select>
                    </div>
                    <div class="integrazo-wz-form-field-wrapper" id="integrazo-wz-form-field-wrapper">
                        <select class="integrazo-wz-form-field-select" name="form_fields[]">
                            <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>
                            <?php
                            // Template uses blank defaults (no undefined variables)
                            integrazo_wz_render_form_field_options($integrazo_wz_form_fields, '', '');
                            ?>
                        </select>
                    </div>
                    <div class="integrazo-wz-custom-textarea" style="display:none;">
                        <textarea name="custom_values[]" placeholder="<?php esc_attr_e('Enter custom value...', 'integrazo-integration-for-zoho-apps'); ?>"></textarea>
                    </div>
                </div>

                <div class="integrazo-wz-field-right">
                    <div class="integrazo-wz-form-field-wrapper" style="display: flex; align-items: center; gap: 8px;">
                        <select class="integrazo-wz-crm-field-select" name="crm_fields[]" style="width: 100%;" disabled>
                            <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>
                            <?php
                            $integrazo_wz_general_fields = array();
                            $integrazo_wz_custom_fields  = array();
                            $integrazo_wz_premium_fields = array();

                            foreach ($integrazo_wz_crm_fields as $integrazo_wz_field) {
                                if (!empty($integrazo_wz_field['is_custom'])) {
                                    $integrazo_wz_custom_fields[] = $integrazo_wz_field;
                                } elseif (in_array($integrazo_wz_field['api_name'], $integrazo_wz_premium_fields_list, true)) {
                                    $integrazo_wz_premium_fields[] = $integrazo_wz_field;
                                } else {
                                    $integrazo_wz_general_fields[] = $integrazo_wz_field;
                                }
                            }

                            function integrazo_wz_render_crm_field_options($fields, $force_disable = false)
                            {
                                global $integrazo_wz_premium_fields_list;
                                $session = integrazo_wz_session();

                                if (empty($fields) || ! is_array($fields)) {
                                    return;
                                }

                                foreach ($fields as $field) {
                                    $api_name   = isset($field['api_name']) ? $field['api_name'] : '';
                                    $data_type  = isset($field['data_type']) ? $field['data_type'] : '';
                                    $picklist   = isset($field['pick_list_values']) ? $field['pick_list_values'] : array();
                                    $mandatory  = ! empty($field['system_mandatory']) ? '1' : '0';
                                    $label      = isset($field['field_label']) ? $field['field_label'] : $api_name;

                                    $is_premium     = in_array($api_name, $integrazo_wz_premium_fields_list, true);
                                    $should_disable = ! $session && ($is_premium || $force_disable);
                            ?>
                                    <option
                                        value="<?php echo esc_attr($api_name); ?>"
                                        data-type="<?php echo esc_attr($data_type); ?>"
                                        data-picklist='<?php echo esc_attr(wp_json_encode($picklist)); ?>'
                                        data-mandatory="<?php echo esc_attr($mandatory); ?>"
                                        <?php if (! $should_disable) : ?>
                                        style="color: blue;"
                                        <?php else : ?>
                                        title="<?php echo esc_attr__('Upgrade to Pro to use this field.', 'integrazo-integration-for-zoho-apps'); ?>"
                                        data-premium="true"
                                        disabled="disabled"
                                        <?php endif; ?>>
                                        <?php echo esc_html($label); ?>
                                    </option>
                                <?php
                                }
                            }

                            if (! empty($integrazo_wz_general_fields)) {
                                ?>
                                <optgroup label="<?php esc_attr_e('General Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php integrazo_wz_render_crm_field_options($integrazo_wz_general_fields); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($integrazo_wz_custom_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Custom Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php integrazo_wz_render_crm_field_options($integrazo_wz_custom_fields, true); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($integrazo_wz_premium_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Premium Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php integrazo_wz_render_crm_field_options($integrazo_wz_premium_fields); ?>
                                </optgroup>
                            <?php
                            }
                            ?>
                        </select>

                        <div class="integrazo-wz-helpicon-help-icon-wrapper integrazo-wz-crm-help" style="display: none !important">
                            <span class="integrazo-wz-helpicon-help-icon">?</span>
                            <div class="integrazo-wz-helpicon-help-tooltip">
                                <p><strong><?php esc_html_e('This field has default options.', 'integrazo-integration-for-zoho-apps'); ?></strong></p>
                                <p><?php esc_html_e('How to use it:', 'integrazo-integration-for-zoho-apps'); ?></p>
                                <ol>
                                    <li><?php esc_html_e('Choose a value from the left dropdown.', 'integrazo-integration-for-zoho-apps'); ?></li>
                                    <li><?php esc_html_e("If not available, pick 'Use a Custom Value' or 'Map to Form Field'.", 'integrazo-integration-for-zoho-apps'); ?></li>
                                </ol>
                                <p><?php esc_html_e('You can use the ready-made options or customize as needed.', 'integrazo-integration-for-zoho-apps'); ?></p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="integrazo-wz-actions">
                    <span class="integrazo-wz-add-row">+</span>
                    <span class="integrazo-wz-remove-field">&ndash;</span>
                </div>
            </div>

            <div style="margin-top: 20px; text-align: right;"></div>
        </div>
    </div>
</div>