<?php

/**
 * 
 * 
 */

namespace IvrVP1\Includes\Backend;

class CreateMenuPages {


	public function __construct() {
		add_action('admin_menu', [$this, 'create_menu_pages']);
		add_action('admin_enqueue_scripts', [$this, 'register_scripts_and_styles']);
		add_filter('script_loader_tag', [$this, 'add_type_module'], 10, 3);
	} // end __construct()


	public function add_type_module($tag, $handle, $src) {
		if ('vuejs' !== $handle) {
			return $tag;
		}

		$tag = '<script type="module" src="' . esc_url($src) . '"></script>';
		return $tag;
	} // end add_type_module()



	public function register_scripts_and_styles() {
		$this->load_scripts();
		$this->load_styles();
	} // end register_scripts_and_styles()



	public function load_scripts() {

		$script_url = PLUGIN_URL . 'vueapp/dist/assets/js/index.js';
		wp_enqueue_script('vuejs', $script_url, array(), PLUGIN_VERSION, true);

		$api_url = get_site_url() . '/wp-json/' . REST_NAMESPACE . '/' . REST_BASE;
		
		$jsData = [
			'api_url' => $api_url,
			'nonce' => wp_create_nonce('wp_rest'),
			'page_slug' => $_GET['page'],
		];

		wp_localize_script('vuejs', 'jsData', $jsData);
	} // end load_scripts()



	public function load_styles() {
		$style_url = PLUGIN_URL . 'vueapp/dist/assets/css/index.css';
		wp_enqueue_style('vuestyle', $style_url, array(), PLUGIN_VERSION, false);
	} // end load_styles()


	public function create_menu_pages() {

		global $submenu;

		add_menu_page(
			ADMIN_PAGE_TITLE,   						// Admin menu page title
			LEFT_MENU_TEXT,          				// menu text on left panel
			CAPABILITY,               			// capability or permissions
			SLUG,                          	// url slug
			[$this, 'menu_page_display'],		// display template
			MENU_ICON,											// icon
			POSITION,												// menu item position
		);

		if (current_user_can(CAPABILITY)) {
			$submenu[SLUG][] = ['List All', 'manage_options', 'admin.php?page=' . SLUG . '#/'];
			$submenu[SLUG][] = ['Add New', 'manage_options', 'admin.php?page=' . SLUG . '#/add-new'];
		}
	} // end create_menu_pages()


	public function menu_page_display() {
?>
		<div class="wrap">
			<h1><?php echo esc_html(get_admin_page_title());?></h1>
			<div id="<?= VUEAPP_MOUNT; ?>">
				<h3>Content here will be replaced by Vue.app</h3>
			</div>
		</div>
<?php

	} // end menu_page_display()

} // end class CreateMenuPages