<?php
/**
 * CDN Domain Mapper
 * Prevents WordPress redirects when accessing via alternative domains
 * Allows admin URL and CDN URLs to work without redirecting to main site
 */

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

class USCDN_Domain_Mapper {
    
    private static $instance = null;
    private $current_host = '';
    private $is_admin_domain = false;
    private $is_cdn_domain = false;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->current_host = $_SERVER['HTTP_HOST'] ?? '';
        $this->detect_domain_type();
        $this->init_hooks();
    }
    
    /**
     * Detect which type of domain is being accessed
     */
    private function detect_domain_type() {
        if (empty($this->current_host)) {
            return;
        }
        
        // Check if accessing via admin URL
        if (USCDN_Settings::get('enable_admin_url') && USCDN_Settings::get('admin_url')) {
            $admin_url = USCDN_Settings::get('admin_url');
            $admin_host = parse_url($admin_url, PHP_URL_HOST);
            
            if ($admin_host && strcasecmp($this->current_host, $admin_host) === 0) {
                $this->is_admin_domain = true;
                return;
            }
        }
        
        // Check if accessing via CDN URLs
        $cdn_hosts = [];
        
        if (USCDN_Settings::get('enable_image_cdn') && USCDN_Settings::get('cdn_image_base')) {
            $cdn_hosts[] = parse_url(USCDN_Settings::get('cdn_image_base'), PHP_URL_HOST);
        }
        
        if (USCDN_Settings::get('enable_static_cdn') && USCDN_Settings::get('cdn_static_base')) {
            $cdn_hosts[] = parse_url(USCDN_Settings::get('cdn_static_base'), PHP_URL_HOST);
        }
        
        if (USCDN_Settings::get('enable_origin_url') && USCDN_Settings::get('origin_url')) {
            $cdn_hosts[] = parse_url(USCDN_Settings::get('origin_url'), PHP_URL_HOST);
        }
        
        foreach ($cdn_hosts as $cdn_host) {
            if ($cdn_host && strcasecmp($this->current_host, $cdn_host) === 0) {
                $this->is_cdn_domain = true;
                return;
            }
        }
    }
    
    /**
     * Initialize hooks to prevent redirects
     */
    private function init_hooks() {
        if (!$this->is_admin_domain && !$this->is_cdn_domain) {
            return;
        }
        
        // Prevent WordPress from redirecting to canonical URL
        remove_action('template_redirect', 'redirect_canonical');
        
        // Override home_url and site_url to current domain
        add_filter('home_url', [$this, 'fix_home_url'], 1, 4);
        add_filter('site_url', [$this, 'fix_site_url'], 1, 4);
        add_filter('admin_url', [$this, 'fix_admin_url'], 1, 3);
        add_filter('network_admin_url', [$this, 'fix_admin_url'], 1, 3);
        
        // Prevent wp_safe_redirect from changing domain
        add_filter('wp_redirect', [$this, 'prevent_redirect'], 1, 2);
        
        // Fix wp-login.php redirects
        add_filter('login_url', [$this, 'fix_login_url'], 1, 3);
        add_filter('logout_url', [$this, 'fix_logout_url'], 1, 2);
        
        // Prevent WordPress from checking if we're on the right domain
        add_filter('option_home', [$this, 'fix_option_home'], 1);
        add_filter('option_siteurl', [$this, 'fix_option_siteurl'], 1);
    }
    
    /**
     * Fix home_url to use current domain
     */
    public function fix_home_url($url, $path, $scheme, $blog_id) {
        if ($this->is_admin_domain || $this->is_cdn_domain) {
            $parsed = parse_url($url);
            $scheme = $parsed['scheme'] ?? (is_ssl() ? 'https' : 'http');
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return $scheme . '://' . $this->current_host . $path . $query;
        }
        return $url;
    }
    
    /**
     * Fix site_url to use current domain
     */
    public function fix_site_url($url, $path, $scheme, $blog_id) {
        if ($this->is_admin_domain || $this->is_cdn_domain) {
            $parsed = parse_url($url);
            $scheme = $parsed['scheme'] ?? (is_ssl() ? 'https' : 'http');
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return $scheme . '://' . $this->current_host . $path . $query;
        }
        return $url;
    }
    
    /**
     * Fix admin_url to use admin domain if configured
     */
    public function fix_admin_url($url, $path, $blog_id = null) {
        if ($this->is_admin_domain) {
            $parsed = parse_url($url);
            $scheme = $parsed['scheme'] ?? (is_ssl() ? 'https' : 'http');
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return $scheme . '://' . $this->current_host . $path . $query;
        }
        
        // If admin URL is enabled and we're not on admin domain, use the configured admin URL
        if (USCDN_Settings::get('enable_admin_url') && USCDN_Settings::get('admin_url')) {
            $admin_url = USCDN_Settings::get('admin_url');
            $parsed = parse_url($url);
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return rtrim($admin_url, '/') . $path . $query;
        }
        
        return $url;
    }
    
    /**
     * Fix login URL
     */
    public function fix_login_url($login_url, $redirect, $force_reauth) {
        if ($this->is_admin_domain) {
            $parsed = parse_url($login_url);
            $scheme = is_ssl() ? 'https' : 'http';
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return $scheme . '://' . $this->current_host . $path . $query;
        }
        return $login_url;
    }
    
    /**
     * Fix logout URL
     */
    public function fix_logout_url($logout_url, $redirect) {
        if ($this->is_admin_domain) {
            $parsed = parse_url($logout_url);
            $scheme = is_ssl() ? 'https' : 'http';
            $path = $parsed['path'] ?? '';
            $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
            
            return $scheme . '://' . $this->current_host . $path . $query;
        }
        return $logout_url;
    }
    
    /**
     * Prevent redirects that change domain
     */
    public function prevent_redirect($location, $status) {
        if ($this->is_admin_domain || $this->is_cdn_domain) {
            $location_host = parse_url($location, PHP_URL_HOST);
            
            // If redirect is trying to change domain, rewrite it to current domain
            if ($location_host && strcasecmp($location_host, $this->current_host) !== 0) {
                $parsed = parse_url($location);
                $scheme = is_ssl() ? 'https' : 'http';
                $path = $parsed['path'] ?? '/';
                $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
                $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
                
                $location = $scheme . '://' . $this->current_host . $path . $query . $fragment;
            }
        }
        return $location;
    }
    
    /**
     * Fix option_home to prevent WordPress from detecting domain mismatch
     */
    public function fix_option_home($value) {
        if ($this->is_admin_domain || $this->is_cdn_domain) {
            $scheme = is_ssl() ? 'https' : 'http';
            return $scheme . '://' . $this->current_host;
        }
        return $value;
    }
    
    /**
     * Fix option_siteurl to prevent WordPress from detecting domain mismatch
     */
    public function fix_option_siteurl($value) {
        if ($this->is_admin_domain || $this->is_cdn_domain) {
            $scheme = is_ssl() ? 'https' : 'http';
            return $scheme . '://' . $this->current_host;
        }
        return $value;
    }
    
    /**
     * Get current domain info
     */
    public static function get_domain_info() {
        $instance = self::get_instance();
        return [
            'current_host' => $instance->current_host,
            'is_admin_domain' => $instance->is_admin_domain,
            'is_cdn_domain' => $instance->is_cdn_domain,
            'main_site_url' => get_option('home'),
            'admin_url_configured' => USCDN_Settings::get('admin_url', '')
        ];
    }
}
