<?php

namespace CustomAdminFooterText;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'custom-admin-footer-text';
	private const MODULE_VERSION = '1.2.1';

	private ?array $settings_cache = null;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Custom Admin Footer Text', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Custom footer text on every dashboard screen—brand it or keep it minimal.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin' ];
	}

	protected function registerHooks(): void {
		if ( ! is_admin() ) {
			return;
		}

		add_filter( 'admin_footer_text', [ $this, 'filterFooterLeft' ], 20 );
		add_filter( 'update_footer', [ $this, 'filterFooterRight' ], 20 );
	}

	public function filterFooterLeft( string $text ): string {
		$left = $this->getSettings()['footer_left'] ?? '';
		$left = is_string( $left ) ? trim( $left ) : '';
		if ( $left === '' ) {
			return $text;
		}
		return wp_kses_post( $left );
	}

	public function filterFooterRight( string $text ): string {
		$right = $this->getSettings()['footer_right'] ?? '';
		$right = is_string( $right ) ? trim( $right ) : '';
		if ( $right === '' ) {
			return '';
		}
		return wp_kses_post( $right );
	}

	private function getSettings(): array {
		if ( $this->settings_cache !== null ) {
			return $this->settings_cache;
		}

		$settings = $this->moduleSettings()->all( [] );
		$settings = is_array( $settings ) ? $settings : [];
		$defaults = $this->getDefaultSettings();
		$this->settings_cache = array_merge( $defaults, $settings );

		if ( ( $this->settings_cache['footer_left'] ?? '' ) === ''
			&& isset( $this->settings_cache['footer_text'] )
			&& is_string( $this->settings_cache['footer_text'] )
			&& trim( $this->settings_cache['footer_text'] ) !== ''
		) {
			$this->settings_cache['footer_left'] = $this->settings_cache['footer_text'];
		}

		return $this->settings_cache;
	}

	public function getDefaultSettings(): array {
		return [
			'footer_left'  => '',
			'footer_right' => '',
		];
	}
}
