<?php
/**
 * Assets Optimizer Helper.
 *
 * @package automation-web-platform
 */

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

/**
 * WAWP_Assets_Optimizer Class
 * Handles optimization of frontend assets (async, defer, etc.)
 */
class WAWP_Assets_Optimizer {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_filter( 'style_loader_tag', array( $this, 'add_async_load_attribute' ), 10, 2 );
		add_filter( 'script_loader_tag', array( $this, 'add_defer_attribute' ), 10, 2 );
		add_filter( 'pre_count_users', array( $this, 'optimize_user_count' ), 10, 1 );
	}

	/**
	 * Add async loading to specific styles.
	 *
	 * @param string $html   The link tag.
	 * @param string $handle The style handle.
	 * @return string
	 */
	public function add_async_load_attribute( $html, $handle ) {
		$async_styles = array( 'remix-icon', 'floating-whatsapp-button-style', 'wawp-otp-frontend-styles', 'wawp-intl-tel-input-css' );
		if ( in_array( $handle, $async_styles, true ) ) {
			// Handle both single and double quotes.
			$html = str_replace( "rel='stylesheet'", "rel='preload' as='style' onload=\"this.onload=null;this.rel='stylesheet'\"", $html );
			$html = str_replace( 'rel="stylesheet"', 'rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"', $html );
		}
		return $html;
	}

	/**
	 * Add defer attribute to specific scripts.
	 *
	 * @param string $tag    The script tag.
	 * @param string $handle The script handle.
	 * @return string
	 */
	public function add_defer_attribute( $tag, $handle ) {
		$defer_scripts = array( 'floating-whatsapp-button-script', 'qrcodejs', 'wawp-country-code-script', 'wawp-intl-tel-input-js', 'wawp-intl-tel-input-utils-js' );
		if ( in_array( $handle, $defer_scripts, true ) ) {
			if ( strpos( $tag, 'defer' ) === false ) {
				return str_replace( ' src', ' defer src', $tag );
			}
		}
		return $tag;
	}

	/**
	 * Optimize Dashboard Performance by overriding user count on specific screens.
	 *
	 * @param array|null $override Count override.
	 * @return array|null
	 */
	public function optimize_user_count( $override ) {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return $override;
		}

		$screen = get_current_screen();
		if ( ! $screen || 'toplevel_page_wawp' !== $screen->id ) {
			return $override;
		}

		$stats = class_exists( 'WAWP_Dashboard' ) ? WAWP_Dashboard::get_snapshot_stats() : array();
		return array(
			'total_users' => $stats['totalWpUsers'] ?? 0,
			'avail_roles' => array(),
		);
	}
}
