<?php
if (!defined('ABSPATH')) {
    exit;
}

class S3_URL_Rewriter {
    
    private $settings;
    private $s3_base_url;
    private $cdn_url;
    
    public function __construct($settings) {
        $this->settings = $settings;
        $this->setup_hooks();
        $this->generate_s3_base_url();
    }
    
    private function setup_hooks() {

        // Only rewrite URLs if enabled in settings
        if ($this->settings->get_option('rewrite_urls')) {
            // Rewrite attachment URLs
            add_filter('wp_get_attachment_url', array($this, 'rewrite_attachment_url'), 10, 2);
            
            // Rewrite image srcset URLs
            add_filter('wp_calculate_image_srcset', array($this, 'rewrite_srcset_urls'), 10, 5);
            
            // Rewrite content URLs
            add_filter('the_content', array($this, 'rewrite_content_urls'), 999);
            
            // Rewrite post thumbnail URLs
            add_filter('post_thumbnail_html', array($this, 'rewrite_html_urls'), 10, 5);
        }
    }

    private function generate_s3_base_url() {
        $bucket_name = $this->settings->get_option('bucket_name');
        $region = $this->settings->get_option('region');
        $endpoint = $this->settings->get_option('endpoint');
        
        if (!empty($endpoint)) {
            // For S3-compatible services (DigitalOcean, Backblaze, etc.)
            $this->s3_base_url = "https://{$bucket_name}.{$endpoint}";
        } else {
            // For AWS S3
            $this->s3_base_url = "https://{$bucket_name}.s3.{$region}.amazonaws.com";
        }
        
        // Add path prefix if set
        $path_prefix = $this->settings->get_option('path_prefix');
        if (!empty($path_prefix)) {
            $this->s3_base_url .= '/' . trim($path_prefix, '/');
        }
    }
    
    public function rewrite_attachment_url($url, $attachment_id) {
        // Only rewrite URLs for uploaded files
        $upload_dir = wp_upload_dir();
        if (strpos($url, $upload_dir['baseurl']) === false) {
            return $url;
        }
        
        // Check if this attachment is synced to S3
        // $s3_synced = get_post_meta($attachment_id, '_s3_synced', true);
        // if (!$s3_synced) {
        //     return $url;
        // }
        
        // Get the relative path from uploads directory
        $relative_path = str_replace($upload_dir['baseurl'] . '/', '', $url);
        
        if( $this->settings->get_option('use_cdn') ) {
            // Use CDN URL if set
            $cdn_url = $this->settings->get_option('cdn_url');
            if (!empty($cdn_url)) {
                return rtrim($cdn_url, '/') . '/' . $relative_path;
            }
        }
        // Return the S3 URL
        return $this->s3_base_url . '/' . $relative_path;
    }
    
    public function rewrite_srcset_urls($sources, $size_array, $image_src, $image_meta, $attachment_id) {
        // Replace each URL in the srcset with S3 URL
        foreach ($sources as $width => $source) {
            $sources[$width]['url'] = $this->rewrite_attachment_url($source['url'], $attachment_id);
        }
        
        return $sources;
    }
    
    public function rewrite_content_urls($content) {
        // Only process if we have uploads in content
        $upload_dir = wp_upload_dir();
        if (strpos($content, $upload_dir['baseurl']) === false) {
            return $content;
        }
        
        if( $this->settings->get_option('use_cdn') ) {
            // Use CDN URL if set
            $cdn_url = $this->settings->get_option('cdn_url');
            if (!empty($cdn_url)) {
                // Replace all local upload URLs with CDN URLs
                $content = str_replace($upload_dir['baseurl'], rtrim($cdn_url, '/'), $content);
                return $content;
            }
        }
        // Replace all local upload URLs with S3 URLs
        $content = str_replace($upload_dir['baseurl'], $this->s3_base_url, $content);
        
        return $content;
    }
    
    public function rewrite_html_urls($html, $post_id, $post_thumbnail_id, $size, $attr) {
        // Only process if we have uploads in HTML
        $upload_dir = wp_upload_dir();
        if (strpos($html, $upload_dir['baseurl']) === false) {
            return $html;
        }
        
        if( $this->settings->get_option('use_cdn') ) {
            // Use CDN URL if set
            $cdn_url = $this->settings->get_option('cdn_url');
            if (!empty($cdn_url)) {
                // Replace all local upload URLs with CDN URLs
                $html = str_replace($upload_dir['baseurl'], rtrim($cdn_url, '/'), $html);
                return $html;
            }
        }
        // Replace all local upload URLs with S3 URLs
        $html = str_replace($upload_dir['baseurl'], $this->s3_base_url, $html);
        
        return $html;
    }
    
    public function get_s3_base_url() {
        return $this->s3_base_url;
    }
    
    public function get_local_base_url() {
        $upload_dir = wp_upload_dir();
        return $upload_dir['baseurl'];
    }
}