<?php
/**
 * AYSA Global Exclusions Manager
 * 
 * Centralized management of URL patterns and content that should be excluded
 * from AYSA processing (internal linking, link purchases, SEO automation, etc.)
 * 
 * @package Aysa
 * @since 1.0.0
 */

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

class Aysa_Global_Exclusions {
    
    /**
     * Get default excluded URL patterns for all AYSA functionality
     * 
     * @return array Array of URL patterns to exclude
     */
    public static function get_default_excluded_url_patterns() {
        return array(
            // WooCommerce system pages
            '/cart/',
            '/checkout/',
            '/my-account/',
            '/wishlist/',
            
            // WordPress internal archives
            '/tag/',
            '/author/',
            '/date/',
            '/\d{4}/\d{2}/', // date archives like /2025/04/ (regex)
            
            // Search parameters and internal queries
            '/?s=',
            '/search/',
            '/?add-to-cart=',
            '/?wc-ajax=',
            '/?orderby=',
            '/?filter_',
            '/?variation_id=',
            '/?attribute_',
            
            // Feeds and technical pages
            '/feed/',
            '/comments/feed/',
            '/rss/',
            '/atom/',
            '/sitemap',
            '/robots.txt',
            
            // WordPress admin and system
            '/wp-admin/',
            '/wp-content/',
            '/wp-includes/',
            '/wp-json/',
            '/wp-login.php',
            '/wp-cron.php',
            
            // Common technical patterns
            '.xml',
            '.json',
            '.css',
            '.js',
            '.ico',
            '.png',
            '.jpg',
            '.jpeg',
            '.gif',
            '.svg',
            '.woff',
            '.woff2',
            '.ttf',
            '.eot',
            '.pdf',
            '.zip',
            '.rar',
            
            // Development and staging
            '/test/',
            '/dev/',
            '/staging/',
            '/debug/',
            
            // Security and system
            '/.well-known/',
            '/security.txt',
            '/ads.txt',
        );
    }
    
    /**
     * Get custom excluded URL patterns from settings
     * 
     * @return array Array of custom URL patterns
     */
    public static function get_custom_excluded_url_patterns() {
        $custom_patterns = get_option('aysa_global_excluded_url_patterns', '');
        if (empty($custom_patterns)) {
            return array();
        }
        
        return array_filter(array_map('trim', explode("\n", $custom_patterns)));
    }
    
    /**
     * Get all excluded URL patterns (default + custom)
     * 
     * @return array Combined array of all excluded URL patterns
     */
    public static function get_all_excluded_url_patterns() {
        $default_patterns = self::get_default_excluded_url_patterns();
        $custom_patterns = self::get_custom_excluded_url_patterns();
        
        return array_merge($default_patterns, $custom_patterns);
    }
    
    /**
     * Check if URL matches any excluded patterns
     * 
     * @param string $url URL to check
     * @return bool True if URL should be excluded, false otherwise
     */
    public static function is_url_excluded($url) {
        aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] Checking exclusion for URL: $url");
        
        // First check if it's a WooCommerce system page by ID
        if (self::is_woocommerce_system_page($url)) {
            aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] URL '$url' excluded as WooCommerce system page");
            return true;
        }
        
        $excluded_patterns = self::get_all_excluded_url_patterns();
        
        if (empty($excluded_patterns)) {
            return false;
        }
        
        // Parse URL to get path and query
        $parsed_url = wp_parse_url($url);
        $path = $parsed_url['path'] ?? '';
        $query = $parsed_url['query'] ?? '';
        $full_url = $path . ($query ? '?' . $query : '');
        
        foreach ($excluded_patterns as $pattern) {
            $pattern = trim($pattern);
            if (empty($pattern)) continue;
            
            // Handle regex patterns (those starting with / and containing regex chars)
            if (strpos($pattern, '/') === 0 && preg_match('/[.*+?^${}()|[\]\\\\]/', $pattern)) {
                try {
                    if (preg_match('#' . $pattern . '#i', $full_url)) {
                        aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] URL '$url' excluded by regex pattern: $pattern");
                        return true;
                    }
                } catch (Exception $e) {
                    aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] Invalid regex pattern: $pattern");
                    continue;
                }
            } else {
                // Handle simple string patterns
                if (strpos($full_url, $pattern) !== false) {
                    aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] URL '$url' excluded by pattern: $pattern");
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * Check if URL is a WooCommerce system page by comparing with actual page IDs
     * 
     * @param string $url URL to check
     * @return bool True if it's a WooCommerce system page
     */
    public static function is_woocommerce_system_page($url) {
        if (!function_exists('wc_get_page_id')) {
            return false;
        }
        
        // Get WooCommerce page IDs
        $wc_pages = array(
            'shop' => wc_get_page_id('shop'),
            'cart' => wc_get_page_id('cart'),
            'checkout' => wc_get_page_id('checkout'),
            'myaccount' => wc_get_page_id('myaccount'),
        );
        
        // Check if URL matches any WooCommerce system page
        foreach ($wc_pages as $page_type => $page_id) {
            if ($page_id > 0) {
                $page_url = get_permalink($page_id);
                if ($page_url && self::urls_match($url, $page_url)) {
                    aysa_debug_log("[AYSA GLOBAL EXCLUSIONS] URL '$url' matches WooCommerce $page_type page: $page_url");
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * Compare two URLs to see if they match (ignoring trailing slashes, query params, etc.)
     * 
     * @param string $url1 First URL
     * @param string $url2 Second URL  
     * @return bool True if URLs match
     */
    private static function urls_match($url1, $url2) {
        $clean_url1 = rtrim(strtok($url1, '?'), '/');
        $clean_url2 = rtrim(strtok($url2, '?'), '/');
        return $clean_url1 === $clean_url2;
    }
    
    /**
     * Get excluded post types for AYSA processing
     * 
     * @return array Array of post types to exclude
     */
    public static function get_excluded_post_types() {
        return array(
            'revision',
            'nav_menu_item',
            'custom_css',
            'customize_changeset',
            'oembed_cache',
            'user_request',
            'wp_block',
            'wp_template',
            'wp_template_part',
            'wp_navigation',
            'wp_global_styles',
        );
    }
    
    /**
     * Check if post type should be excluded from AYSA processing
     * 
     * @param string $post_type Post type to check
     * @return bool True if post type should be excluded
     */
    public static function is_post_type_excluded($post_type) {
        return in_array($post_type, self::get_excluded_post_types());
    }
    
    /**
     * Get excluded taxonomies for AYSA processing
     * 
     * @return array Array of taxonomies to exclude
     */
    public static function get_excluded_taxonomies() {
        return array(
            'nav_menu',
            'link_category',
            'post_format',
            'wp_theme',
            'wp_template_part_area',
        );
    }
    
    /**
     * Check if taxonomy should be excluded from AYSA processing
     * 
     * @param string $taxonomy Taxonomy to check
     * @return bool True if taxonomy should be excluded
     */
    public static function is_taxonomy_excluded($taxonomy) {
        return in_array($taxonomy, self::get_excluded_taxonomies());
    }
    
    /**
     * Save custom excluded URL patterns
     * 
     * @param string $patterns Newline-separated list of patterns
     * @return bool True on success, false on failure
     */
    public static function save_custom_excluded_url_patterns($patterns) {
        return update_option('aysa_global_excluded_url_patterns', sanitize_textarea_field($patterns));
    }
    
    /**
     * Initialize default exclusions if not already set
     */
    public static function initialize_defaults() {
        // Set default 404 exclusion patterns if not already configured
        $existing_404_patterns = get_option('aysa_404_exclude_patterns', '');
        if (empty($existing_404_patterns)) {
            $default_patterns = self::get_default_excluded_url_patterns();
            $patterns_text = implode("\n", $default_patterns);
            update_option('aysa_404_exclude_patterns', $patterns_text);
        }
    }
}

// Initialize on plugin load
add_action('init', array('Aysa_Global_Exclusions', 'initialize_defaults'));
?>
