<?php

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

if (!class_exists('AIEO_Asset_Min')) {

    class AIEO_Asset_Min {

        
        public static function register() {
            if (defined('AIEO_ASSET_MIN_ACTIVE')) {
                return; 
            }
            define('AIEO_ASSET_MIN_ACTIVE', true);

            
            if (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) {
                return;
            }
            add_filter('style_loader_src',  array(__CLASS__, 'rewrite'), 20);
            add_filter('script_loader_src', array(__CLASS__, 'rewrite'), 20);
        }

        
        public static function rewrite($src) {
            if (!is_string($src) || $src === '') {
                return $src;
            }
            
            if (strpos($src, '/ai-eshop-optimizer/') === false
                && strpos($src, '/ai-eshop-optimizer-runtime/') === false) {
                return $src;
            }
            
            if (preg_match('#\.min\.(?:css|js)(?:[?\#]|$)#', $src)) {
                return $src;
            }
            
            if (!preg_match('#\.(css|js)(?:([?\#]).*)?$#', $src)) {
                return $src;
            }

            $min = preg_replace('#\.(css|js)(?=[?\#]|$)#', '.min.$1', $src, 1);

            
            $path_part = (string) wp_parse_url($min, PHP_URL_PATH);
            $marker = '/plugins/';
            $pos = strpos($path_part, $marker);
            if ($pos === false) {
                return $src;
            }
            $abs = WP_PLUGIN_DIR . substr($path_part, $pos + strlen('/plugins'));

            return file_exists($abs) ? $min : $src;
        }
    }
}
