<?php
/**
 * Abstract Options Page
 *
 * @package Kutby
 * @since   1.0.0
 */

declare(strict_types=1);

namespace Kutby\Pages;

use Kutby\Admin\UI\Components;
use Kutby\Fields\Field;

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

/**
 * Class AbstractPage
 */
abstract class AbstractPage {

	/**
	 * @return string
	 */
	abstract public function id(): string;

	/**
	 * @return string
	 */
	abstract public function title(): string;

	/**
	 * @param array<string, mixed> $options All options.
	 * @return array<int, array<string, mixed>>
	 */
	abstract public function fields( array $options ): array;

	/**
	 * @param array<string, mixed> $options Options.
	 * @return void
	 */
	public function render( array $options ): void {
		$fields = $this->fields( $options );

		Components::panel_start( $this->title() );
		?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="kutby-panel__form">
			<input type="hidden" name="action" value="kutby_save_options" />
			<input type="hidden" name="kutby_panel" value="<?php echo esc_attr( $this->id() ); ?>" />
			<?php wp_nonce_field( 'kutby_save_options', 'kutby_nonce' ); ?>

			<div class="kutby-cards">
				<?php foreach ( $fields as $field ) : ?>
					<?php
					ob_start();
					Field::render( $field );
					$control = (string) ob_get_clean();
					Components::card(
						(string) ( $field['title'] ?? '' ),
						$control,
						(string) ( $field['hint'] ?? '' ),
						(string) ( $field['id'] ?? '' )
					);
					?>
				<?php endforeach; ?>
			</div>

			<?php $this->extra( $options ); ?>

			<footer class="kutby-panel__footer">
				<?php
				echo Components::button( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in Components.
					'حفظ الإعدادات',
					array(
						'type'  => 'submit',
						'class' => 'kutby-btn--primary',
					)
				);
				?>
			</footer>
		</form>
		<?php
		Components::panel_end();
	}

	/**
	 * @param array<string, mixed> $options Options.
	 * @return void
	 */
	protected function extra( array $options ): void {}

	/**
	 * @param string $group Group.
	 * @param string $key   Key.
	 * @return string
	 */
	protected function name( string $group, string $key ): string {
		return sprintf( 'kutby[%s][%s]', $group, $key );
	}

	/**
	 * @param string $group Group.
	 * @param string $key   Key.
	 * @return string
	 */
	protected function fid( string $group, string $key ): string {
		return sprintf( 'kutby_%s_%s', $group, $key );
	}
}
