<?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_wczo_form_id = INTEGRAZO_WCZO_Util::get_event_value($integration_data);
$selected_event       = $integration_data['integrazo_wczo_product_event'] ?? '';

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

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

    <?php echo wp_kses($event_html, INTEGRAZO_WCZO_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_wczo_product_event_select" class="integrazo-wczo-setup-lable" style="width:170px;margin-right:10px;">
                <?php esc_html_e('Select Action:', '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('Select what operation to perform in Zoho Inventory like creating an item or adjusting stock.', 'integrazo-wc-zoho-integration'); ?></p>
                    </div>
                </div>
            </label>

           <select
                name="integrazo_wczo_product_event"
                id="integrazo_wczo_product_event_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 ( $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_wczo_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 ); ?>"
                        data-priority="<?php echo esc_attr( isset( $ev['priority'] ) ? (int) $ev['priority'] : 0 ); ?>"
                        <?php
                        if ( $is_disabled ) {
                            echo 'disabled="disabled" title="' . esc_attr__( 'Upgrade to Pro to unlock Zoho Inventory action.', 'integrazo-wc-zoho-integration' ) . '"';
                        } 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_wczo_product_orgid" class="integrazo-wczo-setup-lable" style="width:170px;margin-right:10px;">
                    <?php esc_html_e('Select Organization:', '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 which Zoho Inventory organization this integration will use.', 'integrazo-wc-zoho-integration'); ?></p>
                        </div>
                    </div>
                </label>

                <select
                    name="integrazo_wczo_product_orgid"
                    id="integrazo_wczo_product_orgid"
                    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 ($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_wczo_form_id) && !empty($selected_event) && !empty($selected_org_id)); ?>
    <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($all_selected ? 'display:none;' : ''); ?>">
            <?php esc_html_e('Save & Next', 'integrazo-wc-zoho-integration'); ?>
        </button>
    </div>
</form>

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

    $fields_response = [];

    if (!function_exists('integrazo_wczo_render_zoho_inventory_sku_note')) {
        function integrazo_wczo_render_zoho_inventory_sku_note()
        {
?>
            <div class="integrazo-wczo-setup-step2-note-bottom" style="margin-left: 170px !important; max-width: 71.5% !important;">
                <p>
                    <strong><?php esc_html_e('Note:', 'integrazo-wc-zoho-integration'); ?></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-wc-zoho-integration'); ?>
                </p>
            </div>
<?php
        }
    }

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

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

        case 'integrazo_wczo_cm_create_item':
            integrazo_wczo_render_zoho_inventory_sku_note();
            $fields_response = $product_instance->get_create_items_fields();
            break;

        case 'integrazo_wczo_cm_update_item':
            integrazo_wczo_render_zoho_inventory_sku_note();
            $fields_response = $product_instance->get_update_items_fields();
            break;

        case 'integrazo_wczo_cm_create_inventory_adjustment':
            integrazo_wczo_render_zoho_inventory_sku_note();

            $all_account_ids = $product_instance->get_adjustment_accounts($selected_org_id, true);
            if (empty($all_account_ids) || empty($all_account_ids['accounts'])) {
                $all_account_ids = null;
            }

            $fields_response = $product_instance->get_create_item_adjustment_fields($all_account_ids);
            break;

        case 'integrazo_wczo_cm_create_sales_order':
            integrazo_wczo_render_zoho_inventory_sku_note();
            $fields_response = $product_instance->get_sales_order_fields();
            break;

        case 'integrazo_wczo_cm_create_invoice':
            integrazo_wczo_render_zoho_inventory_sku_note();
            $fields_response = $product_instance->get_invoice_fields();
            break;

        default:
            $fields_response = [
                'error' => __('Unknown event selected.', 'integrazo-wc-zoho-integration'),
            ];
            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_WCZO_PLUGIN_DIR . 'src/products/pre-mapping.php';
}
?>