<?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($integration_data);
$selected_department = $integration_data['integrazo_wz_department_id'] ?? ''; // store selected department id

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

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

// Do we have a valid list?
$has_departments_list = (is_array($departments) && !isset($departments['error']) && !empty($departments) && is_array(reset($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($integration_id); ?>" />

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

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

    <?php if ($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 ($departments as $dept) :
                    // Zoho Desk department structure typically has 'id' and 'name'
                    $dept_id   = isset($dept['id'])   ? (string)$dept['id']   : '';
                    $dept_name = isset($dept['name']) ? (string)$dept['name'] : ($dept_id ?: '');
                    if ($dept_id === '') {
                        continue;
                    }
                ?>
                    <option value="<?php echo esc_attr($dept_id); ?>" <?php selected($dept_id, $selected_department); ?>>
                        <?php echo esc_html($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($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($selected_department)) {

    // Fetch ticket fields for selected department (already normalized)
    $raw_fields = $desk_instance->get_desk_departments_fields($selected_department);

    $normalized_crm_fields = [];

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

    // Append plugin-specific fields if provided (optional)
    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 (expects $normalized_crm_fields)
    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'src/products/pre-mapping.php';
}
?>