<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Layouts;

defined('ABSPATH') || exit;

/**
 * Resolves the layout source the site is using.
 *
 * The bundled source is the answer unless something registers another. That
 * registration is a filter, so a package which adds saved, editable layouts
 * supplies them by answering the filter — no caller needs to know it exists, and
 * nothing here has to enumerate what might.
 */
final class LocatorLayouts
{
    /** Resolved once per request; the filter result is not expected to change. */
    private static ?LocatorLayoutSource $source = null;

    public static function source(): LocatorLayoutSource
    {
        if (self::$source instanceof LocatorLayoutSource) {
            return self::$source;
        }

        /**
         * Filter the source of locator layouts.
         *
         * Replace this to store layouts somewhere else — a post type, a remote
         * service, an editable table. Anything not implementing
         * {@see LocatorLayoutSource} is ignored, so a bad filter degrades to the
         * bundled locator instead of breaking every placement on the site.
         *
         * @param LocatorLayoutSource $source
         */
        $source = apply_filters('cliq_sl_locator_layout_source', new BundledLocatorLayouts());

        return self::$source = $source instanceof LocatorLayoutSource
            ? $source
            : new BundledLocatorLayouts();
    }

    /** Drop the resolved source. For tests, and for a request that re-registers. */
    public static function reset(): void
    {
        self::$source = null;
    }
}
