<?php
/**
 * Asset enqueueing with honest cache-busting: the plugin version in production,
 * the file's mtime under SCRIPT_DEBUG — so "why is my CSS stale" (the classic
 * ?ver= trap) can't happen during development, and shipped sites still get
 * long-lived caches keyed to releases.
 *
 * @package Hakki\WooCore
 */

namespace ErenLabs\SmartCategories\Vendor\Hakki\WooCore\Support;

use ErenLabs\SmartCategories\Vendor\Hakki\WooCore\Core;

defined( 'ABSPATH' ) || exit;

final class Assets {

	/** @var Core */
	private $core;

	public function __construct( Core $core ) {
		$this->core = $core;
	}

	/** Slug-scoped handle, e.g. "quoteguard-for-woocommerce-admin". */
	public function handle( string $name ): string {
		return $this->core->slug() . '-' . $name;
	}

	/**
	 * Version string for a relative asset path. Falls back to the plugin
	 * version when the file is unreadable (never returns an empty ver).
	 */
	public function version( string $rel_path ): string {
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
			$abs   = plugin_dir_path( $this->core->file() ) . ltrim( $rel_path, '/' );
			$mtime = is_readable( $abs ) ? (string) filemtime( $abs ) : '';
			if ( '' !== $mtime ) {
				return $this->core->version() . '.' . $mtime;
			}
		}
		return $this->core->version();
	}

	public function url( string $rel_path ): string {
		return plugin_dir_url( $this->core->file() ) . ltrim( $rel_path, '/' );
	}

	/**
	 * @param string   $name     Handle suffix (e.g. 'admin').
	 * @param string   $rel_path Path relative to the plugin root.
	 * @param string[] $deps
	 */
	public function style( string $name, string $rel_path, array $deps = array() ): string {
		$handle = $this->handle( $name );
		wp_enqueue_style( $handle, $this->url( $rel_path ), $deps, $this->version( $rel_path ) );
		return $handle;
	}

	/**
	 * @param string   $name      Handle suffix.
	 * @param string   $rel_path  Path relative to the plugin root.
	 * @param string[] $deps
	 * @param bool     $in_footer
	 */
	public function script( string $name, string $rel_path, array $deps = array(), bool $in_footer = true ): string {
		$handle = $this->handle( $name );
		wp_enqueue_script( $handle, $this->url( $rel_path ), $deps, $this->version( $rel_path ), $in_footer );
		return $handle;
	}
}
