<?php
/**
 * CacheLoop – Asset Scanner
 *
 * Scans the frontend HTML for CSS and JS files to populate the Asset Manager.
 *
 * @package CacheLoop
 */

defined( 'ABSPATH' ) || exit;

class CACHELOOP_Asset_Scanner {

	private static $max_assets = 200;

	public function __construct() {
		// Run early so it catches everything before it's minified or delayed.
		// We use priority 5 to run before Minifier (20) and Delay JS (which we will set to run later).
		add_filter( 'cacheloop_process_html', array( $this, 'scan_html' ), 5 );
	}

	public function scan_html( $html ) {
		// Only run on frontend HTML
		if ( is_admin() || strpos( $html, '<html' ) === false ) {
			return $html;
		}

		$scanned_assets = get_option(
			'cacheloop_scanned_assets',
			array(
				'css' => array(),
				'js'  => array(),
			)
		);
		$updated        = false;

		// Ensure array structure
		if ( ! isset( $scanned_assets['css'] ) ) {
			$scanned_assets['css'] = array();
		}
		if ( ! isset( $scanned_assets['js'] ) ) {
			$scanned_assets['js'] = array();
		}

		// Limit to prevent huge db entries if something goes wrong
		if ( count( $scanned_assets['css'] ) + count( $scanned_assets['js'] ) > self::$max_assets ) {
			return $html;
		}

		// Match CSS
		if ( preg_match_all( '#<link[^>]+href=[\'"]([^\'"]+\.css[^\'"]*)[\'"][^>]*>#is', $html, $css_matches ) ) {
			foreach ( $css_matches[1] as $url ) {
				$clean_url = $this->clean_url( $url );
				if ( $clean_url && ! isset( $scanned_assets['css'][ md5( $clean_url ) ] ) ) {
					$scanned_assets['css'][ md5( $clean_url ) ] = $clean_url;
					$updated                                    = true;
				}
			}
		}

		// Match JS
		if ( preg_match_all( '#<script[^>]+src=[\'"]([^\'"]+\.js[^\'"]*)[\'"][^>]*>#is', $html, $js_matches ) ) {
			foreach ( $js_matches[1] as $url ) {
				$clean_url = $this->clean_url( $url );
				if ( $clean_url && ! isset( $scanned_assets['js'][ md5( $clean_url ) ] ) ) {
					$scanned_assets['js'][ md5( $clean_url ) ] = $clean_url;
					$updated                                   = true;
				}
			}
		}

		if ( $updated ) {
			update_option( 'cacheloop_scanned_assets', $scanned_assets, false );
		}

		return $html;
	}

	private function clean_url( $url ) {
		// Remove query strings
		$url = preg_replace( '/\?.*$/', '', $url );
		// Make protocol relative URL absolute so they are unique
		if ( strpos( $url, '//' ) === 0 ) {
			$url = 'https:' . ltrim( $url, '/' );
		} elseif ( strpos( $url, '/' ) === 0 ) {
			$url = home_url() . $url;
		}

		// Exclude our own minified files to prevent loops
		if ( strpos( $url, '/cache/cacheloop/' ) !== false ) {
			return false;
		}

		return esc_url_raw( $url );
	}

	/**
	 * Helper to trigger a background scan (e.g. on activation)
	 */
	public static function trigger_background_scan() {
		wp_remote_get(
			home_url(),
			array(
				'blocking'  => false,
				'timeout'   => 1,
				'sslverify' => false,
			)
		);
	}
}
