<?php
declare(strict_types=1);
namespace ConfManager\Admin;

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


use ConfManager\Traits\Singleton;
use ConfManager\Traits\HasHooks;
use ConfManager\Capabilities;

/**
 * WordPress管理画面メニューの登録とスクリプトエンキュー
 *
 * @since 1.0.0
 */
class AdminMenu {

	use Singleton;
	use HasHooks;

	/**
	 * 初期化
	 */
	protected function init(): void {
		$this->register_hooks();
	}

	/**
	 * フック登録
	 */
	protected function register_hooks(): void {
		$this->add_action( 'admin_menu', [ $this, 'register_menus' ] );
		$this->add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
	}

	/**
	 * 管理画面メニューを登録
	 */
	public function register_menus(): void {
		add_menu_page(
			__( 'Conference Manager', 'conferencemanager' ),
			__( 'Conference', 'conferencemanager' ),
			'conf_manager_access',
			'conferencemanager',
			[ $this, 'render_admin_page' ],
			'dashicons-groups',
			26
		);
	}

	/**
	 * 管理画面のReactアプリのマウントポイントを出力
	 */
	public function render_admin_page(): void {
		echo '<div id="conf-manager-admin-app"></div>';
	}

	/**
	 * 管理画面用スクリプト・スタイルをエンキュー
	 *
	 * @param string $hook_suffix 現在の管理画面フックサフィックス
	 */
	public function enqueue_scripts( string $hook_suffix ): void {
		if ( 'toplevel_page_conferencemanager' !== $hook_suffix ) {
			return;
		}

		$asset_file = CONF_MANAGER_PLUGIN_DIR . 'build/admin-app.asset.php';
		$asset      = file_exists( $asset_file )
			? require $asset_file
			: [ 'dependencies' => [], 'version' => CONF_MANAGER_VERSION ];

		wp_enqueue_script(
			'conf-manager-admin',
			CONF_MANAGER_PLUGIN_URL . 'build/admin-app.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		wp_set_script_translations(
			'conf-manager-admin',
			'conferencemanager',
			CONF_MANAGER_PLUGIN_DIR . 'languages'
		);

		wp_enqueue_style(
			'conf-manager-admin',
			CONF_MANAGER_PLUGIN_URL . 'admin/css/admin.css',
			[ 'wp-components' ],
			CONF_MANAGER_VERSION
		);

		wp_localize_script( 'conf-manager-admin', 'confManagerCaps', [
			'caps' => Capabilities::get_current_user_caps(),
		] );
	}
}
