<?php
namespace EVPB\Admin;

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

if ( !class_exists( 'Submenu' ) ) {
	class Submenu {
		public function __construct() {
			add_action( 'admin_menu', [ $this, 'adminMenu' ] );
			add_action( 'admin_enqueue_scripts', [ $this, 'adminEnqueueScripts' ] );
		}

		function adminMenu() {
			add_submenu_page(
				'tools.php',
				'Envision Page Builder - Plugin Envision',
				'Envision Page Builder',
				'manage_options',
				'envision-page-builder',
				function() {
					$evpbHasFSInfo = EVPB_HAS_FS ? [
						'hasFS' => true,
						'plan' => [
							'name' => evpb_fs()->get_plan_name(), 
							'title' => evpb_fs()->get_plan_title()
						],
						'miftah' => is_object( evpb_fs()->_get_license() ) ? evpb_fs()->_get_license()->secret_key : ''
					] : [];
				?>
					<div id='evpbDashboard' data-info='<?php echo esc_attr( json_encode( array_merge( [ 'version' => EVPB_VERSION, 'plan' => [ 'name' => 'free' ] ], $evpbHasFSInfo ) ) ); ?>'></div>
				<?php }
			);
		}

		function adminEnqueueScripts( $path ){
			if( strpos( $path, 'envision-page-builder' ) !== false ) {
				wp_enqueue_style( 'evpb-admin-dashboard', EVPB_DIR_URL . 'build/admin/dashboard.css', [], EVPB_VERSION );

				$dependencies = [ 'react', 'react-dom', 'wp-i18n', 'wp-data', 'wp-util' ];

				$asset_file = EVPB_DIR_PATH . 'build/admin/dashboard.asset.php';
				if ( file_exists( $asset_file ) ) {
					$asset = require_once $asset_file;
					$dependencies = array_merge( $asset['dependencies'], [ 'wp-util' ] );
				}

				wp_enqueue_script( 'evpb-admin-dashboard', EVPB_DIR_URL . 'build/admin/dashboard.js', $dependencies, EVPB_VERSION, true );

				wp_set_script_translations( 'evpb-admin-dashboard', 'envision-page-builder', EVPB_DIR_PATH . 'languages' );
			}
		}
	}
	new Submenu();
}