<?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_module = $integration_data['integrazo_wz_module'] ?? '';
// Zoho Bigin client (expects $account_details with dc/tokens as you already pass)
$product_instance = new INTEGRAZO_WZ_Zoho_Bigin($account_details);

// Fetch modules (array of modules or error structure)
$modules = $product_instance->get_modules();
$record_action_options =  $product_instance->record_action_options();
$general_modules  = [];
$custom_modules   = [];

/**
 * Flag: treat as a valid list (array of rows), not an error wrapper.
 * $modules like:
 *   [
 *     ['api_name' => 'Leads', 'plural_label' => 'Leads', 'generated_type' => 'default', ...],
 *     ...
 *   ]
 */
$has_modules_list = (is_array($modules) && isset($modules[0]) && is_array($modules[0]));

// Show notices if error
if (is_array($modules)) {
    // Wrapper error (our SDK-style)
    if (isset($modules['error']) && is_string($modules['error'])) {
        printf(
            '<div class="notice notice-error is-dismissible"><p>%s</p></div>',
            esc_html($modules['error'])
        );
    }
    // Zoho error payload (category/message pattern)
    if (isset($modules['category'])) {
        $msg = $modules['message'] ?? __('Failed to retrieve modules.', 'integrazo-integration-for-zoho-apps');
        printf(
            '<div class="notice notice-error is-dismissible"><p>%s</p></div>',
            esc_html($msg)
        );
    }
}

// Build bucketed lists when valid
if ($has_modules_list) {
    foreach ($modules as $module) {
        if (!empty($module['api_name']) && !empty($module['plural_label'])) {
            if (!empty($module['generated_type']) && $module['generated_type'] === 'custom') {
                $custom_modules[] = $module;
            } else {
                $general_modules[] = $module;
            }
        }
    }
}

?>
<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_modules_list) : ?>
        <!-- Module Selection -->
        <div style="display:flex;align-items:center;margin-bottom:15px;">
            <label for="integrazo_wz_module_select" class="integrazo-wz-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Module:', '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 Bigin module where you want to send the data.', 'integrazo-integration-for-zoho-apps'); ?></p>
                    </div>
                </div>
            </label>

            <select name="integrazo_wz_module" id="integrazo_wz_module_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 if (!empty($general_modules)) : ?>
                    <optgroup label="<?php esc_attr_e('General Modules', 'integrazo-integration-for-zoho-apps'); ?>">
                        <?php foreach ($general_modules as $module) : ?>
                            <option value="<?php echo esc_attr($module['api_name']); ?>" <?php selected($module['api_name'], $selected_module); ?>>
                                <?php echo esc_html($module['plural_label']); ?>
                            </option>
                        <?php endforeach; ?>
                    </optgroup>
                <?php endif; ?>

                <?php if (!empty($custom_modules)) : ?>
                    <optgroup label="<?php esc_attr_e('Custom Modules', 'integrazo-integration-for-zoho-apps'); ?>">
                        <?php foreach ($custom_modules as $module) : ?>
                            <option
                                value="<?php echo esc_attr('integrazo_wz_cm_' . $module['api_name']); ?>"
                                disabled
                                title="<?php echo esc_attr__('Upgrade to Pro to continue using this module.', 'integrazo-integration-for-zoho-apps'); ?>"
                                <?php selected('integrazo_wz_cm_' . $module['api_name'], $selected_module); ?>>
                                <?php echo esc_html($module['plural_label']); ?>
                            </option>
                        <?php endforeach; ?>
                    </optgroup>
                <?php endif; ?>

            </select>
        </div>
    <?php endif; ?>

    <!-- Save & Next Button (hidden only when a module is selected) -->
    <!-- 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_module)) ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-integration-for-zoho-apps'); ?>
        </button>
    </div>

</form>

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

    // Handle custom module prefix
    if (strpos($selected_module, 'integrazo_wz_cm_') === 0) {
        $selected_module = substr($selected_module, strlen('integrazo_wz_cm_'));
    }

    // Fetch fields for selected module
    $raw_product_fields = $product_instance->get_module_fields($selected_module);
    $normalized_crm_fields = [];

    // Normalize Zoho Bigin fields (respect custom_field and api_name)
    if (!empty($raw_product_fields['fields']) && is_array($raw_product_fields['fields'])) {
        foreach ($raw_product_fields['fields'] as $field) {
            $api_name = $field['api_name'] ?? '';
            if ($api_name === '' || $api_name === 'Tag') {
                continue; // skip empty or Tag fields
            }

            if (!empty($field['custom_field'])) {
                $api_name = 'integrazo_wz_cf_' . $api_name;
            }

            $normalized_crm_fields[] = [
                'api_name'         => $api_name,
                'field_label'      => $field['field_label'] ?? ($field['display_label'] ?? $api_name),
                'system_mandatory' => !empty($field['system_mandatory']),
                'pick_list_values' => $field['pick_list_values'] ?? [],
                'data_type'        => $field['data_type'] ?? '',
                'is_custom'        => !empty($field['custom_field']),
            ];
        }
    }


    // Append plugin-specific fields if provided
    if (!empty($additional_fields[$to_product]) && is_array($additional_fields[$to_product])) {
        foreach ($additional_fields[$to_product] as $field) {
            if (!empty($field['api_name']) && !empty($field['label_name'])) {
                $normalized_crm_fields[] = [
                    'api_name'         => $field['api_name'],
                    'field_label'      => $field['label_name'],
                    'system_mandatory' => false,
                    'pick_list_values' => [],
                    'data_type'        => 'integrazo_wz_data_type',
                    'is_custom'        => false,
                ];
            }
        }
    }

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