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

declare(strict_types=1);

namespace Kutby\Pages;

use Kutby\Footer\Services\FooterVisibility;
use Kutby\ThemeOptions\FieldRegistry;

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

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

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

	/**
	 * {@inheritdoc}
	 */
	public function title(): string {
		return 'الفوتر';
	}

	/**
	 * {@inheritdoc}
	 */
	public function fields( array $options ): array {
		$values    = is_array( $options['footer'] ?? null ) ? $options['footer'] : array();
		$layout_id = isset( $values['layout'] ) ? sanitize_key( (string) $values['layout'] ) : '';
		$allowed   = FooterVisibility::visible_keys( $layout_id );
		$fields    = FieldRegistry::fields_for( 'footer', $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\[footer\]\[([a-z0-9_]+)\]/i', $name, $m ) ) {
			return sanitize_key( $m[1] );
		}

		return '';
	}
}
