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

/**
 * ================================================================
 *  1. INITIAL SETUP & VARIABLE DECLARATIONS
 * ================================================================
 */
$integrazo_wz_form_id = INTEGRAZO_WZ_Util::get_event_value($integrazo_wz_integration_data);
$integrazo_wz_selected_list    = $integrazo_wz_integration_data['integrazo_wz_list']     ?? '';

// Zoho Campaigns client (expects $integrazo_wz_account_details with dc/tokens)
$integrazo_wz_product_instance = new INTEGRAZO_WZ_Zoho_Campaigns($integrazo_wz_account_details);
$integrazo_wz_common_top_note = $integrazo_wz_product_instance->common_note();
// Fetch mailing lists (Zoho Campaigns)
$integrazo_wz_lists = $integrazo_wz_product_instance->get_mailing_lists();
$integrazo_wz_record_action_options = $integrazo_wz_product_instance->record_action_options();


/**
 * Treat as a valid lists payload when it matches Campaigns v1.1:
 * [
 *   'code' => 0,
 *   'list_of_details' => [ [ 'listkey' => '...', 'listname' => '...', ... ], ... ],
 *   'status' => 'success',
 * ]
 */
$integrazo_wz_has_lists = (is_array($integrazo_wz_lists) && isset($integrazo_wz_lists['list_of_details']) && is_array($integrazo_wz_lists['list_of_details']));

// Show notices if error-like
if (is_array($integrazo_wz_lists)) {
    if (isset($integrazo_wz_lists['error']) && is_string($integrazo_wz_lists['error'])) {
        printf('<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html($integrazo_wz_lists['error']));
    }
}
?>

<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
    <?php wp_nonce_field('integrazo_wz_field_mapping_action', 'integrazo_wz_field_mapping_nonce'); ?>
    <input type="hidden" name="action" value="integrazo_wz_handle_field_mapping_step" />
    <input type="hidden" name="integration_id" value="<?php echo esc_attr($integrazo_wz_integration_id); ?>" />

    <?php
    $integrazo_wz_event_html = is_string($integrazo_wz_event) ? $integrazo_wz_event : '';
    echo wp_kses($integrazo_wz_event_html, INTEGRAZO_WZ_Plugin_Input_Renderer::allowed_admin_html());
    ?>

    <?php if ($integrazo_wz_has_lists) : ?>
        <!-- List Selection -->
        <div style="display:flex;align-items:center;margin-bottom:15px;">
            <label for="integrazo_wz_list_select" class="integrazo-wz-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select List:', 'integrazo-integration-for-zoho-apps'); ?>
                <div class="integrazo-wz-helpicon-help-icon-wrapper" style="display:inline-block;margin-left:5px;">
                    <span class="integrazo-wz-helpicon-help-icon">?</span>
                    <div class="integrazo-wz-helpicon-help-tooltip">
                        <p><?php esc_html_e('Choose the Zoho Campaigns mailing list where you want to add contacts.', 'integrazo-integration-for-zoho-apps'); ?></p>
                    </div>
                </div>
            </label>

            <select name="integrazo_wz_list" id="integrazo_wz_list_select" class="regular-text integrazo-wz-setup-select-change" style="width:60%;">
                <option value=""><?php esc_html_e('Select', 'integrazo-integration-for-zoho-apps'); ?></option>

                <?php foreach ($integrazo_wz_lists['list_of_details'] as $integrazo_wz_list_row) : ?>
                    <?php
                    $integrazo_wz_value = isset($integrazo_wz_list_row['listkey']) ? $integrazo_wz_list_row['listkey'] : '';
                    $integrazo_wz_label = isset($integrazo_wz_list_row['listname']) ? $integrazo_wz_list_row['listname'] : $integrazo_wz_value;
                    ?>
                    <?php if (!empty($integrazo_wz_value)) : ?>
                        <option value="<?php echo esc_attr($integrazo_wz_value); ?>" <?php selected($integrazo_wz_value, $integrazo_wz_selected_list); ?>>
                            <?php echo esc_html($integrazo_wz_label); ?>
                        </option>
                    <?php endif; ?>
                <?php endforeach; ?>
            </select>
        </div>
    <?php endif; ?>

    <!-- Save & Next Button -->
    <div class="integrazo-wz-setup-next-btn-wrapper integrazo-wz-setup-step2-save-btn">
        <button
            type="submit"
            id="integrazo_wz_setup_next_button"
            name="integrazo_wz_next"
            class="button button-primary"
            style="<?php echo esc_attr((!empty($integrazo_wz_form_id) && !empty($integrazo_wz_selected_list)) ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-integration-for-zoho-apps'); ?>
        </button>
    </div>
</form>

<?php
/**
 * ================================================================
 *  2. MAPPING UI (ONLY IF A LIST IS SELECTED)
 * ================================================================
 */
if (!empty($integrazo_wz_form_id) && !empty($integrazo_wz_selected_list)) {

    // In Campaigns, fields are global contact fields, not per module/list
    $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_all_fields();

    // Show error notice if failed
    if (is_array($integrazo_wz_fields_response) && isset($integrazo_wz_fields_response['error'])) {
        printf('<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html($integrazo_wz_fields_response['error']));
        return;
    }

    // Normalize to a common structure for the mapping UI
    $integrazo_wz_normalized_crm_fields = [];

    // Response already comes as a flat array of field rows
    $integrazo_wz_field_rows = is_array($integrazo_wz_fields_response) ? $integrazo_wz_fields_response : [];

    if (!empty($integrazo_wz_field_rows)) {
        foreach ($integrazo_wz_field_rows as $integrazo_wz_f) {
            $integrazo_wz_display = $integrazo_wz_f['DISPLAY_NAME'] ?? ($integrazo_wz_f['FIELD_NAME'] ?? '');
            $integrazo_wz_name    = $integrazo_wz_f['DISPLAY_NAME']    ?? '';
            if ($integrazo_wz_name === '') {
                continue;
            }

            $integrazo_wz_uiType      = $integrazo_wz_f['UITYPE'] ?? '';
            $integrazo_wz_isMandatory = !empty($integrazo_wz_f['IS_MANDATORY']); // '1' or truthy => true
            $integrazo_wz_isCustom    = (isset($integrazo_wz_f['TYPE']) && strtolower((string)$integrazo_wz_f['TYPE']) === 'custom');

            // Prefix if custom
            if ($integrazo_wz_isCustom) {
                $integrazo_wz_name = 'integrazo_wz_cf_' . $integrazo_wz_name;
            }

            $integrazo_wz_normalized_crm_fields[] = [
                'api_name'         => $integrazo_wz_name,
                'field_label'      => ($integrazo_wz_display !== '' ? $integrazo_wz_display : $integrazo_wz_name),
                'system_mandatory' => $integrazo_wz_isMandatory,
                'pick_list_values' => [],   // always empty now
                'data_type'        => $integrazo_wz_uiType,
                'is_custom'        => $integrazo_wz_isCustom,
            ];
        }
    }

    // Load the shared pre-mapping UI
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'src/products/pre-mapping.php';
}

?>