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

declare(strict_types=1);

namespace Kutby\Pages;

use Kutby\Hero\Services\HeroVisibility;
use Kutby\ThemeOptions\FieldRegistry;

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

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

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

	/**
	 * {@inheritdoc}
	 */
	public function title(): string {
		return 'قسم البطل';
	}

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

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

		return $out;
	}

	/**
	 * @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\[hero\]\[([a-z0-9_]+)\]/i', $name, $m ) ) {
			return sanitize_key( $m[1] );
		}

		return '';
	}
}
