<?php
/**
 * Critical CSS Manager Service
 *
 * Manages critical CSS generation, caching, and retrieval for WooCommerce pages.
 * Provides page-type specific critical CSS with fallback to generic styles.
 *
 * @package Mamba\Modules\CriticalCss\Services
 * @since   1.1.0
 */

namespace Mamba\Modules\CriticalCss\Services;

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

/**
 * Class CriticalCssManager
 *
 * Core service for critical CSS management.
 * Handles page type detection, CSS loading, caching, and custom CSS overrides.
 *
 * @since 1.1.0
 */
final class CriticalCssManager {
    
    private const CACHE_GROUP = 'mamba_critical_css';
    private const CACHE_TTL = DAY_IN_SECONDS;
    
    /**
     * Page types supported by critical CSS
     */
    private const PAGE_TYPES = [
        'product',
        'shop',
        'category',
        'cart',
        'checkout',
        'account',
        'generic'
    ];
    
    /**
     * Get critical CSS for the current page
     */
    public function getCriticalCss(): string {
        $pageType = $this->detectPageType();
        $cacheKey = $this->getCacheKey($pageType);
        
        // Try to get from cache first
        $cached = get_transient($cacheKey);
        if ($cached !== false) {
            return $cached;
        }
        
        // Build critical CSS
        $criticalCss = $this->buildCriticalCss($pageType);
        
        // Cache the result
        if (!empty($criticalCss)) {
            set_transient($cacheKey, $criticalCss, self::CACHE_TTL);
        }
        
        return $criticalCss;
    }
    
    /**
     * Detect the current page type
     */
    public function detectPageType(): string {
        // WooCommerce-specific page types
        if (function_exists('is_product') && is_product()) {
            return 'product';
        }
        
        if (function_exists('is_shop') && is_shop()) {
            return 'shop';
        }
        
        if (function_exists('is_product_category') && is_product_category()) {
            return 'category';
        }
        
        if (function_exists('is_product_tag') && is_product_tag()) {
            return 'category'; // Use category CSS for tags too
        }
        
        if (function_exists('is_cart') && is_cart()) {
            return 'cart';
        }
        
        if (function_exists('is_checkout') && is_checkout()) {
            return 'checkout';
        }
        
        if (function_exists('is_account_page') && is_account_page()) {
            return 'account';
        }
        
        // WordPress page types
        if (is_front_page() || is_home()) {
            return 'shop'; // Often the shop page is the homepage
        }
        
        return 'generic';
    }
    
    /**
     * Build critical CSS for a page type
     * 
     * Free: Basic CSS reset only (minimal)
     * Premium: Full WooCommerce-optimized CSS + custom CSS + theme-specific
     */
    private function buildCriticalCss(string $pageType): string {
        $css = '';
        
        // 1. Always include base critical CSS (minimal reset - FREE)
        $css .= $this->getBaseCriticalCss();
        
        // 2. Add page-type specific WooCommerce CSS (PREMIUM ONLY)
        if ($this->isPremium()) {
            $css .= $this->getPageTypeCss($pageType);
            
            // 3. Add custom CSS if configured (PREMIUM)
            $customCss = $this->getCustomCss($pageType);
            if (!empty($customCss)) {
                $css .= "\n/* Custom Critical CSS */\n" . $customCss;
            }
        }
        
        // 4. Minify the result
        $css = $this->minifyCss($css);
        
        return $css;
    }
    
    /**
     * Get base critical CSS (common to all pages)
     */
    private function getBaseCriticalCss(): string {
        return $this->loadCssFile('base');
    }
    
    /**
     * Get page-type specific CSS
     */
    private function getPageTypeCss(string $pageType): string {
        // First try theme-specific CSS (Premium)
        if ($this->isPremium()) {
            $themeCss = $this->getThemeSpecificCss($pageType);
            if (!empty($themeCss)) {
                return $themeCss;
            }
        }
        
        // Fall back to default WooCommerce CSS
        return $this->loadCssFile($pageType);
    }
    
    /**
     * Get theme-specific critical CSS (Premium)
     */
    private function getThemeSpecificCss(string $pageType): string {
        $theme = get_template();
        $themeCssPath = $this->getDataPath() . '/themes/' . sanitize_file_name($theme) . '/' . $pageType . '.css';
        
        if (file_exists($themeCssPath)) {
            return file_get_contents($themeCssPath);
        }
        
        return '';
    }
    
    /**
     * Get custom CSS for a page type (Premium)
     */
    private function getCustomCss(string $pageType): string {
        $customCss = get_option('mamba_critical_css_custom_' . $pageType, '');
        return is_string($customCss) ? $customCss : '';
    }
    
    /**
     * Load CSS from a data file
     */
    private function loadCssFile(string $name): string {
        $filePath = $this->getDataPath() . '/' . $name . '.css';
        
        if (file_exists($filePath)) {
            return file_get_contents($filePath);
        }
        
        // Fallback to inline defaults if file doesn't exist
        return $this->getInlineDefault($name);
    }
    
    /**
     * Get inline default CSS when file doesn't exist
     */
    private function getInlineDefault(string $name): string {
        $defaults = [
            'base' => '
*,*::before,*::after{box-sizing:border-box}
body{visibility:visible!important;opacity:1!important}
.screen-reader-text,.sr-only{clip:rect(1px,1px,1px,1px);position:absolute!important;height:1px;width:1px;overflow:hidden}
.hidden,[hidden]{display:none!important}
',
            'product' => '
.woocommerce div.product{position:relative}
.woocommerce div.product div.images img{max-width:100%;height:auto}
.woocommerce div.product .product_title{margin:0 0 .5em;font-size:2em;font-weight:700}
.woocommerce div.product p.price{font-size:1.5em;margin:1em 0}
.woocommerce div.product p.price ins{text-decoration:none}
.woocommerce div.product p.price del{opacity:.5}
.woocommerce div.product .woocommerce-product-rating{margin-bottom:1em}
.woocommerce div.product form.cart{margin-bottom:2em}
.woocommerce .woocommerce-breadcrumb{margin-bottom:1em;font-size:.9em}
.woocommerce a.button,.woocommerce button.button,.woocommerce input.button{display:inline-block;padding:.618em 1em;text-decoration:none;font-weight:700;border-radius:3px;cursor:pointer}
',
            'shop' => '
.woocommerce ul.products{list-style:none}
.woocommerce ul.products li.product{position:relative}
.woocommerce ul.products li.product a{text-decoration:none;color:inherit}
.woocommerce ul.products li.product a img,.woocommerce ul.products li.product img{max-width:100%;height:auto}
.woocommerce ul.products li.product .woocommerce-loop-product__title{font-size:1em;font-weight:600;margin-bottom:.25em}
.woocommerce ul.products li.product .price{font-size:.9em;margin-bottom:.5em}
.woocommerce ul.products li.product .button{display:inline-block;padding:.5em 1em;font-size:.9em}
.woocommerce .woocommerce-result-count,.woocommerce .woocommerce-ordering{margin-bottom:1em}
.woocommerce-products-header{margin-bottom:1.5em}
',
            'category' => '
.woocommerce ul.products{list-style:none}
.woocommerce ul.products li.product{position:relative}
.woocommerce ul.products li.product a{text-decoration:none;color:inherit}
.woocommerce ul.products li.product a img,.woocommerce ul.products li.product img{max-width:100%;height:auto}
.woocommerce ul.products li.product .woocommerce-loop-product__title{font-size:1em;font-weight:600;margin-bottom:.25em}
.woocommerce ul.products li.product .price{font-size:.9em;margin-bottom:.5em}
.woocommerce ul.products li.product .button{display:inline-block;padding:.5em 1em;font-size:.9em}
.woocommerce .woocommerce-result-count,.woocommerce .woocommerce-ordering{margin-bottom:1em}
.term-description{margin-bottom:1.5em}
.woocommerce-products-header{margin-bottom:1.5em}
',
            'cart' => '
.woocommerce-cart .woocommerce{max-width:1200px;margin:0 auto}
.woocommerce table.shop_table{width:100%;border-collapse:collapse}
.woocommerce table.shop_table th,.woocommerce table.shop_table td{padding:1em;text-align:left;border-bottom:1px solid #eee}
.woocommerce table.shop_table img{width:80px;height:auto}
.woocommerce .cart_totals{float:right;width:48%}
.woocommerce .cart_totals table{width:100%}
.woocommerce .wc-proceed-to-checkout{padding:1em 0}
.woocommerce .wc-proceed-to-checkout a.checkout-button{display:block;text-align:center;padding:1em;font-weight:700}
.woocommerce .quantity .qty{width:60px;text-align:center}
',
            'checkout' => '
.woocommerce-checkout .woocommerce{max-width:1200px;margin:0 auto}
.woocommerce form.checkout{display:flex;flex-wrap:wrap;gap:2em}
.woocommerce form.checkout .col2-set{flex:1;min-width:300px}
.woocommerce form.checkout #order_review_heading,.woocommerce form.checkout #order_review{flex:1;min-width:300px}
.woocommerce form .form-row{margin-bottom:1em}
.woocommerce form .form-row label{display:block;margin-bottom:.25em}
.woocommerce form .form-row input.input-text,.woocommerce form .form-row textarea,.woocommerce form .form-row select{width:100%;padding:.75em;border:1px solid #ddd;border-radius:3px}
.woocommerce #payment{background:#f7f7f7;padding:1.5em;border-radius:5px}
.woocommerce #payment ul.payment_methods{list-style:none;padding:0;margin:0 0 1em}
.woocommerce #payment .place-order{padding-top:1em}
.woocommerce #payment #place_order{width:100%;padding:1em;font-size:1.1em;font-weight:700}
',
            'account' => '
.woocommerce-account .woocommerce{max-width:1200px;margin:0 auto}
.woocommerce-account .woocommerce-MyAccount-navigation{float:left;width:25%}
.woocommerce-account .woocommerce-MyAccount-navigation ul{list-style:none;padding:0;margin:0}
.woocommerce-account .woocommerce-MyAccount-navigation ul li{margin-bottom:.5em}
.woocommerce-account .woocommerce-MyAccount-navigation ul li a{display:block;padding:.75em 1em;background:#f7f7f7;border-radius:3px}
.woocommerce-account .woocommerce-MyAccount-navigation ul li.is-active a{background:#333;color:#fff}
.woocommerce-account .woocommerce-MyAccount-content{float:right;width:72%}
.woocommerce form.login,.woocommerce form.register{max-width:400px}
',
            'generic' => '
.site-content{max-width:1200px;margin:0 auto;padding:0 1em}
.entry-header{margin-bottom:1.5em}
.entry-title{font-size:2em;font-weight:700;margin:0 0 .5em}
.entry-content{line-height:1.7}
.entry-content p{margin-bottom:1em}
.entry-content img{max-width:100%;height:auto}
'
        ];
        
        return $defaults[$name] ?? '';
    }
    
    /**
     * Minify CSS
     */
    private function minifyCss(string $css): string {
        // Remove comments
        $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
        
        // Remove whitespace
        $css = str_replace(["\r\n", "\r", "\n", "\t"], '', $css);
        
        // Remove multiple spaces
        $css = preg_replace('/\s+/', ' ', $css);
        
        // Remove spaces around special characters
        $css = preg_replace('/\s*([{}:;,>+~])\s*/', '$1', $css);
        
        // Remove trailing semicolons before closing braces
        $css = str_replace(';}', '}', $css);
        
        return trim($css);
    }
    
    /**
     * Get the data directory path
     */
    private function getDataPath(): string {
        return dirname(__DIR__) . '/Data';
    }
    
    /**
     * Get cache key for a page type
     */
    private function getCacheKey(string $pageType): string {
        $theme = get_template();
        return self::CACHE_GROUP . '_' . $pageType . '_' . $theme;
    }
    
    /**
     * Clear critical CSS cache
     */
    public function clearCache(?string $pageType = null): void {
        if ($pageType) {
            delete_transient($this->getCacheKey($pageType));
        } else {
            // Clear all page types
            foreach (self::PAGE_TYPES as $type) {
                delete_transient($this->getCacheKey($type));
            }
        }
    }
    
    /**
     * Get all supported page types
     */
    public function getPageTypes(): array {
        return self::PAGE_TYPES;
    }
    
    /**
     * Check if premium features are available
     */
    private function isPremium(): bool {
        return function_exists('mamba_fs') && mamba_fs()->can_use_premium_code__premium_only();
    }
    
    /**
     * Save custom CSS for a page type (Premium)
     */
    public function saveCustomCss(string $pageType, string $css): bool {
        if (!$this->isPremium()) {
            return false;
        }
        
        if (!in_array($pageType, self::PAGE_TYPES, true)) {
            return false;
        }
        
        // Sanitize CSS
        $css = wp_strip_all_tags($css);
        
        // Save to option
        $result = update_option('mamba_critical_css_custom_' . $pageType, $css);
        
        // Clear cache for this page type
        $this->clearCache($pageType);
        
        return $result;
    }
    
    /**
     * Get force-include selectors (Premium)
     */
    public function getForceIncludeSelectors(): array {
        if (!$this->isPremium()) {
            return [];
        }
        
        $selectors = get_option('mamba_critical_css_force_include', '');
        if (empty($selectors)) {
            return [];
        }
        
        return array_filter(array_map('trim', explode("\n", $selectors)));
    }
    
    /**
     * Save force-include selectors (Premium)
     */
    public function saveForceIncludeSelectors(array $selectors): bool {
        if (!$this->isPremium()) {
            return false;
        }
        
        $selectors = array_map('sanitize_text_field', $selectors);
        return update_option('mamba_critical_css_force_include', implode("\n", $selectors));
    }
}
