<?php

namespace GOS\GravityOps\Core\SuiteCore;

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

/**
 * Shared admin asset loader for GravityOps screens.
 */
class AdminAssetHelper {

	/**
	 * SuiteCore instance.
	 *
	 * @var SuiteCore
	 */
	private SuiteCore $core;

	/**
	 * Constructor method for initializing the class with a SuiteCore instance.
	 *
	 * @param SuiteCore $core Instance of SuiteCore to be assigned to the class.
	 *
	 * @return void
	 */
	public function __construct( SuiteCore $core ) {
		$this->core = $core;
	}

	/**
	 * Enqueue GravityOps admin assets for the current screen.
	 *
	 * @param bool $is_shell_page True when viewing a GravityOps shell page.
	 * @param bool $is_freemius   True when viewing a Freemius page.
	 * @param bool $is_gf_page    True when viewing a Gravity Forms page.
	 *
	 * @return bool True when assets were enqueued.
	 */
	public function enqueue( bool $is_shell_page, bool $is_freemius, bool $is_gf_page ): bool {
		$load_globally = $this->core->config()->load_admin_assets_globally();

		if ( ! $is_shell_page && ! $is_freemius && ! $is_gf_page && ! $load_globally ) {
			return false;
		}

		$assets  = $this->core->shell()->resolve_assets_urls();
		$version = SuiteCore::VERSION;

		if ( empty( $assets['css'] ) && empty( $assets['js'] ) && empty( $assets['menu_css'] ) ) {
			return false;
		}

		// Load minimal menu/icon CSS globally or on GF pages.
		if ( ! empty( $assets['menu_css'] ) ) {
			wp_enqueue_style( 'gravityops-menu', $assets['menu_css'], [], $version );
		}

		// Load the full admin UI CSS only on our shell or Freemius pages.
		if ( ! empty( $assets['css'] ) && ( $is_shell_page || $is_freemius ) ) {
			wp_enqueue_style( 'gravityops-admin', $assets['css'], [ 'gravityops-menu' ], $version );
		}

		// We only need the JS on our shell pages or Freemius pages where we inject tabs.
		if ( $is_shell_page || $is_freemius ) {
			if ( ! empty( $assets['js'] ) ) {
				wp_enqueue_script( 'gravityops-admin', $assets['js'], [ 'jquery' ], $version, true );
				wp_localize_script(
					'gravityops-admin',
					'gopsAdmin',
					[
						'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
						'nonce'      => wp_create_nonce( 'gops_admin' ),
						'baseUrl'    => admin_url( 'admin.php?page=gravity_ops' ),
						'updatesUrl' => add_query_arg( 'gops_filter', 'updates', admin_url( 'admin.php?page=gravity_ops' ) ),
					]
				);
			}
			// On Freemius pages also load a small override stylesheet to hide native tabs safely.
			if ( $is_freemius && ! empty( $assets['css'] ) ) {
				$fs_css = trailingslashit( dirname( $assets['css'] ) ) . 'freemius.css';
				wp_enqueue_style( 'gravityops-freemius', $fs_css, [ 'gravityops-admin' ], $version );
			}
		}

		return true;
	}
}
