<?php
/**
 * Footer option field visibility — single source of truth.
 *
 * @package Kutby
 * @since   2.7.0
 */

declare(strict_types=1);

namespace Kutby\Footer\Services;

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

/**
 * Class FooterVisibility
 */
final class FooterVisibility {

	/**
	 * Always-visible footer keys.
	 *
	 * @var array<int, string>
	 */
	public const ALWAYS_VISIBLE = array( 'layout' );

	/**
	 * @param string $layout_id Layout id.
	 * @return array<int, string>
	 */
	public static function visible_keys( string $layout_id = '' ): array {
		$layout_id = sanitize_key( $layout_id );
		if ( '' === $layout_id ) {
			$layout_id = FooterManager::DEFAULT_LAYOUT;
		}

		$allowed  = self::ALWAYS_VISIBLE;
		$registry = FooterRegistry::instance();
		$layout   = $registry->make( $layout_id );

		if ( null === $layout ) {
			$layout = $registry->make( FooterManager::DEFAULT_LAYOUT );
		}

		if ( null !== $layout ) {
			$allowed = array_merge( $allowed, $layout->option_keys() );
		}

		return array_values( array_unique( $allowed ) );
	}

	/**
	 * @param array<string, mixed> $posted  Posted footer group.
	 * @param array<string, mixed> $current Stored footer group.
	 * @return array<int, string>
	 */
	public static function visible_keys_from_values( array $posted, array $current = array() ): array {
		$layout_id = '';
		if ( isset( $posted['layout'] ) && is_scalar( $posted['layout'] ) ) {
			$layout_id = sanitize_key( (string) $posted['layout'] );
		}
		if ( '' === $layout_id && isset( $current['layout'] ) && is_scalar( $current['layout'] ) ) {
			$layout_id = sanitize_key( (string) $current['layout'] );
		}

		return self::visible_keys( $layout_id );
	}

	/**
	 * @param string $key       Field key.
	 * @param string $layout_id Layout id.
	 * @return bool
	 */
	public static function is_visible( string $key, string $layout_id = '' ): bool {
		return in_array( sanitize_key( $key ), self::visible_keys( $layout_id ), true );
	}
}
