<?php

namespace VendorTasksDokanClickUp\Settings;

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

/**
 * Assets Handler
 *
 * Handles enqueueing of admin and frontend assets
 *
 * @since      1.0.0
 * @package VendorTasksDokanClickUp
 * @subpackage Settings
 */
class Assets {

	/**
	 * WordPress core style handles captured before plugins register theirs.
	 *
	 * @since 1.2.0
	 * @var string[]
	 */
	private array $core_style_handles = array();

	/**
	 * WordPress core script handles captured before plugins register theirs.
	 *
	 * @since 1.2.0
	 * @var string[]
	 */
	private array $core_script_handles = array();

	/**
	 * Class constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_head', array( $this, 'suppress_admin_notices' ), 1 );
		add_action( 'admin_enqueue_scripts', array( $this, 'snapshot_core_handles' ), 1 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'dequeue_third_party_assets' ), PHP_INT_MAX );
		add_filter( 'admin_footer_text', array( $this, 'remove_footer_text' ) );
		add_filter( 'update_footer', array( $this, 'remove_footer_text' ), PHP_INT_MAX );
	}

	/**
	 * Remove all admin notices from the plugin settings page.
	 *
	 * Fires at admin_head priority 1 — before any plugin adds notice output —
	 * so both standard WP notices and third-party notices are suppressed.
	 * Our own settings_errors() feedback (saved/error) is intentionally kept
	 * because that output fires from our template, not these hooks.
	 *
	 * @since 1.2.0
	 *
	 * @return void
	 */
	public function suppress_admin_notices(): void {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return;
		}

		$screen = get_current_screen();
		if ( ! $screen || 'toplevel_page_vendor-tasks-dokan-clickup' !== $screen->id ) {
			return;
		}

		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );
		remove_all_actions( 'network_admin_notices' );
		remove_all_actions( 'user_admin_notices' );
	}

	/**
	 * Remove the WP admin footer text on the plugin's own screen.
	 *
	 * @since 1.3.0
	 *
	 * @param string $text Default footer text.
	 * @return string Empty string on the plugin screen, original value elsewhere.
	 */
	public function remove_footer_text( string $text ): string {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return $text;
		}

		$screen = get_current_screen();
		if ( $screen && 'toplevel_page_vendor-tasks-dokan-clickup' === $screen->id ) {
			return '';
		}

		return $text;
	}

	/**
	 * Snapshot all handles registered by WordPress core before any plugin
	 * gets a chance to enqueue at admin_enqueue_scripts priority 10+.
	 *
	 * Called at admin_enqueue_scripts priority 1 — WP_Styles is initialized
	 * by this point (wp_default_styles() has already run) but no plugin or
	 * theme has enqueued yet. Used by dequeue_third_party_assets() as the
	 * authoritative allowlist of core handles to always keep.
	 *
	 * @since 1.2.0
	 *
	 * @return void
	 */
	public function snapshot_core_handles(): void {
		global $wp_styles, $wp_scripts;

		if ( $wp_styles instanceof \WP_Styles ) {
			$this->core_style_handles = array_keys( $wp_styles->registered );
		}

		if ( $wp_scripts instanceof \WP_Scripts ) {
			$this->core_script_handles = array_keys( $wp_scripts->registered );
		}
	}

	/**
	 * Enqueue admin assets
	 *
	 * @since 1.0.0
	 *
	 * @param string $hook Current admin page hook.
	 *
	 * @return void
	 */
	public function enqueue_admin_assets( string $hook ): void {
		// Freemius pricing / checkout pages (hook contains the plugin slug).
		if ( false !== strpos( $hook, 'vendor-tasks-dokan-clickup-pricing' ) ||
			false !== strpos( $hook, 'vendor-tasks-dokan-clickup-checkout' ) ) {
			wp_enqueue_style(
				'vendor-tasks-dokan-clickup-freemius-pricing',
				VENDOR_TASKS_DOKAN_CLICKUP_URL . 'assets/css/freemius-pricing.css',
				array(),
				VENDOR_TASKS_DOKAN_CLICKUP_VERSION
			);
		}

		// Freemius account page.
		if ( false !== strpos( $hook, 'vendor-tasks-dokan-clickup-account' ) ) {
			wp_enqueue_style(
				'vendor-tasks-dokan-clickup-freemius-account',
				VENDOR_TASKS_DOKAN_CLICKUP_URL . 'assets/css/freemius-account.css',
				array(),
				VENDOR_TASKS_DOKAN_CLICKUP_VERSION
			);
		}

		// Vendor-profile script on user edit pages
		if ( in_array( $hook, array( 'user-edit.php', 'profile.php' ), true ) ) {
			$vp_asset_file = VENDOR_TASKS_DOKAN_CLICKUP_PATH . 'build/vendor-profile.asset.php';
			if ( file_exists( $vp_asset_file ) ) {
				$vp_asset = require $vp_asset_file;
				wp_enqueue_script(
					'vendor-tasks-dokan-clickup-vendor-profile',
					VENDOR_TASKS_DOKAN_CLICKUP_URL . 'build/vendor-profile.js',
					$vp_asset['dependencies'] ?? array(),
					$vp_asset['version'] ?? VENDOR_TASKS_DOKAN_CLICKUP_VERSION,
					true
				);
			}
		}

		// Freemius admin notices — shown on any admin page, enqueue globally.
		wp_enqueue_style(
			'vendor-tasks-dokan-clickup-freemius-notices',
			VENDOR_TASKS_DOKAN_CLICKUP_URL . 'assets/css/freemius-notices.css',
			array(),
			VENDOR_TASKS_DOKAN_CLICKUP_VERSION
		);

		// Only load admin settings script on plugin settings page
		if ( 'toplevel_page_vendor-tasks-dokan-clickup' !== $hook ) {
			return;
		}

		$asset_file = VENDOR_TASKS_DOKAN_CLICKUP_PATH . 'build/admin.asset.php';
		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;
		$deps  = $asset['dependencies'] ?? array();
		$ver   = $asset['version'] ?? VENDOR_TASKS_DOKAN_CLICKUP_VERSION;

		// Enqueue admin styles
		wp_enqueue_style(
			'vendor-tasks-dokan-clickup-admin',
			VENDOR_TASKS_DOKAN_CLICKUP_URL . 'build/style-admin.css',
			array(),
			$ver
		);

		wp_add_inline_style(
			'vendor-tasks-dokan-clickup-admin',
			'#wpcontent { padding-left: 0; } #wpbody-content { padding: 0; } .wrap { margin: 0; }'
		);

		// Freemius opt-in / connect page styles (no-op when #fs_connect is absent).
		wp_enqueue_style(
			'vendor-tasks-dokan-clickup-freemius-connect',
			VENDOR_TASKS_DOKAN_CLICKUP_URL . 'assets/css/freemius-connect.css',
			array( 'vendor-tasks-dokan-clickup-admin' ),
			VENDOR_TASKS_DOKAN_CLICKUP_VERSION
		);

		// Enqueue admin scripts with WordPress dependencies
		wp_enqueue_script(
			'vendor-tasks-dokan-clickup-admin',
			VENDOR_TASKS_DOKAN_CLICKUP_URL . 'build/admin.js',
			$deps,
			$ver,
			true
		);

		$settings           = get_option( 'vendor_tasks_dokan_clickup_settings', array() );
		$api_token_exists   = ! empty( $settings['api_token'] );
		$plan_manager       = vendor_tasks_dokan_clickup()->plan_manager();
		$license_key_exists = ! empty( $settings['license_key'] );

		// Localize script with REST API endpoint and i18n strings for dynamic JS
		wp_localize_script(
			'vendor-tasks-dokan-clickup-admin',
			'vendorTasksAdmin',
			array(
				'restUrl'            => rest_url( 'vendor-tasks-dokan-clickup/v1' ),
				'nonce'              => wp_create_nonce( 'wp_rest' ),
				'namespace'          => 'vendor-tasks-dokan-clickup/v1',
				'apiTokenExists'     => $api_token_exists,
				'plan'               => $plan_manager->plan(),
				'proFeatures'        => $plan_manager->pro_features(),
				'licenseKeyExists'   => $license_key_exists,
				'proPlugin'          => class_exists( 'Vendor_Tasks_DokanClickUp_Pro' ),
				'freemiusSdkLoaded'  => function_exists( 'vendor_tasks_dokan_clickup_freemius' ) && null !== vendor_tasks_dokan_clickup_freemius(),
				'freemiusUpgradeUrl' => $plan_manager->freemius_upgrade_url(),
				'freemiusAccountUrl' => $plan_manager->freemius_account_url(),
				'webhookActions'     => array(
					'enable_vendor'      => __( 'Enable Vendor (dokan_enable_selling=yes)', 'alamin-vendor-tasks-dokan-clickup' ),
					'disable_vendor'     => __( 'Disable Vendor (dokan_enable_selling=no)', 'alamin-vendor-tasks-dokan-clickup' ),
					'send_welcome_email' => __( 'Fire Welcome Email Action', 'alamin-vendor-tasks-dokan-clickup' ),
					'_custom_'           => __( 'Custom action key…', 'alamin-vendor-tasks-dokan-clickup' ),
				),
				'i18n'               => array(
					'saving'              => __( 'Saving…', 'alamin-vendor-tasks-dokan-clickup' ),
					'saved'               => __( 'Settings saved.', 'alamin-vendor-tasks-dokan-clickup' ),
					'saveFailed'          => __( 'Save failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'exportFailed'        => __( 'Export failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'exported'            => __( 'Exported.', 'alamin-vendor-tasks-dokan-clickup' ),
					'exportRequestFailed' => __( 'Export request failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'invalidJson'         => __( 'Invalid JSON file.', 'alamin-vendor-tasks-dokan-clickup' ),
					'imported'            => __( 'Imported.', 'alamin-vendor-tasks-dokan-clickup' ),
					'importFailed'        => __( 'Import failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'importRequestFailed' => __( 'Import request failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'backfillConfirm'     => __( 'This will queue all vendors without a ClickUp task for creation via WP-Cron. Continue?', 'alamin-vendor-tasks-dokan-clickup' ),
					'queuing'             => __( 'Queuing…', 'alamin-vendor-tasks-dokan-clickup' ),
					'done'                => __( 'Done.', 'alamin-vendor-tasks-dokan-clickup' ),
					'failed'              => __( 'Failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'requestFailed'       => __( 'Request failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'connectionSuccess'   => __( 'Connected successfully.', 'alamin-vendor-tasks-dokan-clickup' ),
					'connectionFailed'    => __( 'Connection failed.', 'alamin-vendor-tasks-dokan-clickup' ),
					'testing'             => __( 'Testing…', 'alamin-vendor-tasks-dokan-clickup' ),
				),
			)
		);

		// Enable translations
		wp_set_script_translations( 'vendor-tasks-dokan-clickup-admin', 'alamin-vendor-tasks-dokan-clickup' );
	}

	/**
	 * Dequeue all styles and scripts enqueued by third-party plugins and themes
	 * on our settings page to prevent asset conflicts and reduce page weight.
	 *
	 * Runs at PHP_INT_MAX so every plugin has already enqueued by this point.
	 * Keeps handles that were registered by WordPress core (captured via
	 * snapshot_core_handles() at init:5, before any plugin registers) plus
	 * our own plugin assets. Third-party plugin/theme assets are removed.
	 *
	 * Other code can preserve additional handles via the filter:
	 *   add_filter( 'vendor_tasks_dokan_clickup_allowed_asset_handles', fn($h) => [...$h, 'my-handle'] );
	 *
	 * @since 1.2.0
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function dequeue_third_party_assets( string $hook ): void {
		if ( 'toplevel_page_vendor-tasks-dokan-clickup' !== $hook ) {
			return;
		}

		global $wp_styles, $wp_scripts;

		/** Our own handles — always kept. */
		$our_handles = array(
			'vendor-tasks-dokan-clickup-admin',
			'vendor-tasks-dokan-clickup-freemius-connect',
		);

		/**
		 * Filter: allow external code to protect additional handles from removal.
		 *
		 * @param string[] $handles Handle names to keep.
		 */
		$extra_kept = (array) apply_filters( 'vendor_tasks_dokan_clickup_allowed_asset_handles', array() );

		// Core handles snapshot + our own + any externally allowlisted handles.
		$keep = array_merge( $this->core_style_handles, $our_handles, $extra_kept );

		// ── Styles ────────────────────────────────────────────────────────
		foreach ( array_values( $wp_styles->queue ) as $handle ) {
			if ( in_array( $handle, $keep, true ) ) {
				continue;
			}
			wp_dequeue_style( $handle );
		}

		$keep_scripts = array_merge( $this->core_script_handles, $our_handles, $extra_kept );

		// ── Scripts ───────────────────────────────────────────────────────
		foreach ( array_values( $wp_scripts->queue ) as $handle ) {
			if ( in_array( $handle, $keep_scripts, true ) ) {
				continue;
			}
			wp_dequeue_script( $handle );
		}
	}
}
