<?php
// Do not load directly...
if ( ! defined( 'ABSPATH' ) ) { die( 'Direct access forbidden.' ); }

class ktzsoc_flickr_classes {

	// sanitize double quotes
	public static function ktzsoc_flickr_cleanup( $s = null ) {
		if ( !$s ) return false;

    	else {
    		return str_replace( '"', '', $s );
    	}
	}

	// return Flickr URL based on image size
	public static function ktzsoc_flickr_photo( $url, $size ) {

		$url   = explode( '/', $url );
		$photo = array_pop( $url );

		switch( $size ) {
			case 's':
				$r = preg_replace( '/(_(s|q|t|m|n|c|b))?\./i', '_q.', $photo );
				break;

			case 't':
				$r = preg_replace( '/(_(s|q|t|m|n|c|b))?\./i', '_m.', $photo );
				break;

			case 'm':
				$r = preg_replace( '/(_(s|q|t|m|n|c|b))?\./i', '_n.', $photo );
				break;

			default: // medium
				$r = preg_replace( '/(_(s|q|t|m|n|c|b))?\./i', '.', $photo );
				break;

		}

		$url[] = $r;

    	return implode( '/', $url );

    }

	// find first image
	public static function ktzsoc_find_flickr_photo( $data ) {
		preg_match_all( '/<img src="([^"]*)"([^>]*)>/i', $data, $m );
		return $m[1][0];
	}

}

class KtzSoc_Flickr_Widget extends WP_Widget {
	
	/**
	 * Register widget with WordPress.
	 */
	function __construct() {
		parent::__construct(
			'kentooz_socializer_flickr_plugin', // Base ID
			__('KTZSOC Flickr', 'kentooz-socializer'), // Name
			array( 'description' => __( 'Drag and drop this widget for display flickr image.', 'kentooz-socializer' ), ) // Args
		);
	}
	
	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		
		$title = apply_filters( 'widget_title', $instance['title'] );
		
        $type = empty( $instance['type'] ) ? 'user' : $instance['type'];
		
        $flickr_id = empty( $instance['flickr_id'] ) ? '' : $instance['flickr_id'];
        
		$count =  empty( $instance['count'] ) ? 9 : (int) $instance['count'];
		
		$thumb = isset( $instance['size'] ) ? $instance['size'] : 's';
		
		$column = isset( $instance['column'] ) ? $instance['column'] : 3;
		
		include_once( ABSPATH . WPINC . '/feed.php' ); // load feed.php

		// determine if this is a group feed or not
		if ( $type == 'group' ) { // if a group feed
			$rss = fetch_feed( 'https://api.flickr.com/services/feeds/groups_pool.gne?id=' . $flickr_id . '&lang=en-us&format=rss_200' );
		} else { // if not a group feed
			$rss = fetch_feed( 'https://api.flickr.com/services/feeds/photos_public.gne?id=' . $flickr_id . '&lang=en-us&format=rss_200' );
		}
 
		echo $args['before_widget'];
		if ( ! empty( $title ) )
			echo $args['before_title'] . $title . $args['after_title'];
		
		if ( ! empty( $instance['intro_text'] ) )
			echo '<p>' . do_shortcode( $instance['intro_text'] ) . '</p>';
		
		if ( $column == 4 ) {
			$col = ' ktzsoc-col4';
		} elseif ( $column == 2 ) {
			$col = ' ktzsoc-col2';
		} else {
			$col = '';
		}
		
		echo '<div class="ktzsoc-grid' . $col . ' ktzsoc-flickr-wrap">';
		
		if( ! is_wp_error( $rss ) ) {
		
			$maxitems = $rss->get_item_quantity( $count );
			$rss_items = $rss->get_items( 0, $maxitems );

			if ( is_wp_error( $rss ) ) {
				
				$error_string = $rss->get_error_message();
				echo '<div class="error"><p>' . $error_string . '</p></div>';
			
			} else {
				
				if ( $maxitems == 0 ) {					
					echo '<p>' . __( 'No images found.', 'kentooz-socializer' ) . '</p>';
				} else{
					echo '<ul>';
					foreach ( $rss_items as $item ) :

						$url       = ktzsoc_flickr_classes::ktzsoc_find_flickr_photo( $item->get_description() );
						$title     = ktzsoc_flickr_classes::ktzsoc_flickr_cleanup( $item->get_title() );
						$thumb_url = ktzsoc_flickr_classes::ktzsoc_flickr_photo( $url, $thumb );

						echo '<li><a href="' . esc_url( $item->get_permalink() ) . '" title="' . esc_attr( $title ) . '" target="_blank">';
							echo '<img src="' . esc_url( $thumb_url ) . '" alt="' . esc_attr( $title ) . '" />';
						echo '</a></li>';

					endforeach;	
					echo '</ul>';
				}

			}
		} else {
				echo '<div class="error"><p>Can not find user or group ID. Please insert valid ID in your widget flickr settings.</p></div>';
		}
				
		echo '</div>';
		
		if ( ! empty( $instance['outro_text'] ) )
			echo '<p>' . do_shortcode( $instance['outro_text'] ) . '</p>';
		
		echo $args['after_widget'];
	}

	/* Update the widget settings. */
    public function update( $new_instance, $old_instance ) {
    	$instance = $old_instance;
		
		$instance['title']		 	= strip_tags($new_instance['title']);
		
		$instance['type'] 			= strip_tags($new_instance['type']);
		
		$instance['flickr_id'] 		= strip_tags($new_instance['flickr_id']);
		
		$instance['count'] 			= (int) $new_instance['count'];
		
		$instance['column'] 		= (int) $new_instance['column'];
		
		$instance['size']			= strip_tags($new_instance['size']);
		
		$instance['intro_text'] 	= $new_instance['intro_text'];
		
		$instance['outro_text']		= $new_instance['outro_text'];
		
        return $instance;
    }

	public function form( $instance ) {
		$instance = wp_parse_args( (array) $instance, 
			array( 
				'title'			=> esc_attr__( 'Flickr Widget', 'kentooz-socializer' ),
				'type'			=> 'user',
				'flickr_id'		=> '', // 83779042%40N07
				'count'			=> 9,
				'size'			=> 's',
				'column'		=> 3,
				'intro_text'	=> '',
				'outro_text'	=> ''
			) 
		);
		
		$types = array( 
			'user'  => esc_attr__( 'user', 'kentooz-socializer' ), 
			'group' => esc_attr__( 'group', 'kentooz-socializer' )
		);
		$sizes = array(
			's' => esc_attr__( 'Small 150 x 150', 'kentooz-socializer' ), 
			't' => esc_attr__( 'Medium 240 x 180', 'kentooz-socializer' ),
			'm' => esc_attr__( 'Large 320 x 240', 'kentooz-socializer' )
		);
		$columns = array( 
			'4'  => esc_attr__( '4 column', 'kentooz-socializer' ), 
			'3' => esc_attr__( '3 column', 'kentooz-socializer' ), 
			'2' => esc_attr__( '2 column', 'kentooz-socializer' ),
		);
		?>

        <p>
			<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:','kentooz-socializer'); ?></label> 
			<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
        </p>
		
        <p>
			<label for="<?php echo $this->get_field_id('type'); ?>"><?php _e( 'Type', 'kentooz-socializer' ); ?></label>
			<select id="<?php echo $this->get_field_id( 'type' ); ?>" name="<?php echo $this->get_field_name( 'type' ); ?>" class="widefat">
				<?php foreach ( $types as $k => $v ) { ?>
					<option value="<?php echo esc_attr( $k ); ?>" <?php selected( $instance['type'], $k ); ?>><?php echo esc_html( $v ); ?></option>
				<?php } ?>
			</select>	
			<br/>
			<small><?php _e( 'The type of images from user or group.', 'kentooz-socializer' ); ?></small>
        </p>
		
		<p>
			<label for="<?php echo $this->get_field_id('flickr_id'); ?>"><?php _e('Flickr ID', 'kentooz-socializer' ); ?></label>							
			<input class="widefat" id="<?php echo $this->get_field_id('flickr_id'); ?>" name="<?php echo $this->get_field_name('flickr_id'); ?>" type="text" value="<?php echo esc_attr( $instance['flickr_id'] ); ?>" />
			<br/>
			<small><?php _e( 'Put the flickr ID here, go to <a href="http://idgettr.com/" target="_blank">Flickr NSID Lookup</a> if you don\'t know your ID. Example: 83779042%40N07', 'kentooz-socializer' ); ?></small>
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id('count'); ?>"><?php _e('Number','kentooz-socializer'); ?></label>
			<input id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" type="number" min="1" max="10" value="<?php echo esc_attr( $instance['count'] ); ?>" size="3" />
			<br/>
			<small><?php _e( 'Number of images shown from 1 to 10', 'kentooz-socializer'); ?></small>
		</p>
		
        <p>
			<label for="<?php echo $this->get_field_id('column'); ?>"><?php _e( 'Column', 'kentooz-socializer' ); ?></label>
			<select id="<?php echo $this->get_field_id( 'column' ); ?>" name="<?php echo $this->get_field_name( 'column' ); ?>" class="widefat">
				<?php foreach ( $columns as $k => $v ) { ?>
					<option value="<?php echo esc_attr( $k ); ?>" <?php selected( $instance['column'], $k ); ?>><?php echo esc_html( $v ); ?></option>
				<?php } ?>
			</select>	
			<br/>
			<small><?php _e( 'Select number column the grid.', 'kentooz-socializer' ); ?></small>
        </p>
		
		<p>
			<label for="<?php echo $this->get_field_id('size'); ?>"><?php _e( 'Sizes', 'kentooz-socializer' ); ?></label>
			<select id="<?php echo $this->get_field_id( 'size' ); ?>" name="<?php echo $this->get_field_name( 'size' ); ?>" class="widefat">
				<?php foreach ( $sizes as $k => $v ) { ?>
					<option value="<?php echo $k; ?>" <?php selected( $instance['size'], $k ); ?>><?php echo $v; ?></option>
				<?php } ?>
			</select>
			<br/>
			<small><?php _e( 'Represents the size of the image', 'kentooz-socializer' ); ?></small>
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id('intro_text'); ?>"><?php _e( 'Intro Text', 'kentooz-socializer' ); ?></label>
			<textarea name="<?php echo $this->get_field_name( 'intro_text' ); ?>" id="<?php echo $this->get_field_id( 'intro_text' ); ?>" rows="2" class="widefat"><?php echo esc_textarea($instance['intro_text']); ?></textarea>
			<br/>
			<small><?php _e( 'This option will display addtional text before the widget content and HTML supports.', 'kentooz-socializer' ); ?></small>	
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id('outro_text'); ?>"><?php _e( 'Outro Text', 'kentooz-socializer' ); ?></label>
			<textarea name="<?php echo $this->get_field_name( 'outro_text' ); ?>" id="<?php echo $this->get_field_id( 'outro_text' ); ?>" rows="2" class="widefat"><?php echo esc_textarea($instance['outro_text']); ?></textarea>
			<br/>
			<small><?php _e( 'This option will display addtional text after widget and HTML supports.', 'kentooz-socializer' ); ?></small>			
		</p>	
		
	<?php
	}
}

// TODO: Remember to change 'Widget_Name' to match the class name definition
add_action( 'widgets_init', function(){
     register_widget( 'KtzSoc_Flickr_Widget' );
});