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

/**
 * ================================================================
 *  1. INITIAL SETUP & VARIABLE DECLARATIONS
 * ================================================================
 */
$integrazo_wczo_form_id = INTEGRAZO_WCZO_Util::get_event_value($integration_data);
$selected_module = $integration_data['integrazo_wczo_module'] ?? '';
// Zoho Bigin client (expects $account_details with dc/tokens as you already pass)
$product_instance = new INTEGRAZO_WCZO_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-wc-zoho-integration');
        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_wczo_field_mapping_action', 'integrazo_wczo_field_mapping_nonce'); ?>
    <input type="hidden" name="action" value="integrazo_wczo_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_WCZO_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_wczo_module_select" class="integrazo-wczo-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Module:', 'integrazo-wc-zoho-integration'); ?>
                <div class="integrazo-wczo-helpicon-help-icon-wrapper" style="display:inline-block;margin-left:5px;">
                    <span class="integrazo-wczo-helpicon-help-icon">?</span>
                    <div class="integrazo-wczo-helpicon-help-tooltip">
                        <p><?php esc_html_e('Choose the Zoho Bigin module where you want to send the data.', 'integrazo-wc-zoho-integration'); ?></p>
                    </div>
                </div>
            </label>

            <select name="integrazo_wczo_module" id="integrazo_wczo_module_select" class="regular-text integrazo-wczo-setup-select-change" style="width:60%;">
                <option value=""><?php esc_html_e('Select', 'integrazo-wc-zoho-integration'); ?></option>

                <?php if (!empty($general_modules)) : ?>
                    <optgroup label="<?php esc_attr_e('General Modules', 'integrazo-wc-zoho-integration'); ?>">
                        <?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-wc-zoho-integration'); ?>">
                        <?php foreach ($custom_modules as $module) : ?>
                            <option
                                value="<?php echo esc_attr('integrazo_wczo_cm_' . $module['api_name']); ?>"
                                disabled
                                title="<?php echo esc_attr__('Upgrade to Pro to continue using this module.', 'integrazo-wc-zoho-integration'); ?>"
                                <?php selected('integrazo_wczo_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-wczo-setup-next-btn-wrapper integrazo-wczo-setup-step2-save-btn">
        <button
            type="submit"
            id="integrazo_wczo_setup_next_button"
            name="integrazo_wczo_next"
            class="button button-primary"
            style="<?php echo esc_attr((!empty($integrazo_wczo_form_id) && !empty($selected_module)) ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-wc-zoho-integration'); ?>
        </button>
    </div>

</form>

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

    // Handle custom module prefix
    if (strpos($selected_module, 'integrazo_wczo_cm_') === 0) {
        $selected_module = substr($selected_module, strlen('integrazo_wczo_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_wczo_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($integrazo_wczo_additional_fields[$to_product]) && is_array($integrazo_wczo_additional_fields[$to_product])) {
        foreach ($integrazo_wczo_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_wczo_data_type',
                    'is_custom'        => false,
                ];
            }
        }
    }

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