<?php
/* Security-Check */
if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class pbsfi_pro
{
	/** @var pbSEOFriendlyImages */
	var $pbSEOFriendlyImages;

	var $updateURL = 'https://pb-seo-friendly-images.s3-eu-west-1.amazonaws.com/';
	var $updateslug = 'pb-seo-friendly-images-pro';
	var $updatejson = 'pb-seo-friendly-images-pro-4.json';

	public function __construct( pbSEOFriendlyImages &$pb_SEO_friendly_images )
	{
		$this->pbSEOFriendlyImages = $pb_SEO_friendly_images;

		$this->updater();

		add_action('wp', array($this, 'initialize'));

		if( false === $this->pbSEOFriendlyImages->isProVersion() ) {
			// ?!
		}
	}

	public function initialize()
	{
		if( ! is_admin() && ! is_feed() ) {

			if( (isset($this->pbSEOFriendlyImages->settings['enable_lazyload']) && $this->pbSEOFriendlyImages->settings['enable_lazyload']) ||
                (isset($this->pbSEOFriendlyImages->settings['enable_lazyload_acf']) && $this->pbSEOFriendlyImages->settings['enable_lazyload_acf']) ) {
				add_action( 'wp_head', array($this, 'thresholdVariable') );
				add_action( 'wp_enqueue_scripts', array($this, 'unveilScript') );
			}

			if( isset($this->pbSEOFriendlyImages->settings['enable_lazyload']) && $this->pbSEOFriendlyImages->settings['enable_lazyload'] ) {
				add_filter( 'post_thumbnail_html', array($this, 'lazyLoadImages') );
				add_filter( 'the_content', array($this, 'lazyLoadImages'), 12 );
				add_filter( 'get_avatar', array($this, 'lazyLoadImages') );
			}

			if( isset($this->pbSEOFriendlyImages->settings['enable_lazyload_acf']) && $this->pbSEOFriendlyImages->settings['enable_lazyload_acf'] ) {
				add_filter( 'acf/load_value/type=textarea', array($this, 'lazyLoadImages'), 19 );
				add_filter( 'acf/load_value/type=wysiwyg', array($this, 'lazyLoadImages'), 19 );

				add_filter( 'acf_load_value-textarea', array($this, 'lazyLoadImages'), 20 );
				add_filter( 'acf_load_value-wysiwyg', array($this, 'lazyLoadImages'), 20 );
			}

			/*if( $this->pbSEOFriendlyImages->settings['link_title'] ) {
				add_filter( 'the_content', array($this, 'optimizeLinkTitle'), 998 );

				add_filter( 'acf/load_value/type=textarea', array($this, 'optimizeLinkTitle'), 19 );
				add_filter( 'acf/load_value/type=wysiwyg', array($this, 'optimizeLinkTitle'), 19 );

				add_filter( 'acf_load_value-textarea', array($this, 'optimizeLinkTitle'), 20 );
				add_filter( 'acf_load_value-wysiwyg', array($this, 'optimizeLinkTitle'), 20 );
			}*/

			if( isset($this->pbSEOFriendlyImages->settings['disable_srcset']) && $this->pbSEOFriendlyImages->settings['disable_srcset'] ) {
                add_filter( 'wp_calculate_image_srcset', '__return_false' );
                add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
			}
		}
	}

    /**
     * Threshold variable for wp_head
     */
    public function thresholdVariable()
    {
        $lazyload_threshold = $this->pbSEOFriendlyImages->settings['lazyload_threshold'];

        if( is_numeric($lazyload_threshold) && $lazyload_threshold > 0 ) {
            echo '<script>var pbUnveilThreshold = '.trim($lazyload_threshold).';</script>';
        }
    }

    /**
     * Unveil Script
     */
    public function unveilScript()
    {
        if( $this->pbSEOFriendlyImages->settings['enable_lazyload_styles'] ) {
            wp_register_style('unveil-css', $this->pbSEOFriendlyImages->plugin['url'].'/assets/css/lazy.css', false, '1.0.0');
            wp_enqueue_style('unveil-css');
        }

        wp_register_script('unveil', $this->pbSEOFriendlyImages->plugin['url'].'/assets/js/unveil.js', array('jquery'), '1.0.0', true);
        wp_enqueue_script('unveil');
    }

    public function lazyLoadImages($content)
    {
        /* No lazy images? */
        if( true === apply_filters('pbsfi_disable_lazyloadimages', false) ) {
            return $content;
        }

        if ( strpos($content, '<img') === false ) {
            return $content;
        }

        if( get_post_type() == 'tribe_events' || is_feed() ) {
            return $content;
        }

        /* Empty gif */
        $null = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

        preg_match_all('#(<img(.*?)src=["\'](.+?)["\'](.*?)(/?)>)#', $content, $matches, PREG_PATTERN_ORDER);

        if( $matches ) {
            foreach( $matches[0] as $img ) {
                $new_img = $img;

                if(
                    strstr($img, 'lazy') ||
                    strstr($img, 'no-lazy') ||
                    strstr($img, 'image/gif;base64') ||
                    strstr($img, 'blank.gif') ||
                    strstr($img, 'data-src=') ||

                    // MasterSlider
                    strstr($img, 'ms-slide') ||
                    strstr($img, 'ms-thumb')
                ) {
                    continue;
                }

                $new_img = str_replace('src="', 'src="'.$null.'" data-src="', $new_img);

                if( strpos($new_img, 'class=') === false ) {
                    $new_img = str_replace('src="', 'class="pb-seo-lazy" src="', $new_img);
                } else {
                    $new_img = str_replace('class="', 'class="pb-seo-lazy ', $new_img);
                }

                $content = str_replace($img, $new_img.'<noscript>'.$img.'</noscript>', $content);
            }
        }

        return $content;
    }

	protected function updater()
    {
        try{
            $UpdateChecker = Puc_v4_Factory::buildUpdateChecker(
                $this->updateURL.$this->updatejson,
                $this->pbSEOFriendlyImages->plugin['file'],
                $this->updateslug
            );
        } catch (Exception $e) {
            new WP_Error( 'broke', 'Puc_v4_Factory failed!' );
        }
    }
}