<?php
/**
 * Shortcode class.
 *
 * @since 1.0.0
 *
 * @package owlabkbs
 * @author  owlab
 */
class Owlabbulkg_Slider_Shortcode {


	/**
     * Holds the class object.
     *
     * @since 1.0.0
     *
     * @var object
     */
    public static $instance;

    /**
     * Path to the file.
     *
     * @since 1.0.0
     *
     * @var string
     */
    public $file = __FILE__;

    /**
     * Holds the inline css 
     *
     * @since 1.0.0
     *
     * @var object
     */
    public $inline = '';

     /**
     * Holds the base class object.
     *
     * @since 1.0.0
     *
     * @var object
     */
    public $base;

    /**
     * Holds slider IDs for init firing checks.
     *
     * @since 1.0.0
     *
     * @var array
     */
    public $done = array();

    /**
     * Holds the slider data.
     *
     * @since 1.0.0
     *
     * @var array
     */
    public $data;

    /**
     * Primary class constructor.
     *
     * @since 1.0.0
     */
    public function __construct() {

    	// Load the base class object.
        $this->base = Owlabbulkg::get_instance();

        // Register main slider style.
        // this slider will use the same js file that is used by blog slider se we just need to enque it - rslider at functions-styles-scripts.php

        // Register main slider script.
        // also rslider css is needed which is registered with the toranj theme functions-styles-scripts.php

        // Load hooks and filters.
        add_shortcode( 'bulkgal_slider', array( $this, 'shortcode' ) );
        // Use shortcodes in text widgets.
        add_filter( 'widget_text', 'do_shortcode' );

    }

    /**
     * Creates the shortcode for the plugin.
     *
     * @since 1.0.0
     *
     * @global object $post The current post object.
     *
     * @param array $atts Array of shortcode attributes.
     * @return string     The slider output.
     */
    public function shortcode( $atts ) {

        global $post;

        $myatts = shortcode_atts(array(
			'galleryid' =>'',
			'slug' 		=>'',
			'crop'		=>'',
			'auto'		=> '',
			'speed'		=> 500,
			'timeout'	=> 4000,
			'pager'		=> '',
			'nav'		=> '',
			'random'	=> '',
			'pause'		=> '',
		), $atts,'bulkgal_slider');

        extract($myatts);


        // If no attributes have been passed, we just echo a message
        $gallery_id = false;
        if ( empty( $atts ) ) 
        {
            _e('Hey from Bulk gallery shortcode! You need to pass id parameter or slug parameter to me!','owlabbulkg');
            return;
        } 
        else if ( isset( $atts['galleryid'] ) ) 
        {
            $gallery_id = (int) $atts['galleryid'];
            $data      = is_preview() ? $this->base->_get_gallery( $gallery_id ) : $this->base->get_gallery( $gallery_id );
        } 
        else if ( isset( $atts['slug'] ) ) 
        {
            $gallery_id = $atts['slug'];
            $data      = is_preview() ? $this->base->_get_gallery_by_slug( $gallery_id ) : $this->base->get_gallery_by_slug( $gallery_id );
        } else {
            // A custom attribute must have been passed. Allow it to be filtered to grab data from a custom source.
            $data = apply_filters( 'owlabbulkg_custom_gallery_data', false, $atts, $post );
        }

        // If there is no data and the attribute used is an ID, try slug as well.
        if ( ! $data && isset( $atts['galleryid'] ) ) {
            $gallery_id = (int) $atts['galleryid'];
            $data      = is_preview() ? $this->base->_get_gallery_by_slug( $gallery_id ) : $this->base->get_gallery_by_slug( $gallery_id );
        }

        // If there is no data to output or the slider is inactive, do nothing.
        if ( ! $data ) {
            return false;
        }

        //add atts to the $data
        $data = $data + $myatts;
        $this->data[$data['id']] = $data;
        
        // Load scripts and styles.
        // wp_enqueue_style( 'rslider' );
        // wp_enqueue_script( 'rslider' );



        // Load slider init code in the footer.
        add_action( 'wp_footer', array( $this, 'slider_init' ), 1000 );

        //outputing the layout
        
        $output = '<div class="owlabbulkg-slider-wrapper">';
        $output .= '<ul class="owlabbulkg-rslides" id="gallery-slider-'.$data["id"].'">';
        

        foreach ($data['slider'] as $id=>$image) {
            
            if( isset($image['src']) )
            {
            	
            	$img_src = $image['src'];
                // get the cropped version of the image
                if ( $crop == 'yes' ){
                	$img = wp_get_attachment_image_src( $id,'blog-gallery' );
                	$img_src =$img[0];

                }else{
                	$img = wp_get_attachment_image_src( $id,'full');
                	$img_src = $img[0];
                }

            	
                $output .= '<li><img src="'.$img_src.'" alt="'.$image['title'] .'" /></li>';
           		
            }
        }
        
        $output .= '</ul></div>';
        
        return $output;


    }

    /**
     * Outputs the slider init script in the footer.
     *
     * @since 1.0.0
     */
    public function slider_init() {

        foreach ( $this->data as $id => $data ) {
            // Prevent multiple init scripts for the same slider ID.
            if ( in_array( $data['id'], $this->done ) ) {
                continue;
            }
            $this->done[] = $data['id'];

            $auto = $data['auto']=="no" ? 0 :1;
            $pager = $data['pager']=="yes" ? 1 :0;
            $nav = $data['nav']=="no" ? 0 :1;
            $random = $data['random']=="yes" ? 1 :0;
            $pause = $data['pause']=="yes" ? 1 :0;

            $inline ='
                (function($){
                    
                        var $ = jQuery;
                        var gallery_slide_'.$data["id"].' = $("#gallery-slider-'.$data["id"].'");

                        gallery_slide_'.$data["id"].'.responsiveSlides({
					    	namespace: "owlabgal",
					    	auto: '. $auto .',
						  	speed: '. $data['speed'].', 
						  	timeout: '. $data['timeout'] .', 
						  	pager: '. $pager .', 
						  	nav: '. $nav .', 
						  	random: '. $random .',
						  	pause: '. $pause .'
					    });
                    
                })(jQuery);
            ';
            $this->inline .= $this->minify($inline);
            
        }

        add_action('wp_footer', array( $this,'append_js_to_footer'),100000,1);

    }

    /**
     * Echo exera js 
     *
     * @since 1.0.0
     *
     * @param string $inline the string of js that will be echo
     */
    public function append_js_to_footer() {
        $out = '<script type="text/javascript" id="owlabbulkg-script">';
        $out .= $this->inline;
        $out .='</script>';
        echo $out;
    }

    /**
     * Helper method to minify a string of data.
     *
     * @since 1.0.4
     *
     * @param string $string  String of data to minify.
     * @return string $string Minified string of data.
     */
    public function minify( $string ) {

        $clean = preg_replace( '/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/', '', $string );
        $clean = str_replace( array( "\r\n", "\r", "\t", "\n", '  ', '    ', '     ' ), '', $clean );
        return apply_filters( 'owlabkbs_minified_string', $clean, $string );

    }

	/**
     * Returns the singleton instance of the class.
     *
     * @since 1.0.0
     *
     * @return object The Owlabbulkg_Slider_Shortcode object.
     */
    public static function get_instance() {

        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Owlabbulkg_Slider_Shortcode ) ) {
            self::$instance = new Owlabbulkg_Slider_Shortcode();
        }

        return self::$instance;

    }
}

// Load the shortcode class.
$owlabbulkg_Slider_Shortcode = Owlabbulkg_Slider_Shortcode::get_instance();