<?php
/**
 * Admin menu and React app bootstrap.
 *
 * @package Vist360
 */

namespace Vist360\Admin;

defined( 'ABSPATH' ) || exit;

use Vist360\Domain\TourPostType;
use Vist360\Domain\TourTemplates;
use Vist360\Domain\Settings;

/**
 * Registers the admin menu and enqueues the Ant Design React app.
 */
class Menu {

	const MENU_SLUG = 'vist360-tours';

	/**
	 * Hook registrations.
	 */
	public function register_hooks() {
		add_action( 'admin_menu', array( $this, 'add_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Register the admin menu pages.
	 */
	public function add_menu() {
		add_menu_page(
			__( '360° Tours', 'vistour-virtual-tour-builder' ),
			__( '360° Tours', 'vistour-virtual-tour-builder' ),
			'edit_posts',
			self::MENU_SLUG,
			array( $this, 'render_app' ),
			'dashicons-format-image',
			26
		);

		$submenus = array(
			''            => __( 'All Tours', 'vistour-virtual-tour-builder' ),
			'#/templates' => __( 'Add New Tour', 'vistour-virtual-tour-builder' ),
			'#/analytics' => __( 'Analytics', 'vistour-virtual-tour-builder' ),
			'#/settings'  => __( 'Settings', 'vistour-virtual-tour-builder' ),
		);

		foreach ( $submenus as $hash => $label ) {
			add_submenu_page(
				self::MENU_SLUG,
				$label,
				$label,
				'#/settings' === $hash ? 'manage_options' : 'edit_posts',
				self::MENU_SLUG . $hash,
				array( $this, 'render_app' )
			);
		}
	}

	/**
	 * Render the React application root.
	 */
	public function render_app() {
		echo '<div id="vist360-admin" class="vist360-admin-root"></div>';
	}

	/**
	 * Enqueue the admin app on plugin pages only.
	 *
	 * @param string $hook_suffix Current admin page hook suffix.
	 */
	public function enqueue_assets( $hook_suffix ) {
		if ( false === strpos( $hook_suffix, self::MENU_SLUG ) ) {
			return;
		}

		$asset_file = VIST360_DIR . 'assets/build/admin.asset.php';
		$asset      = file_exists( $asset_file )
			? include $asset_file
			: array(
				'dependencies' => array(),
				'version'      => VIST360_VERSION,
			);

		wp_enqueue_media();

		wp_enqueue_script(
			'vist360-admin',
			VIST360_URL . 'assets/build/admin.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		wp_enqueue_style(
			'vist360-admin',
			VIST360_URL . 'assets/build/admin.css',
			array(),
			$asset['version']
		);

		wp_set_script_translations( 'vist360-admin', 'vistour-virtual-tour-builder' );

		wp_add_inline_script(
			'vist360-admin',
			'window.vist360Admin = ' . wp_json_encode(
				array(
					'maxScenes'       => TourPostType::max_scenes(),
					'canManage'       => current_user_can( 'manage_options' ),
					'sceneTypes'      => TourPostType::SCENE_TYPES,
					'templates'       => TourTemplates::all(),
					'lockedTemplates' => TourTemplates::locked(),
					'viewerDefaults'  => Settings::viewer_defaults(),
					'pluginUrl'       => VIST360_URL,
				)
			) . ';',
			'before'
		);
	}
}
