<?php

namespace AdminStarterPack;

if (!defined('WPINC')) { die; }

class ImageKitCDN {
    
    private static $_instance;
    private $options = [];
    private $exclude_list;
    private $quality;
    private $imagekitID;
    
    public static function getInstance()
    {
        if (!self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    public function __construct() {
        
        $this->options = get_option('starterpack_options', []);
        
        $this->exclude_list = array_filter(array_map('trim', explode("\n", $this->options['use_free_img_cdn_exclude_list'] ?? '')));
        
        $this->quality = $this->options['use_free_img_cdn_compression_quality'];
        $this->imagekitID = $this->options['imagekit_id'];
        
        add_action('wp_head', [$this, 'printDnsPrefetch'], 0);
        $this->startBuffer();

    }

    protected function excludeKeywords( $matches ) {
        
        $excludeKeywords = $this->exclude_list;
        foreach ( $excludeKeywords as $exclude ) {
            if ( !! $exclude && stristr( $matches, $exclude ) != false ) {
                return true;
            }
        }
        return false;
        
    }

    // Processes the output buffer, replacing all matching images with URLs, pointing to statically url
    public function processOutput( $content ) {

        // Get the content directory URL minus the http://
        $img_url = content_url();
        
        $img_url = str_replace([
            'http://',
            'https://'
        ], ['', ''], $img_url);
        
        return preg_replace_callback(
            '{'. $img_url .'/[^\/\s]+\/\S+\.(jpg|jpeg|png|gif|webp)}i',
            [$this, 'replaceUrl'],
            $content
        );
        
    }

    // Replace matched image URLs
    public function replaceUrl( $matches ) {
        
        if ( $this->excludeKeywords( $matches[0]) ) {
            return $matches[0];
        }
        
        $imagekitID = $this->imagekitID;
        $quality = $this->quality;
        
        // Grab the parsed image URL
        $url = isset( $matches[0] ) ? $matches[0] : '' ;
        
        $site_url = get_home_url();
		
		$site_url = str_replace([
		        	'http://',
		        	'https://'],
		            ['', ''],
		        	 $site_url );
		
		$url  = str_replace($site_url, '', $url);
        
        // construct the url
        
        if ( !empty($quality) ) {
			$cdnUrl = "ik.imagekit.io/$imagekitID/tr:q-$quality";	        
        } else {
	        $cdnUrl = "ik.imagekit.io/$imagekitID";
        }

        
        $final_url = "$cdnUrl$url";
        
        return esc_attr($final_url);
        
    }
    
    // Print the DNS prefetch
    public function printDnsPrefetch() {
	    
	    $domain = "https://ik.imagekit.io.io";
	    echo '<link rel="dns-prefetch" href="' . esc_url($domain) . '">';
        echo '<link rel="preconnect" href="' . esc_url($domain) . '" crossorigin>
';
        
    }

    // Start the output buffering
    public function startBuffer() {
        
        if (!is_admin()) {
            ob_start([$this, 'processOutput']);
            register_shutdown_function([$this, 'endBuffer']);
        }
        
    }

    public function endBuffer() {
	    // Get the contents of the output buffer
	    $this->buffer = ob_get_contents();
	    // Clean the output buffer if it's active
	    if (ob_get_length() > 0) {
	        ob_end_clean();
	    }
	    // Process the modified content
	    echo $this->buffer;
	    // Flush the output buffer if it's active
	    if (ob_get_length() > 0) {
	        ob_end_flush();
	    }
	}

}