<?php
if (!defined('ABSPATH')) exit;
class Botami_Url_Checker {
    public static function is_url_excluded() {
        global $wp;
        $excluded_urls = get_option('botami_excluded_urls', '');
        $excluded_urls_array = array_filter(explode("||", $excluded_urls));
        $current_url = wp_parse_url(home_url(add_query_arg([], $wp->request)), PHP_URL_PATH);
        $current_url = $current_url === null ? '' : trim($current_url, '/');
        
        // Check if current URL matches any exclusion pattern
        foreach ($excluded_urls_array as $pattern) {
            if (self::matches_excluded_pattern($current_url, $pattern)) {
                return true;
            }
        }
        
        return false;
    }

    private static function matches_excluded_pattern($url_to_check, $pattern) {
        // Normalize URLs by trimming slashes and converting to lowercase
        $url_to_check = strtolower(trim($url_to_check, '/'));
        $pattern = strtolower(trim($pattern, '/'));
        
        // If pattern is empty after trimming, don't exclude
        if (empty($pattern)) {
            return false;
        }
        
        $current_host = wp_parse_url(home_url(), PHP_URL_HOST);

        // Handle full URL patterns
        if (strpos($pattern, '/') !== false && (strpos($pattern, 'http') === 0 || strpos($pattern, '.') !== false)) {
            $parsed_pattern = wp_parse_url((strpos($pattern, 'http') === 0) ? $pattern : 'https://' . $pattern);
            $pattern_path = isset($parsed_pattern['path']) ? trim($parsed_pattern['path'], '/') : '';
            $pattern_host = isset($parsed_pattern['host']) ? $parsed_pattern['host'] : '';
    
            // Compare host and path
            return ($pattern_host === $current_host || empty($pattern_host)) && $url_to_check === $pattern_path;
        }
        
        // Handle path-only patterns
        $url_parts = explode('/', $url_to_check);
        $pattern_parts = explode('/', $pattern);
        
        // If pattern is longer than URL, no match
        if (count($pattern_parts) > count($url_parts)) {
            return false;
        }
        
        // Check if URL starts with the pattern
        for ($i = 0; $i < count($pattern_parts); $i++) {
            if ($pattern_parts[$i] !== $url_parts[$i]) {
                return false;
            }
        }
        
        return true;
    }
}