<?php
/**
 * Header options page — layout-scoped field visibility.
 *
 * @package Kutby
 * @since   2.6.0
 */

declare(strict_types=1);

namespace Kutby\Pages;

use Kutby\Header\Services\HeaderVisibility;
use Kutby\ThemeOptions\FieldRegistry;

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

/**
 * Class HeaderPage
 */
final class HeaderPage extends AbstractPage {

	/**
	 * {@inheritdoc}
	 */
	public function id(): string {
		return 'header';
	}

	/**
	 * {@inheritdoc}
	 */
	public function title(): string {
		return 'الهيدر';
	}

	/**
	 * {@inheritdoc}
	 */
	public function fields( array $options ): array {
		$values    = is_array( $options['header'] ?? null ) ? $options['header'] : array();
		$layout_id = isset( $values['layout'] ) ? sanitize_key( (string) $values['layout'] ) : '';
		$allowed   = HeaderVisibility::visible_keys( $layout_id );
		$fields    = FieldRegistry::fields_for( 'header', $values );
		$out       = array();

		foreach ( $fields as $field ) {
			$key = self::field_key( $field );
			if ( '' === $key || in_array( $key, $allowed, true ) ) {
				$out[] = $field;
			}
		}

		return $out;
	}

	/**
	 * Extract schema key from field payload.
	 *
	 * @param array<string, mixed> $field Field.
	 * @return string
	 */
	private static function field_key( array $field ): string {
		if ( isset( $field['key'] ) ) {
			return sanitize_key( (string) $field['key'] );
		}

		$name = (string) ( $field['name'] ?? '' );
		if ( preg_match( '/kutby\[header\]\[([a-z0-9_]+)\]/i', $name, $m ) ) {
			return sanitize_key( $m[1] );
		}

		return '';
	}
}
