<?php
/**
 * Footer manager — resolve selected layout.
 *
 * @package Kutby
 * @since   2.7.0
 */

declare(strict_types=1);

namespace Kutby\Footer\Services;

use Kutby\Footer\Contracts\FooterLayoutInterface;
use Kutby\Footer\Support\FooterContext;

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

/**
 * Class FooterManager
 */
final class FooterManager {

	public const DEFAULT_LAYOUT = 'classic';

	/**
	 * @return FooterLayoutInterface
	 */
	public function layout(): FooterLayoutInterface {
		$ctx      = FooterContext::from_request();
		$id       = $ctx->layout_id();
		$registry = FooterRegistry::instance();

		$layout = $registry->make( $id );
		if ( null !== $layout ) {
			return $layout;
		}

		$fallback = $registry->make( self::DEFAULT_LAYOUT );
		if ( null !== $fallback ) {
			return $fallback;
		}

		foreach ( $registry->all() as $class ) {
			if ( is_subclass_of( $class, FooterLayoutInterface::class ) ) {
				return new $class();
			}
		}

		throw new \RuntimeException( 'No Kutby footer layouts registered.' );
	}
}
