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

/**
 * ================================================================
 *  1. INITIAL SETUP & VARIABLE DECLARATIONS (Zoho Desk - Departments)
 * ================================================================
 */
$integrazo_wz_form_id = INTEGRAZO_WZ_Util::get_event_value($integrazo_wz_integration_data);
$integrazo_wz_selected_department = $integrazo_wz_integration_data['integrazo_wz_department_id'] ?? ''; // store selected department id

// Zoho Desk client (expects $integrazo_wz_account_details with dc/tokens as you already pass)
$integrazo_wz_desk_instance = new INTEGRAZO_WZ_Zoho_Desk($integrazo_wz_account_details);

// Fetch departments (array list or ['error' => '...'])
$integrazo_wz_departments = $integrazo_wz_desk_instance->get_desk_departments();

// Do we have a valid list?
$integrazo_wz_has_departments_list = (is_array($integrazo_wz_departments) && !isset($integrazo_wz_departments['error']) && !empty($integrazo_wz_departments) && is_array(reset($integrazo_wz_departments)));

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

    <?php if ($integrazo_wz_has_departments_list) : ?>
        <!-- Department Selection -->
        <div style="display:flex;align-items:center;margin-bottom:15px;">
            <label for="integrazo_wz_department_select" class="integrazo-wz-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Department:', '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 Desk department where you want to create tickets.', 'integrazo-integration-for-zoho-apps'); ?></p>
                    </div>
                </div>
            </label>

            <select name="integrazo_wz_department_id" id="integrazo_wz_department_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_departments as $integrazo_wz_dept) :
                    // Zoho Desk department structure typically has 'id' and 'name'
                    $integrazo_wz_dept_id   = isset($integrazo_wz_dept['id'])   ? (string)$integrazo_wz_dept['id']   : '';
                    $integrazo_wz_dept_name = isset($integrazo_wz_dept['name']) ? (string)$integrazo_wz_dept['name'] : ($integrazo_wz_dept_id ?: '');
                    if ($integrazo_wz_dept_id === '') {
                        continue;
                    }
                ?>
                    <option value="<?php echo esc_attr($integrazo_wz_dept_id); ?>" <?php selected($integrazo_wz_dept_id, $integrazo_wz_selected_department); ?>>
                        <?php echo esc_html($integrazo_wz_dept_name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    <?php endif; ?>

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

</form>

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

    // Fetch ticket fields for selected department (already normalized)
    $integrazo_wz_raw_fields = $integrazo_wz_desk_instance->get_desk_departments_fields($integrazo_wz_selected_department);

    $integrazo_wz_normalized_crm_fields = [];

    // Error notice if failed
    if (is_array($integrazo_wz_raw_fields) && isset($integrazo_wz_raw_fields['error'])) {
        printf(
            '<div class="notice notice-error is-dismissible"><p>%s</p></div>',
            esc_html($integrazo_wz_raw_fields['error'])
        );
    } elseif (is_array($integrazo_wz_raw_fields)) {
        // ✅ Fields are already normalized by the SDK method
        $integrazo_wz_normalized_crm_fields = $integrazo_wz_raw_fields;
    }

    // Append plugin-specific fields if provided (optional)
    if (!empty($integrazo_wz_additional_fields[$integrazo_wz_to_product]) && is_array($integrazo_wz_additional_fields[$integrazo_wz_to_product])) {
        foreach ($integrazo_wz_additional_fields[$integrazo_wz_to_product] as $integrazo_wz_field) {
            if (!empty($integrazo_wz_field['api_name']) && !empty($integrazo_wz_field['label_name'])) {
                $integrazo_wz_normalized_crm_fields[] = [
                    'api_name'         => $integrazo_wz_field['api_name'],
                    'field_label'      => $integrazo_wz_field['label_name'],
                    'system_mandatory' => false,
                    'pick_list_values' => [],
                    'data_type'        => 'integrazo_wz_data_type',
                    'is_custom'        => false,
                ];
            }
        }
    }

    // Load the shared pre-mapping UI (expects $integrazo_wz_normalized_crm_fields)
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'src/products/pre-mapping.php';
}
?>