<?php
/*
 * Widgets
 * * * 1. Testimonials carousel widget
 */

/*
 * 1. Testimonials carousel widget
 */
function sell_out_template ($post, $text, $pic) {
    $out = '<div class="item" id="post-'. $post->ID .'">
	            <div class="bubbles">
			        <div class="mention">
				        <p>'.
					    $text.
					    '</p>
					</div>
				    <div class="face">'.
				        $pic.
				    '</div>	
			    </div>
			</div>';
			
	return $out;
	 
}

function sell_testimonial_out ($post) {

	$client_name = types_render_field("name-of-client", array("post_id" => $post->ID, "output"=>"normal"));
	$client_post = types_render_field("post-of-client", array("post_id" => $post->ID, "output"=>"normal"));
	$client_photo = types_render_field("photo-of-client", array("post_id" => $post->ID, "url" => "true"));
	
	$text = implode(' ', array_slice( explode(' ', $post->post_content), 0, 25) );
	
	$pic = '<a href="' . get_permalink($post->ID) . '"><img src="'.$client_photo.'" alt=""></a><strong><a href="'. get_permalink($post->ID) . '">' . $client_name . '</strong></a><p>'.$client_post.'</p>';
				
	$output = sell_out_template ($post, $text, $pic);
	
	return $output;

}

function sell_teammate_out ($post) {

    $description = types_render_field("post-of-member", array("post_id" => $post->ID, "output"=>"normal"));
	$photo = types_render_field("photo-of-member", array("post_id" => $post->ID, "output"=>"normal"));
	$pic = $photo.'<strong>'.$post->post_title.'</strong><p>'.$description.'</p>';
	
	$output = sell_out_template ($post, $post->post_content, $pic);
	
	return $output;
	
}

function sell_service_out ($post) {
    
	$pic = types_render_field("sicon", array("post_id" => $post->ID, "output"=>"normal"));
	$text = $post->post_excerpt;
	
	$output = sell_out_template ($post, $text, $pic);
	
	return $output;
}

function sell_standart_out ($post) {
    $pic = get_the_post_thumbnail( $post->ID, 'thumbnail', array ( 'alt'=> trim(strip_tags( $post->post_excerpt )), 
	                                                               'title'=> trim(strip_tags( $post->post_title )) ) );
    $text = thelawyer_get_excerpt( $post, null, 25 );
	$output = sell_out_template ($post, $text, $pic);
	return $output;
}


class Slick_Carousel extends WP_Widget {

	function __construct() {
		parent::__construct(
			'sl_slick_carousel', // Base ID
			esc_attr__('Testimonials Carousel', 'the-guard'), // Name
			array( 'description' => esc_attr__( 'Testimonials Carousel Widget', 'the-guard' ), ) // Args
		);
	}


	public function widget( $args, $instance ) {
	
	    $args = extract($args);
		$title = $instance['title'];
		$class = $instance['box_class'];
		//$pts = $instance['pt'];
		$pts = 'testimonial';
		$qnt = $instance['qnt'];
		$widget_id = $instance['widget_id'];
		//var_dump($instance);
		
	
	    $posts_per_page = isset($instance['posts_per_page']) ? $instance['posts_per_page'] : 5;

	    $result = new WP_query(array( 'post_type' => $pts, 'posts_per_page' => $qnt ));
		$output = $html_id = '';
		
		if ( $result->posts ) :	
		
			$html_id = 'id="##"';
		
		    $output = '<aside ' . str_ireplace('##', $instance['aside_id'], $html_id) . ' class="aside_' . $class . '"><h3 class="widget-title">' . $title . '</h3><div id="'. $widget_id .'" class="' . $class . '">';
                           	
			foreach ( $result->posts as $post ) :
			
			    if ( $post->post_type == 'post' || $post->post_type == 'page' || $post->post_type == 'portfolio' || $post->post_type == 'attachment') $pt = 'standart';
                else $pt = $post->post_type;				
			    $func = 'sell_' . $pt . '_out';

			    $output .= $func($post);
				
			endforeach;
			
			$output .= '</div></aside>';
			
		endif;
		
		$result = null;
		wp_reset_postdata();
		
		echo $output;
	
	}

	public function form( $instance ) {
	
	    $title = isset( $instance[ 'title' ] ) ? $instance[ 'title' ] : 'Testimonials';
	    $box_class = isset( $instance[ 'box_class' ] ) ? $instance[ 'box_class' ] : 'widget_testimonial_carousel';
		$qnt = isset( $instance[ 'qnt' ] ) ? $instance[ 'qnt' ] : 5;
		$autoplaySpeed = isset( $instance[ 'autoplaySpeed' ] ) ? $instance[ 'autoplaySpeed' ] : 3000;
		$slick_autoplay = isset($instance['autoplay']) ? esc_attr($instance['autoplay']) : 1;
		$slick_arrows = isset($instance['arrows']) ? esc_attr($instance['arrows']) : 1;
		$slick_dots = isset($instance['dots']) ? esc_attr($instance['dots']) : 1;
		if ( isset( $instance[ 'aside_id' ] ) ) {
		    $aside_id = $instance[ 'aside_id' ];
		}
		else {
		    if ( isset( $instance[ 'widget_id' ] )) {
			    $aside_id = str_ireplace('widget_', 'aside_', $instance[ 'widget_id' ]);
			}
			else {
			    $aside_id = '';
			}
		}
		
		    echo '
			    <label class="slick_widget" for="' . $this->get_field_id( 'title' ) . '">' . esc_attr__( 'Set title:', 'the-guard' ) . '</label>
		        <input class="widefat" id="' . $this->get_field_id( 'title' ) . '" name="' . $this->get_field_name( 'title' ) . '" type="text" value="' . esc_attr( $title ) . '"/>';		
		
		    echo '
			    <label class="slick_widget" for="' . $this->get_field_id( 'box_class' ) . '">' . esc_attr__( 'Set carousel conteiner class:', 'the-guard' ) . '</label>
		        <input class="widefat" id="' . $this->get_field_id( 'box_class' ) . '" name="' . $this->get_field_name( 'box_class' ) . '" type="text" value="' . esc_attr( $box_class ) . '"/>';
		    echo '
			    <label class="slick_widget" for="' . $this->get_field_id( 'qnt' ) . '">' . esc_attr__( 'Posts to show:', 'the-guard' ) . '</label>
		        <input class="widefat" id="' . $this->get_field_id( 'qnt' ) . '" name="' . $this->get_field_name( 'qnt' ) . '" type="text" value="' . esc_attr ( $qnt ) . '"/>';				
				
			echo '
			    <input class="widefat"' . ' id="' . $this->get_field_id( 'autoplay' ) . '" name="' . $this->get_field_name( 'autoplay' ) . '"' . ' type="checkbox" value="1"' . checked("1", $slick_autoplay, false) . '/><label class="slick_widget" for="' . $this->get_field_id( 'autoplay' ) . '">' . esc_attr__( 'Set autoplay mode:', 'the-guard' ) . '</label>';
				
			echo '
				<br>
				<label class="slick_widget"for="' . $this->get_field_id( 'autoplaySpeed' ) . '">' . esc_attr__( 'Set autoplay speed (ms):', 'the-guard' ) . '</label>
			    <input class="widefat" id="' . $this->get_field_id( 'autoplaySpeed' ) . '" name="' . $this->get_field_name( 'autoplaySpeed' ) . '" type="text" value="' . esc_attr( $autoplaySpeed ) . '"/>';			
				
			echo '
			    <input class="widefat"' . ' id="' . $this->get_field_id( 'arrows' ) . '" name="' . $this->get_field_name( 'arrows' ) . '"' . ' type="checkbox" value="1"' . checked("1", $slick_arrows, false) .  '/>' . 
				'<label class="slick_widget" for="' . $this->get_field_id( 'arrows' ) . '">' . esc_attr__( 'navigation arrows on/off:', 'the-guard' ) . '</label><br>';
			echo '
			    <input class="widefat"' . ' id="' . $this->get_field_id( 'dots' ) . '" name="' . $this->get_field_name( 'dots' ) . '"' . ' type="checkbox" value="1"' . checked("1", $slick_dots, false) . '/>' .
				'<label class="slick_widget" for="' . $this->get_field_id( 'dots' ) . '">' . esc_attr__( 'navigation dots on/off:', 'the-guard' ) . '</label><br>';
	}


	public function update( $new_instance, $old_instance ) {
	
	    $instance = $old_instance;
		
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : 'Testimonials';		
		$instance['box_class'] = ( ! empty( $new_instance['box_class'] ) ) ? strip_tags( $new_instance['box_class'] ) : 'widget_testimonial_carousel';
		$instance['qnt'] = ( ! empty( $new_instance['qnt'] ) ) ? strip_tags( $new_instance['qnt'] ) : 5;
		$instance[ 'autoplay' ] = strip_tags( $new_instance[ 'autoplay' ] );
		$instance[ 'arrows' ] = strip_tags( $new_instance[ 'arrows' ] );
		$instance[ 'dots' ] = strip_tags( $new_instance[ 'dots' ] );
		//$instance[ 'pt' ] = esc_sql( $new_instance[ 'pt' ] );
		
		$widget_id = null;
		if ( !isset($_POST[ 'multi_number' ]) || $_POST[ 'multi_number' ] == '' ) {
		    $widget_id = 'widget_' . $_POST[ 'widget-id' ][0];
		}
		else {
		    $n = $_POST[ 'multi_number' ];
			if ( count( $_POST[ 'widget-id' ] ) > 0 ) {
		        foreach ( $_POST[ 'widget-id' ] as $v ) {
			        if ( preg_match( '/' . $n . '/', $v) ) {
				        $widget_id = 'widget_' . $v;
					    break;
				    }
			    }
				if ( !$widget_id ) {
				    $widget_id = 'widget_' . $_POST[ 'id_base' ] . '-' . $n;
				}
			}
			else {
			    $widget_id = 'widget_' . $_POST[ 'id_base' ] . '-' . $n;
			}
		}
		$instance[ 'widget_id' ] = $widget_id;
		if ( ! empty( $new_instance['aside_id'] ) ) {
		    $instance['aside_id'] = strip_tags( $new_instance['aside_id'] );
		}
		else {
		    $instance['aside_id'] = str_ireplace('widget_', 'aside_', $widget_id);
		}
		
		$args = array();
		
		if (!empty($new_instance['box_class'])) $class = $new_instance['box_class']; else $class = 'widget_testimonial_carousel';
		if (!empty($new_instance[ 'autoplay' ])) $args['autoplay'] = 'autoplay : true'; else $args['autoplay'] = 'autoplay : false';
		if (preg_match('/true/', $args['autoplay'])) {
		    if (!empty($new_instance[ 'autoplaySpeed' ])) $args['autoplaySpeed'] = 'autoplaySpeed : ' . $new_instance[ 'autoplaySpeed' ]; else $args['autoplaySpeed'] = 3000;
			$instance[ 'autoplaySpeed' ] = ( ! empty( $new_instance['autoplaySpeed'] ) ) ? strip_tags( $new_instance['autoplaySpeed'] ) : 3000;
		}		
		if (!empty($new_instance[ 'arrows' ])) $args['arrows'] = 'arrows : true'; else $args['arrows'] = 'arrows : false';
		if (!empty($new_instance[ 'dots' ])) $args['dots'] = 'dots : true'; else $args['dots'] = 'dots : false';
		
		$prefix = 'jQuery(document).ready(function() { ';
		
		$script = 
		'jQuery("#'. $widget_id . '.' . $class . '").slick({ '.
            implode(', ', $args) .
		    ' ,slidesPerRow : '.'1'.
		    ',slidesToScroll : '.'1'.
		    ',slidesToShow : '.'1'. ' });';
			
		$postfix = ' });';
		
		global $wp_filesystem;
		
		if( empty( $wp_filesystem ) ) {
		    include_once ABSPATH.'/wp-admin/includes/file.php';
	        WP_Filesystem();
		}
		 
		if( $wp_filesystem ) {
		    if ( file_exists( get_template_directory () . '/js/widget_carousel.js' ) ) {
			    $content = $wp_filesystem->get_contents( get_template_directory () . '/js/widget_carousel.js' );
				if (strlen($content) > 0) {
				    if ( preg_match('/#' . $widget_id . '/i', $content) ) {
				        $content = preg_replace( '/jQuery\(\"#'. $widget_id . '[^;]+;/Ui', $script, $content );
				    }
				    else {
				        $content = preg_replace( '/\}\);\s+\}\);/i','}); ' . $script . ' });' , $content );
				    }
				}
				else {
				    $content = $prefix . $script . $postfix;
				}
			}
			else {
			    $content = $prefix . $script . $postfix;
			}
			$wp_filesystem->put_contents( get_template_directory () . '/js/widget_carousel.js', $content );
		}
		
		return $instance;
    
	}

} 


function sell_register_slick_carousel_widget() {
	register_widget( 'Slick_Carousel' );
}
add_action( 'widgets_init', 'sell_register_slick_carousel_widget' );

function sell_get_widget_carousel_script() {

    if (!is_admin()) {
	
        wp_register_style( 'slick_css', esc_url(get_template_directory_uri()) . '/js/lib/slick/slick.css', array(), false, 'all' );
        wp_enqueue_style( 'slick_css');
        wp_register_script('slick_js', esc_url(get_template_directory_uri()) . '/js/lib/slick/slick.js', array('jquery'), false, true);
        wp_enqueue_script('slick_js');
        wp_register_script('thelawyer_widget_carousel_js', esc_url(get_template_directory_uri()) . '/js/widget_carousel.js', array('jquery', 'slick_js'), false, true);
        wp_enqueue_script('thelawyer_widget_carousel_js');
	}

}

add_action('init', 'sell_get_widget_carousel_script');


function sell_sidebar_widgets_admin_setup() {

    if ( 'post' == strtolower( $_SERVER['REQUEST_METHOD'] ) ) {

        $widget_id = 'widget_' . $_POST['widget-id'];

            if ( isset( $_POST['delete_widget'] ) && $_POST['id_base'] == 'sl_slick_carousel' ) {
                if ( 1 === (int) $_POST['delete_widget'] ) {
				
				global $wp_filesystem;
		
		        if( empty( $wp_filesystem ) ) {
		            include_once ABSPATH.'/wp-admin/includes/file.php';
	                WP_Filesystem();
		        }
				
				$content = $wp_filesystem->get_contents( get_template_directory () . '/js/widget_carousel.js' );
				$content = preg_replace( '/jQuery\(\"#'. $widget_id . '[^;]+;/Ui', '', $content );
				
				if ( preg_match( '/'. $_POST[ 'id_base' ] .'/' , $content ) ) {
			        $wp_filesystem->put_contents( get_template_directory () . '/js/widget_carousel.js', $content );
				}
				else {
				    $wp_filesystem->put_contents( get_template_directory () . '/js/widget_carousel.js', '' );
				}
				

                }
            }

    }

}

add_action( 'sidebar_admin_setup', 'sell_sidebar_widgets_admin_setup' );


function sell_get_admin_widget_carousel_script() {

    if (preg_match('/widgets.php/', $_SERVER['PHP_SELF'])) { 

        wp_register_script('admin_slick_js', esc_url(get_template_directory_uri()) . '/js/lib/admin_slick.js', array('jquery'), false, false);
        wp_enqueue_script('admin_slick_js');   
		
	}
}

add_action('admin_init', 'sell_get_admin_widget_carousel_script');


?>
