<?php
/**
 * Per-request registry of FormOrderShims keyed by order_id.
 *
 * Reason this exists: OrderDataRepository::save_order_data() / delete_order_data()
 * receive an `$order_id` (int) and resolve it with the shop order lookup, which
 * returns false for our Pay4All Form order IDs. Rather than re-write those calls, we let
 * the registry surface a registered shim through the
 * `p4all_pro_resolve_order_for_meta` filter (wired in FormIntegration).
 *
 * The registry is in-process only; it's repopulated by the launcher / the webhook
 * handler at the top of each request that needs it.
 */

namespace Twnt4All\Pay4All;

if ( ! defined( 'ABSPATH' ) ) { exit; }

final class FormOrderRegistry
{
    /** @var array<int,FormOrderShim> */
    private static $shims = [];

    public static function register( FormOrderShim $shim ) : void
    {
        self::$shims[ $shim->get_id() ] = $shim;
    }

    public static function get( int $order_id ) : ?FormOrderShim
    {
        return self::$shims[ $order_id ] ?? null;
    }

    /**
     * Lazy-resolve: if not yet in the registry, attempt to build one from the
     * underlying p4all_order CPT. Returns null if the post type doesn't match
     * (so non-form lookups fall through to the shop order lookup untouched).
     */
    public static function get_or_load( int $order_id ) : ?FormOrderShim
    {
        $cached = self::get( $order_id );
        if ( $cached ) { return $cached; }
        if ( ! FormOrderShim::is_form_order_id( $order_id ) ) { return null; }
        $shim = new FormOrderShim( $order_id );
        self::register( $shim );
        return $shim;
    }
}
