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

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

// Zoho Campaigns client (expects $account_details with dc/tokens)
$product_instance = new INTEGRAZO_WZ_Zoho_Campaigns($account_details);
$common_top_note = $product_instance->common_note();
// Fetch mailing lists (Zoho Campaigns)
$lists = $product_instance->get_mailing_lists();
$record_action_options = $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',
 * ]
 */
$has_lists = (is_array($lists) && isset($lists['list_of_details']) && is_array($lists['list_of_details']));

// Show notices if error-like
if (is_array($lists)) {
    if (isset($lists['error']) && is_string($lists['error'])) {
        printf('<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html($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($integration_id); ?>" />

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

    <?php if ($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 ($lists['list_of_details'] as $list_row) : ?>
                    <?php
                    $value = isset($list_row['listkey']) ? $list_row['listkey'] : '';
                    $label = isset($list_row['listname']) ? $list_row['listname'] : $value;
                    ?>
                    <?php if (!empty($value)) : ?>
                        <option value="<?php echo esc_attr($value); ?>" <?php selected($value, $selected_list); ?>>
                            <?php echo esc_html($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($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($selected_list)) {

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

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

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

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

    if (!empty($field_rows)) {
        foreach ($field_rows as $f) {
            $display = $f['DISPLAY_NAME'] ?? ($f['FIELD_NAME'] ?? '');
            $name    = $f['DISPLAY_NAME']    ?? '';
            if ($name === '') {
                continue;
            }

            $uiType      = $f['UITYPE'] ?? '';
            $isMandatory = !empty($f['IS_MANDATORY']); // '1' or truthy => true
            $isCustom    = (isset($f['TYPE']) && strtolower((string)$f['TYPE']) === 'custom');

            // Prefix if custom
            if ($isCustom) {
                $name = 'integrazo_wz_cf_' . $name;
            }

            $normalized_crm_fields[] = [
                'api_name'         => $name,
                'field_label'      => ($display !== '' ? $display : $name),
                'system_mandatory' => $isMandatory,
                'pick_list_values' => [],   // always empty now
                'data_type'        => $uiType,
                'is_custom'        => $isCustom,
            ];
        }
    }

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

?>