<?php

// PORTFOLIO
add_action('widgets_init', create_function('', 'return register_widget("toppic_portfolio_widget");'));

class toppic_portfolio_widget extends WP_Widget{

	function __construct() {
		$widget_ops = array(
					'classname' => 'toppic_portfolio_widget',
					'description' => esc_html__('Shows a few portfolio works linked to your current work','toppic')
					);
		parent::__construct( 'portfolio_items', esc_html__('Portfolio widget','toppic'), $widget_ops );
	}
	
	function widget($args, $instance){
		extract($args);
		$title = apply_filters('widget_title', $instance['title']); if(empty($title)) $title= esc_html__('Latest projects','toppic');
		$display = $instance['display'];
		$number = $instance['number']; if(empty($number)) $number=4;

		global $post;

		echo wp_kses_post($before_widget);
		echo wp_kses_post($before_title.$title.$after_title); ?>
		
		
		<ul class="kk-portfolio-widget">
		<?php 
		$args = array(
				'post_type'   => 'portfolio', 
				'numberposts' => (int)$number, 
				'exclude'     => get_the_ID()
			);
			
		$works = get_posts( $args );

		foreach ( $works as $work ) {
			
			printf( '<li class="widget-img"><a href="%1$s">%2$s</a></li>',
				esc_attr( get_permalink( $work->ID ) ),
				get_the_post_thumbnail( $work->ID, 'thumbnail', array( 'data-lazy-load' => 0 ) )
			);
		}; wp_reset_query(); ?>
		</ul>
		
		<?php echo wp_kses_post($after_widget);
	}


function update($new_instance, $old_instance){
	$instance = $old_instance;
	$instance['title'] = strip_tags($new_instance['title']);
	$instance['display'] = $new_instance['display'];
	$instance['number'] = $new_instance['number'];
	return $instance;
}

function form($instance){
	$instance = wp_parse_args((array)$instance, array('title'=>'', 'text'=>'', 'title_link'=>''));
	$title = strip_tags($instance['title']);
	$display = isset( $instance['display'] ) ? $instance['display'] : false;
	$number = isset( $instance['number'] ) ? $instance['number'] : false;

	$text = format_to_edit($instance['text']);?>
	  <p><label><?php esc_html_e( 'Title:', 'toppic' )?><input class="widefat" id="<?php echo esc_attr( $this->get_field_id(strtolower('title'))) ?>" name="<?php echo esc_attr( $this->get_field_name(strtolower('title'))) ?>" type="text" value="<?php echo esc_attr( $title )?>" /></label></p>
	  <p><label><?php esc_html_e( 'Number of works:', 'toppic' )?><input class="widefat" id="<?php echo esc_attr( $this->get_field_id(strtolower('number'))) ?>" name="<?php echo esc_attr( $this->get_field_name(strtolower('number'))) ?>" type="text" value="<?php echo esc_attr( $number )?>" /></label></p>
	<?php
}
}