<?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 = $advanced_fields[$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 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
            $has_mandatory = array_filter($crm_fields, function ($f) {
                return !empty($f['system_mandatory']);
            });

            if (! empty($crm_fields)) :
                foreach ($crm_fields as $index => $crm_field) :
                    // If there are mandatory fields, skip non-mandatory ones
                    if ($has_mandatory && empty($crm_field['system_mandatory'])) {
                        continue;
                    }

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

                    // Safe defaults for first-time (before save)
                    $mapping_value  = '';
                    $mapping_source = '';

                    $has_picklist = ! empty($crm_field['pick_list_values']);
                    $show_left_picklist = $has_picklist; // show picklist if CRM field has defaults
                    $show_left_form     = !$has_picklist || $mapping_value === '__map_form_field__' || $mapping_source === 'option_map_form_field';
                    $show_left_textarea = ($mapping_source === 'custom_value' || $mapping_source === 'option_custom_value' || $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 $show_left_picklist ? 'display:block;' : 'display:none;'; ?>">
                                <?php
                                if ($show_left_picklist) {
                                    integrazo_wz_render_left_picklist($crm_field, $mapping_value, $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 $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)
                                    render_form_field_options($form_fields, '', '');
                                    ?>
                                </select>
                            </div>

                            <div class="integrazo-wz-custom-textarea" style="<?php echo $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 $is_editable = (!$has_mandatory && $index === 0); ?>
                                <select class="integrazo-wz-crm-field-select" name="crm_fields[]" style="width: 100%;" <?php echo $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 ($crm_fields as $field) :
                                            $selected = ($crm_field['api_name'] === $field['api_name']) ? 'selected' : '';
                                        ?>
                                            <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'] ?? array())); ?>'
                                                data-mandatory="<?php echo ! empty($field['system_mandatory']) ? '1' : '0'; ?>"
                                                <?php echo esc_attr($selected); ?>>
                                                <?php echo esc_html($field['field_label']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                </select>

                                <div class="integrazo-wz-helpicon-help-icon-wrapper integrazo-wz-crm-help" style="<?php echo $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)
                            render_form_field_options($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
                            $general_fields = array();
                            $custom_fields  = array();
                            $premium_fields = array();

                            foreach ($crm_fields as $field) {
                                if (!empty($field['is_custom'])) {
                                    $custom_fields[] = $field;
                                } elseif (in_array($field['api_name'], $integrazo_wz_premium_fields_list, true)) {
                                    $premium_fields[] = $field;
                                } else {
                                    $general_fields[] = $field;
                                }
                            }

                            function 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($general_fields)) {
                                ?>
                                <optgroup label="<?php esc_attr_e('General Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php render_crm_field_options($general_fields); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($custom_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Custom Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php render_crm_field_options($custom_fields, true); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($premium_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Premium Fields', 'integrazo-integration-for-zoho-apps'); ?>">
                                    <?php render_crm_field_options($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>