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

// ---- GUARD: require an authenticated/selected account ----
if (empty($account_details) || !is_array($account_details)) {
    return; // stop rendering this page
}

/**
 * ================================================================
 *  1. INITIAL SETUP & VARIABLE DECLARATIONS
 * ================================================================
 */
$integrazo_wz_form_id = INTEGRAZO_WZ_Util::get_event_value($integration_data);
$selected_event       = $integration_data['integrazo_wz_product_event'] ?? '';

// Zoho Invoice client
$product_instance = new INTEGRAZO_WZ_Zoho_Invoice($account_details);

// Get org list
$org_list = $product_instance->get_organizations_list();
$orgs = [];
if (is_array($org_list) && isset($org_list['organizations']) && is_array($org_list['organizations'])) {
    $orgs = $org_list['organizations'];
} elseif (isset($org_list['error'])) {
    printf('<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html($org_list['error']));
}

// Saved org id (renamed field)
$selected_org_id = $integration_data['integrazo_wz_product_orgid'] ?? '';

// ---- NEW: fetch & normalize events (array of ['api_name','display_name','pro','priority']) ----
$events_raw = $product_instance->get_events();
$events     = [];
if (is_array($events_raw)) {
    foreach ($events_raw as $ev) {
        if (!is_array($ev) || empty($ev['api_name']) || empty($ev['display_name'])) {
            continue;
        }

        $events[] = [
            'api_name'     => (string) $ev['api_name'],
            'display_name' => (string) $ev['display_name'],
            'pro'          => !empty($ev['pro']),
            'priority'     => isset($ev['priority']) ? (int) $ev['priority'] : 0,
        ];
    }
}
$has_events = !empty($events);

$event_html = (isset($event) && is_string($event)) ? $event : '';

// ---- Determine selected event priority for hidden field ----
$selected_priority = '';
if ($has_events && !empty($selected_event)) {
    foreach ($events as $ev) {
        $value   = $ev['api_name'];
        $is_pro  = !empty($ev['pro']);

        // Match the same logic used for option values
        $option_value = !$is_pro ? ('integrazo_wz_cm_' . $value) : $value;

        if ($option_value === $selected_event) {
            if (isset($ev['priority']) && (int) $ev['priority'] > 0) {
                $selected_priority = (int) $ev['priority'];
            }
            break;
        }
    }
}
?>

<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
    // Load run priority only when an event is selected and mapped to a valid priority.
    if ($selected_priority !== '') :

    ?>
        <input type="hidden"
            name="integrazo_wz_run_priority"
            value="<?php echo esc_attr($selected_priority); ?>" />
    <?php endif; ?>

    <?php echo wp_kses($event_html, INTEGRAZO_WZ_Plugin_Input_Renderer::allowed_admin_html()); ?>

    <?php if ($has_events) : ?>

        <!-- Action Selection -->
        <div style="display:flex;align-items:center;margin-bottom:15px;">
            <label for="integrazo_wz_product_event_select" class="integrazo-wz-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Action:', '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('Select what operation to perform in Zoho Invoice like creating an item or adjusting stock.', 'integrazo-integration-for-zoho-apps'); ?></p>
                    </div>
                </div>
            </label>

           <select
                name="integrazo_wz_product_event"
                id="integrazo_wz_product_event_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 ( $events as $ev ) :
                    $value  = isset( $ev['api_name'] ) ? $ev['api_name'] : '';
                    $label  = isset( $ev['display_name'] ) ? $ev['display_name'] : '';
                    $is_pro = ! empty( $ev['pro'] );

                    // Prefix for non-pro (common) actions.
                    $option_value = ! $is_pro ? 'integrazo_wz_cm_' . $value : $value;

                    // Disable only when pro is false and session is empty.
                    $is_disabled = ( ! $is_pro && empty( $session ) );

                    // Update label text when disabled.
                    $label_text = $is_disabled ? $label . ' (Pro)' : $label;
                    ?>
                    <option
                        value="<?php echo esc_attr( $option_value ); ?>"
                        <?php
                        if ( $is_disabled ) {
                            echo 'disabled="disabled" title="' . esc_attr__( 'Upgrade to Pro to unlock Zoho Invoice action.', 'integrazo-integration-for-zoho-apps' ) . '"';
                        } else {
                            echo 'style="color:' . esc_attr( 'rgb(0, 0, 255)' ) . ';"';
                        }
                        ?>
                        <?php selected( $option_value, $selected_event ); ?>>
                        <?php echo esc_html( $label_text ); ?>
                    </option>
                <?php endforeach; ?>
            </select>

        </div>

        <!-- Organization Selection -->
        <?php if (!empty($orgs)) : ?>
            <div style="display:flex;align-items:center;margin-bottom:15px;">
                <label for="integrazo_wz_product_orgid" class="integrazo-wz-setup-lable" style="width:170px;margin-right:10px;">
                    <?php esc_html_e('Select Organization:', '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 which Zoho Invoice organization this integration will use.', 'integrazo-integration-for-zoho-apps'); ?></p>
                        </div>
                    </div>
                </label>

                <select
                    name="integrazo_wz_product_orgid"
                    id="integrazo_wz_product_orgid"
                    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 ($orgs as $org) :
                        $oid   = isset($org['organization_id']) ? (string) $org['organization_id'] : '';
                        $oname = isset($org['name']) ? (string) $org['name'] : $oid;
                    ?>
                        <option
                            value="<?php echo esc_attr($oid); ?>"
                            <?php selected($oid, $selected_org_id); ?>>
                            <?php echo esc_html($oname); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>

    <?php endif; ?>

    <!-- Save & Next Button -->
    <?php $all_selected = (!empty($integrazo_wz_form_id) && !empty($selected_event) && !empty($selected_org_id)); ?>
    <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($all_selected ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-integration-for-zoho-apps'); ?>
        </button>
    </div>
</form>

<?php
/**
 * ================================================================
 *  2. MAPPING UI
 * ================================================================
 */
if (!empty($integrazo_wz_form_id) && !empty($selected_event) && !empty($selected_org_id)) {

    $fields_response = [];

    if (!function_exists('integrazo_wz_render_zoho_invoice_sku_note')) {
        function integrazo_wz_render_zoho_invoice_sku_note()
        {
?>
            <div class="integrazo-wz-setup-step2-note-bottom" style="margin-left: 170px !important; max-width: 71.5% !important;">
                <p>
                    <strong><?php esc_html_e('Note:', 'integrazo-integration-for-zoho-apps'); ?></strong>
                    <?php esc_html_e('If the SKU is not available, map the Product ID or any other unique identifier as the SKU. This is required to uniquely identify items in Zoho Invoice.', 'integrazo-integration-for-zoho-apps'); ?>
                </p>
            </div>
<?php
        }
    }

    switch ($selected_event) {
        case 'create_contact':
            $fields_response = $product_instance->get_create_contact_fields();
            break;

        case 'integrazo_wz_cm_update_contact':
            $fields_response = $product_instance->get_update_contact_fields();
            break;

        case 'integrazo_wz_cm_create_item':
            integrazo_wz_render_zoho_invoice_sku_note();
            $fields_response = $product_instance->get_create_items_fields();
            break;

        case 'integrazo_wz_cm_update_item':
            integrazo_wz_render_zoho_invoice_sku_note();
            $fields_response = $product_instance->get_update_items_fields();
            break;
        case 'integrazo_wz_cm_create_invoice':
            integrazo_wz_render_zoho_invoice_sku_note();
            $fields_response = $product_instance->get_invoice_fields();
            break;

        default:
            $fields_response = [
                'error' => __('Unknown event selected.', 'integrazo-integration-for-zoho-apps'),
            ];
            break;
    }

    if (isset($fields_response['error'])) {
        printf('<div class="notice notice-error"><p>%s</p></div>', esc_html($fields_response['error']));
        return;
    }

    // Normalize to your mapping schema
    $normalized_crm_fields = [];
    if (is_array($fields_response) && !empty($fields_response)) {
        foreach ($fields_response as $field) {
            if (!is_array($field) || !isset($field['api_name'])) {
                continue;
            }
            $normalized_crm_fields[] = [
                'api_name'         => (string) $field['api_name'],
                'field_label'      => (string) ($field['field_label'] ?? ucwords(str_replace('_', ' ', $field['api_name']))),
                'system_mandatory' => (bool) ($field['system_mandatory'] ?? false),
                'pick_list_values' => $field['pick_list_values'] ?? [],
                'data_type'        => (string) ($field['data_type'] ?? ''),
                'is_custom'        => (bool) ($field['is_custom'] ?? false),
            ];
        }
    }

    require_once INTEGRAZO_WZ_PLUGIN_DIR . 'src/products/pre-mapping.php';
}
?>