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

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

global $integrazo_wczo_premium_fields_list;
$integrazo_wczo_premium_fields_list = $integrazo_wczo_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_wczo_render_left_picklist($crm_field, $selected_value = '', $selected_source = '')
{
    $opts = $crm_field['pick_list_values'] ?? array();
?>
    <select class="integrazo-wczo-picklist-select" name="picklist_combined[]">
        <option value=""><?php esc_html_e('Select', 'integrazo-wc-zoho-integration'); ?></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-wc-zoho-integration'); ?>
        </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-wc-zoho-integration'); ?>
        </option>
    </select>
<?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">
            <?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-wczo-mapping-row integrazo-wczo-mandatory-row">
                        <div class="integrazo-wczo-field-left">
                            <div class="integrazo-wczo-picklist-combined" style="<?php echo $show_left_picklist ? 'display:block;' : 'display:none;'; ?>">
                                <?php
                                if ($show_left_picklist) {
                                    integrazo_wczo_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-wczo-picklist-select" name="picklist_combined[]"></select>';
                                }
                                ?>
                            </div>

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

                            <div class="integrazo-wczo-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-wc-zoho-integration'); ?>"></textarea>
                            </div>
                        </div>

                        <div class="integrazo-wczo-field-right">
                            <div class="integrazo-wczo-form-field-wrapper" style="display: flex; align-items: center; gap: 8px;">
                                <?php $is_editable = (!$has_mandatory && $index === 0); ?>
                                <select class="integrazo-wczo-crm-field-select" name="crm_fields[]" style="width: 100%;" <?php echo $is_editable ? '' : 'disabled'; ?>>
                                    <option value=""><?php esc_html_e('Select', 'integrazo-wc-zoho-integration'); ?></option>
                                    <optgroup label="<?php esc_attr_e('General Fields', 'integrazo-wc-zoho-integration'); ?>">
                                        <?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-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><?php esc_html_e('This field has default options.', 'integrazo-wc-zoho-integration'); ?></strong></p>
                                        <p><?php esc_html_e('How to use it:', 'integrazo-wc-zoho-integration'); ?></p>
                                        <ol>
                                            <li><?php esc_html_e('Choose a value from the left dropdown.', 'integrazo-wc-zoho-integration'); ?></li>
                                            <li><?php esc_html_e("If not available, pick 'Use a Custom Value' or 'Map to Form Field'.", 'integrazo-wc-zoho-integration'); ?></li>
                                        </ol>
                                        <p><?php esc_html_e('You can use the ready-made options or customize as needed.', 'integrazo-wc-zoho-integration'); ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

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

            <div class="integrazo-wczo-mapping-row" style="display:none;" id="integrazo-wczo-template-row">
                <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=""><?php esc_html_e('Select', 'integrazo-wc-zoho-integration'); ?></option>
                            <?php
                            // Template uses blank defaults (no undefined variables)
                            render_form_field_options($form_fields, '', '');
                            ?>
                        </select>
                    </div>
                    <div class="integrazo-wczo-custom-textarea" style="display:none;">
                        <textarea name="custom_values[]" placeholder="<?php esc_attr_e('Enter custom value...', 'integrazo-wc-zoho-integration'); ?>"></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%;" disabled>
                            <option value=""><?php esc_html_e('Select', 'integrazo-wc-zoho-integration'); ?></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_wczo_premium_fields_list, true)) {
                                    $premium_fields[] = $field;
                                } else {
                                    $general_fields[] = $field;
                                }
                            }

                            function render_crm_field_options($fields, $force_disable = false)
                            {
                                global $integrazo_wczo_premium_fields_list;
                                $session = integrazo_wczo_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_wczo_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-wc-zoho-integration'); ?>"
                                        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-wc-zoho-integration'); ?>">
                                    <?php render_crm_field_options($general_fields); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($custom_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Custom Fields', 'integrazo-wc-zoho-integration'); ?>">
                                    <?php render_crm_field_options($custom_fields, true); ?>
                                </optgroup>
                            <?php
                            }
                            if (! empty($premium_fields)) {
                            ?>
                                <optgroup label="<?php esc_attr_e('Premium Fields', 'integrazo-wc-zoho-integration'); ?>">
                                    <?php render_crm_field_options($premium_fields); ?>
                                </optgroup>
                            <?php
                            }
                            ?>
                        </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><?php esc_html_e('This field has default options.', 'integrazo-wc-zoho-integration'); ?></strong></p>
                                <p><?php esc_html_e('How to use it:', 'integrazo-wc-zoho-integration'); ?></p>
                                <ol>
                                    <li><?php esc_html_e('Choose a value from the left dropdown.', 'integrazo-wc-zoho-integration'); ?></li>
                                    <li><?php esc_html_e("If not available, pick 'Use a Custom Value' or 'Map to Form Field'.", 'integrazo-wc-zoho-integration'); ?></li>
                                </ol>
                                <p><?php esc_html_e('You can use the ready-made options or customize as needed.', 'integrazo-wc-zoho-integration'); ?></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 style="margin-top: 20px; text-align: right;"></div>
        </div>
    </div>
</div>