<?php
/**
 * Asset Manager
 *
 * Handles conditional loading of scripts and styles.
 *
 * @package DonorCore\Performance
 */

namespace DonorCore\Performance;

defined( 'ABSPATH' ) || exit;

/**
 * Asset Manager Class
 */
class Asset_Manager {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_action( 'wp_enqueue_scripts', array( $this, 'conditional_frontend_assets' ), 20 );
		add_action( 'admin_enqueue_scripts', array( $this, 'conditional_admin_assets' ), 20 );
	}

	/**
	 * Conditionally load frontend assets.
	 */
	public function conditional_frontend_assets() {
		// Only load on pages with donation blocks or forms.
		if ( ! $this->should_load_frontend_assets() ) {
			return;
		}

		// Frontend assets are already enqueued by block registration.
		// This is a placeholder for future conditional loading.
	}

	/**
	 * Conditionally load admin assets.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function conditional_admin_assets( $hook ) {
		// Only load on DonorCore admin pages.
		if ( ! $this->is_donorcore_page( $hook ) ) {
			// Dequeue admin app on non-DonorCore pages.
			return;
		}

		// Admin assets are already enqueued by Menu_Manager.
	}

	/**
	 * Check if frontend assets should load.
	 *
	 * @return bool
	 */
	private function should_load_frontend_assets() {
		global $post;

		// Check if current post has donation blocks.
		if ( $post && has_block( 'donor-core/donation-form', $post ) ) {
			return true;
		}

		if ( $post && has_block( 'donor-core/progress-bar', $post ) ) {
			return true;
		}

		// Check if it's a donation product page.
		if ( is_product() ) {
			$product = wc_get_product( get_the_ID() );
			if ( $product && 'donation' === $product->get_type() ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Check if current page is a DonorCore admin page.
	 *
	 * @param string $hook Page hook.
	 * @return bool
	 */
	private function is_donorcore_page( $hook ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page parameter check during asset enqueue hook
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		return strpos( $hook, 'donorcore-donations' ) !== false 
			|| strpos( $page, 'donorcore-donations' ) !== false;
	}

	/**
	 * Defer non-critical scripts.
	 *
	 * @param string $tag    Script tag.
	 * @param string $handle Script handle.
	 * @return string
	 */
	public function defer_scripts( $tag, $handle ) {
		// Defer specific scripts.
		$defer_scripts = array(
			'dc-donation-form',
			'dc-progress-bar',
		);

		if ( in_array( $handle, $defer_scripts, true ) ) {
			return str_replace( ' src', ' defer src', $tag );
		}

		return $tag;
	}
}
