<?php
/**
 * Menu Handler
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Handlers\Menu
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Handlers\Menu;

use MOWCPS\Common\Utils\Utils;
use MOWCPS\Common\Constants\Constants;

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

/**
 * Class Menu_Handler
 *
 * Handles menu-related functionality implementation
 */
class Menu_Handler {

	/**
	 * Register the admin menu
	 *
	 * @return void
	 */
	public static function register_menu() {
		add_menu_page(
			'Products Sync for WooCommerce',
			'Products Sync for WooCommerce',
			'manage_options',
			'sync-to-woocommerce',
			array( __CLASS__, 'render_app_container' ),
			MOWCPS_PLUGIN_URL . 'views/assets/images/miniorange-logo.png',
			56
		);
	}

	/**
	 * Render the React app container
	 *
	 * @return void
	 */
	public static function render_app_container() {
		echo '<div id="sync-to-woocommerce"></div>';
	}

	/**
	 * Enqueue necessary assets
	 *
	 * @return void
	 */
	public static function enqueue_assets() {
		$plan_name = str_replace( 'wp_rest_woocommerce_sync_', '', Constants::MOWCPS_PLAN_NAME );
		$plan_name = str_replace( '_plan', '', $plan_name );

		wp_enqueue_style(
			'plugin_fonts',
			plugin_dir_url( MOWCPS_PLUGIN_DIR . 'index.php' ) . 'views/assets/fonts/fonts.css',
			array(),
			'1.0',
			null
		);

		wp_enqueue_style(
			'wcps-react-app-style',
			plugin_dir_url( dirname( __DIR__, 3 ) ) . 'views/build/products-sync-for-woocommerce.css',
			array(),
			'1.0'
		);

		wp_enqueue_script(
			'wcps-react-app',
			plugin_dir_url( dirname( __DIR__, 3 ) ) . 'views/build/assets/index.js',
			array(),
			'1.0',
			true
		);

		wp_localize_script(
			'wcps-react-app',
			'MOWCPSData',
			array(
				'pluginUrl' => plugin_dir_url( MOWCPS_PLUGIN_DIR . 'index.php' ),
				'siteUrl'   => site_url(),
				'restNonce' => wp_create_nonce( 'wp_rest' ),
				'restUrl'   => rest_url( 'mowcps/v1' ),
				'plan'      => $plan_name,
			)
		);
	}

	/**
	 * Check if dev mode should be enabled
	 *
	 * @return bool
	 */
	public static function should_enable_dev_mode() {
		$screen = get_current_screen();
		return $screen && 'toplevel_page_sync-to-woocommerce' === $screen->id;
	}

	/**
	 * Initialize development mode
	 *
	 * @return void
	 */
	public static function initialize_dev_mode() {
		?>
		<script type="module">
			import RefreshRuntime from 'http://localhost:5174/@react-refresh';
			RefreshRuntime.injectIntoGlobalHook(window);
			window.$RefreshReg$ = () => {};
			window.$RefreshSig$ = () => (type) => type;
			window.__vite_plugin_react_preamble_installed__ = true;
		</script>
		<script type="module" src="http://localhost:5174/@vite/client"></script>
		<script type="module" src="http://localhost:5174/src/main.jsx"></script>
		<?php
	}
}
