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

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

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

// Zoho Inventory client
$integrazo_wz_product_instance = new INTEGRAZO_WZ_Zoho_Inventory($integrazo_wz_account_details);

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

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

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

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

// Free plan: list allowed actions first (event's own 'pro' flag marks it as
// free-plan-allowed here — see the disabled check below), Pro-gated-and-locked
// actions after.
if (empty($session) && !empty($integrazo_wz_events)) {
    $integrazo_wz_allowed_events  = [];
    $integrazo_wz_disabled_events = [];
    foreach ($integrazo_wz_events as $integrazo_wz_ev) {
        if (!empty($integrazo_wz_ev['pro'])) {
            $integrazo_wz_allowed_events[] = $integrazo_wz_ev;
        } else {
            $integrazo_wz_disabled_events[] = $integrazo_wz_ev;
        }
    }
    $integrazo_wz_events = array_merge($integrazo_wz_allowed_events, $integrazo_wz_disabled_events);
}

$integrazo_wz_has_events = !empty($integrazo_wz_events);

$integrazo_wz_event_html = (isset($integrazo_wz_event) && is_string($integrazo_wz_event)) ? $integrazo_wz_event : '';

// ---- Determine selected event priority for hidden field ----
$integrazo_wz_selected_priority = '';
if ($integrazo_wz_has_events && !empty($integrazo_wz_selected_event)) {
    foreach ($integrazo_wz_events as $integrazo_wz_ev) {
        $integrazo_wz_value   = $integrazo_wz_ev['api_name'];
        $integrazo_wz_is_pro  = !empty($integrazo_wz_ev['pro']);

        // Match the same logic used for option values
        $integrazo_wz_option_value = !$integrazo_wz_is_pro ? ('integrazo_wz_cm_' . $integrazo_wz_value) : $integrazo_wz_value;

        if ($integrazo_wz_option_value === $integrazo_wz_selected_event) {
            if (isset($integrazo_wz_ev['priority']) && (int) $integrazo_wz_ev['priority'] > 0) {
                $integrazo_wz_selected_priority = (int) $integrazo_wz_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($integrazo_wz_integration_id); ?>" />

    <?php
    // Load run priority only when an event is selected and mapped to a valid priority.
    if ($integrazo_wz_selected_priority !== '') :

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

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

    <?php if ($integrazo_wz_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 Inventory 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 ( $integrazo_wz_events as $integrazo_wz_ev ) :
                    $integrazo_wz_value   = isset( $integrazo_wz_ev['api_name'] ) ? $integrazo_wz_ev['api_name'] : '';
                    $integrazo_wz_label   = isset( $integrazo_wz_ev['display_name'] ) ? $integrazo_wz_ev['display_name'] : '';
                    $integrazo_wz_is_pro  = ! empty( $integrazo_wz_ev['pro'] );

                    // Prefix for non-pro (common) actions.
                    $integrazo_wz_option_value = ! $integrazo_wz_is_pro ? 'integrazo_wz_cm_' . $integrazo_wz_value : $integrazo_wz_value;

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

                    // Update label text when disabled.
                    $integrazo_wz_label_text = $integrazo_wz_is_disabled
                        ? $integrazo_wz_label . ' (Pro)'
                        : $integrazo_wz_label;
                    ?>
                    <option
                        value="<?php echo esc_attr( $integrazo_wz_option_value ); ?>"
                        data-priority="<?php echo esc_attr( isset( $integrazo_wz_ev['priority'] ) ? (int) $integrazo_wz_ev['priority'] : 0 ); ?>"
                        <?php
                        if ( $integrazo_wz_is_disabled ) {
                            echo 'disabled="disabled" title="' . esc_attr__( 'Upgrade to Pro to unlock Zoho Inventory action.', 'integrazo-integration-for-zoho-apps' ) . '"';
                        } else {
                            echo 'style="color:' . esc_attr( 'rgb(0, 0, 255)' ) . ';"';
                        }
                        ?>
                        <?php selected( $integrazo_wz_option_value, $integrazo_wz_selected_event ); ?>>
                        <?php echo esc_html( $integrazo_wz_label_text ); ?>
                    </option>
                <?php endforeach; ?>
            </select>

        </div>

        <!-- Organization Selection -->
        <?php if (!empty($integrazo_wz_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 Inventory 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 ($integrazo_wz_orgs as $integrazo_wz_org) :
                        $integrazo_wz_oid   = isset($integrazo_wz_org['organization_id']) ? (string) $integrazo_wz_org['organization_id'] : '';
                        $integrazo_wz_oname = isset($integrazo_wz_org['name']) ? (string) $integrazo_wz_org['name'] : $integrazo_wz_oid;
                    ?>
                        <option
                            value="<?php echo esc_attr($integrazo_wz_oid); ?>"
                            <?php selected($integrazo_wz_oid, $integrazo_wz_selected_org_id); ?>>
                            <?php echo esc_html($integrazo_wz_oname); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endif; ?>

    <?php endif; ?>

    <!-- Save & Next Button -->
    <?php $integrazo_wz_all_selected = (!empty($integrazo_wz_form_id) && !empty($integrazo_wz_selected_event) && !empty($integrazo_wz_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($integrazo_wz_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($integrazo_wz_selected_event) && !empty($integrazo_wz_selected_org_id)) {

    $integrazo_wz_fields_response = [];

    if (!function_exists('integrazo_wz_render_zoho_inventory_sku_note')) {
        function integrazo_wz_render_zoho_inventory_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 Inventory.', 'integrazo-integration-for-zoho-apps'); ?>
                </p>
            </div>
<?php
        }
    }

    switch ($integrazo_wz_selected_event) {
        case 'create_contact':
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_create_contact_fields();
            break;

        case 'integrazo_wz_cm_update_contact':
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_update_contact_fields();
            break;

        case 'integrazo_wz_cm_create_item':
            integrazo_wz_render_zoho_inventory_sku_note();
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_create_items_fields();
            break;

        case 'integrazo_wz_cm_update_item':
            integrazo_wz_render_zoho_inventory_sku_note();
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_update_items_fields();
            break;

        case 'integrazo_wz_cm_create_inventory_adjustment':
            integrazo_wz_render_zoho_inventory_sku_note();

            $integrazo_wz_all_account_ids = $integrazo_wz_product_instance->get_adjustment_accounts($integrazo_wz_selected_org_id, true);
            if (empty($integrazo_wz_all_account_ids) || empty($integrazo_wz_all_account_ids['accounts'])) {
                $integrazo_wz_all_account_ids = null;
            }

            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_create_item_adjustment_fields($integrazo_wz_all_account_ids);
            break;

        case 'integrazo_wz_cm_create_sales_order':
            integrazo_wz_render_zoho_inventory_sku_note();
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_sales_order_fields();
            break;

        case 'integrazo_wz_cm_create_invoice':
            integrazo_wz_render_zoho_inventory_sku_note();
            $integrazo_wz_fields_response = $integrazo_wz_product_instance->get_invoice_fields();
            break;

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

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

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

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