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

/**
 * ================================================================
 *  1. INITIAL SETUP & VARIABLE DECLARATIONS (Zoho Desk - Departments)
 * ================================================================
 */
$integrazo_wczo_form_id = INTEGRAZO_WCZO_Util::get_event_value($integration_data);
$selected_department = $integration_data['integrazo_wczo_department_id'] ?? ''; // store selected department id

// Zoho Desk client (expects $account_details with dc/tokens as you already pass)
$desk_instance = new INTEGRAZO_WCZO_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_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
    // 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_wczo_department_select" class="integrazo-wczo-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Department:', '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 Desk department where you want to create tickets.', 'integrazo-wc-zoho-integration'); ?></p>
                    </div>
                </div>
            </label>

            <select name="integrazo_wczo_department_id" id="integrazo_wczo_department_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 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-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_department)) ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-wc-zoho-integration'); ?>
        </button>
    </div>

</form>

<?php
/**
 * ================================================================
 *  2. MAPPING UI (ONLY IF A DEPARTMENT IS SELECTED)
 * ================================================================
 */
if (!empty($integrazo_wczo_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($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 (expects $normalized_crm_fields)
    require_once INTEGRAZO_WCZO_PLUGIN_DIR . 'src/products/pre-mapping.php';
}
?>