<?php
/**
 * Asset manager for enqueuing plugin styles and scripts.
 *
 * @package MonitorCat\Admin
 */

declare(strict_types=1);

namespace MonitorCat\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Handles enqueuing of CSS and JavaScript assets with cache-busting.
 */
final class AssetManager {

	/**
	 * Enqueue a stylesheet relative to the plugin root.
	 *
	 * @param string   $handle        Unique handle for the stylesheet.
	 * @param string   $relative_path Path relative to plugin root directory.
	 * @param string[] $deps          Array of dependency handles.
	 */
	public function enqueue_style( string $handle, string $relative_path, array $deps = array() ): void {
		$file_path = MONITORCAT_DIR . $relative_path;

		if ( ! file_exists( $file_path ) ) {
			return;
		}

		wp_enqueue_style(
			$handle,
			MONITORCAT_URL . $relative_path,
			$deps,
			$this->file_version( $file_path )
		);
	}

	/**
	 * Enqueue a script relative to the plugin root.
	 *
	 * @param string   $handle        Unique handle for the script.
	 * @param string   $relative_path Path relative to plugin root directory.
	 * @param string[] $deps          Array of dependency handles.
	 * @param bool     $in_footer     Whether to load in the footer.
	 */
	public function enqueue_script( string $handle, string $relative_path, array $deps = array(), bool $in_footer = true ): void {
		$file_path = MONITORCAT_DIR . $relative_path;

		if ( ! file_exists( $file_path ) ) {
			return;
		}

		wp_enqueue_script(
			$handle,
			MONITORCAT_URL . $relative_path,
			$deps,
			$this->file_version( $file_path ),
			$in_footer
		);
	}

	/**
	 * Get a file's modification time as a version string for cache busting.
	 *
	 * @param string $file_path Absolute path to the file.
	 * @return string File modification time as a string, or plugin version as fallback.
	 */
	public function file_version( string $file_path ): string {
		if ( file_exists( $file_path ) ) {
			return (string) filemtime( $file_path );
		}

		return MONITORCAT_VERSION;
	}
}
