<?php
defined( 'ABSPATH' ) || exit;

/**
 * Registers the admin menu page and serves the React app as a full standalone page.
 */
class WAD_Admin {

	public static function init() {
		add_action( 'admin_menu', [ __CLASS__, 'register_menu' ] );
		add_action( 'admin_init', [ __CLASS__, 'maybe_serve_standalone' ] );
	}

	public static function register_menu() {
		$capability = self::get_required_capability();

		add_submenu_page(
			'woocommerce',
			__( 'Analytics Dashboard', 'woo-analytics-dashboard' ),
			__( 'Analytics Dashboard', 'woo-analytics-dashboard' ),
			$capability,
			'woo-analytics-dashboard',
			'__return_null'
		);
	}

	/**
	 * Intercept the page request early and serve a full standalone HTML page,
	 * completely bypassing the WordPress admin chrome.
	 */
	public static function maybe_serve_standalone() {
		if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'woo-analytics-dashboard' ) {
			return;
		}

		if ( ! is_user_logged_in() || ! current_user_can( self::get_required_capability() ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'woo-analytics-dashboard' ) );
		}

		$asset_file  = WAD_PLUGIN_DIR . 'build/index.asset.php';
		$asset       = file_exists( $asset_file )
			? include $asset_file
			: [ 'dependencies' => [], 'version' => WAD_VERSION ];
		$script_url  = WAD_PLUGIN_URL . 'build/index.js';
		$style_url   = WAD_PLUGIN_URL . 'build/index.css';
		$has_css     = file_exists( WAD_PLUGIN_DIR . 'build/index.css' );
		$ver         = esc_attr( $asset['version'] );

		$data = wp_json_encode( [
			'apiUrl'       => rest_url( 'wooinsight/v1' ),
			'nonce'        => wp_create_nonce( 'wp_rest' ),
			'currency'     => html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8' ),
			'currencyCode' => get_woocommerce_currency(),
			'siteUrl'      => get_site_url(),
			'aiEnabled'    => (bool) get_option( 'wad_ai_enabled', true ),
			'dashName'     => get_option( 'wad_dashboard_name', 'WooCommerce' ),
		] );

		// Build the dependency chain (react, react-dom must load before the bundle).
		ob_start();
		wp_print_scripts( $asset['dependencies'] );
		$dep_scripts = ob_get_clean();

		header( 'Content-Type: text/html; charset=UTF-8' );
		?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title><?php echo esc_html( get_option( 'wad_dashboard_name', 'Analytics Dashboard' ) ); ?></title>
	<style>
		*, *::before, *::after { box-sizing: border-box; }
		html, body { margin: 0; padding: 0; height: 100%; background: #0f1117; }
		#woo-insight-dashboard { height: 100%; }
	</style>
	<?php if ( $has_css ) : ?>
	<link rel="stylesheet" href="<?php echo esc_url( $style_url ); ?>?ver=<?php echo $ver; ?>">
	<?php endif; ?>
	<?php echo $dep_scripts; // phpcs:ignore WordPress.Security.EscapeOutput ?>
</head>
<body>
	<div id="woo-insight-dashboard"></div>
	<script>
		window.wooInsightData = <?php echo $data; // phpcs:ignore WordPress.Security.EscapeOutput ?>;
	</script>
	<script src="<?php echo esc_url( $script_url ); ?>?ver=<?php echo $ver; ?>"></script>
</body>
</html>
		<?php
		exit;
	}

	/**
	 * Returns the WordPress capability required to view the dashboard.
	 * Defaults to manage_woocommerce (Shop Manager and above).
	 */
	private static function get_required_capability(): string {
		$stored = get_option( 'wad_min_role', 'manage_woocommerce' );
		return in_array( $stored, [ 'manage_woocommerce', 'manage_options' ], true )
			? $stored
			: 'manage_woocommerce';
	}
}
