<?php
/**
 * Instagram Widget
 *
 * @package Theme Palace
 * @subpackage Personify Pro
 * @since Personify Pro 1.0
 */

if ( ! class_exists( 'Personify_Pro_Instagram_Widget' ) ) :
	/**
	 * Instragram class.
	 * 
	 */
	class Personify_Pro_Instagram_Widget extends WP_Widget {

		/**
		 * Holds widget settings defaults, populated in constructor.
		 *
		 * @var array
		 */
		protected $defaults;

		/**
		 * Constructor. Set the default widget options and create widget.
		 *
		 * @since 1.0
		 */
		function __construct() {
			$this->defaults = array(
				'title'    => esc_html__( 'Instagram', 'personify-pro' ),
				'username' => '',
				'layout'   => 'col-1',
				'number'   => 5,
				'size'     => 'small',
				'target'   => 0,
				'link_text'     => '',
			);

			$tp_widget_instagram = array(
				'classname'   => 'tp-instagram tpinstagram tpfeaturedpostpageimage',
				'description' => esc_html__( 'Displays your latest Instagram photos', 'personify-pro' ),
			);

			$tp_control_instagram = array(
				'id_base' => 'tp-instagram',
			);

			parent::__construct(
				'tp-instagram', // Base ID
				esc_html__( 'TP: Instagram', 'personify-pro' ), // Name
				$tp_widget_instagram,
				$tp_control_instagram
			);
		}

		function form( $instance ) {
			$instance = wp_parse_args( (array) $instance, $this->defaults );

			?>
			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title', 'personify-pro' ); ?>:</label>
				<input type="text" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>" class="widefat" />
			</p>

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'username' ) ); ?>"><?php esc_html_e( 'Access Token', 'personify-pro' ); ?>:</label>
				<input type="text" id="<?php echo esc_attr( $this->get_field_id( 'username' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'username' ) ); ?>" value="<?php echo esc_attr( $instance['username'] ); ?>" class="widefat" />
			</p>
			<p><?php printf( esc_html__( 'Get your Instagram token ID from %1$s HERE %2$s', 'personify-pro' ), '<a target="_blank" href="https://instagram.pixelunion.net/">', '</a>' ); ?></p>

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'layout' ) ); ?>"><?php esc_html_e( 'Layout', 'personify-pro' ); ?>:</label>
				<select id="<?php echo esc_attr( $this->get_field_id( 'layout' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'layout' ) ); ?>" class="widefat">
					<?php
						$post_type_choices = array(
							'col-1'  => esc_html__( '1 Column', 'personify-pro' ),
							'col-2'  => esc_html__( '2 Column', 'personify-pro' ),
							'col-3'  => esc_html__( '3 Column', 'personify-pro' ),
							'col-4'  => esc_html__( '4 Column', 'personify-pro' ),
							'col-5'  => esc_html__( '5 Column', 'personify-pro' ),
						);

					foreach ( $post_type_choices as $key => $value ) {
						echo '<option value="' . esc_attr( $key ) . '" '. selected( $key, $instance['layout'], false ) .'>' . esc_html( $value ) .'</option>';
					}
					?>
				</select>
			</p>

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php esc_html_e( 'Number of photos', 'personify-pro' ); ?>:</label>
				<input type="number" id="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" value="<?php echo absint( $instance['number'] ); ?>" class="small-text" min="1" />
			</p>

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'size' ) ); ?>"><?php esc_html_e( 'Instagram Image Size', 'personify-pro' ); ?>:</label>
				<select id="<?php echo esc_attr( $this->get_field_id( 'size' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'size' ) ); ?>" class="widefat">
					<?php
						$post_type_choices = array(
							'thumbnail' => esc_html__( 'Thumbnail', 'personify-pro' ),
							'small'     => esc_html__( 'Small', 'personify-pro' ),
							'large'     => esc_html__( 'Large', 'personify-pro' ),
							'original'  => esc_html__( 'Original', 'personify-pro' ),
						);

					foreach ( $post_type_choices as $key => $value ) {
						echo '<option value="' . esc_attr( $key ) . '" '. selected( $key, $instance['size'], false ) .'>' . esc_html( $value ) .'</option>';
					}
					?>
				</select>
			</p>

			 <p>
	        	<input class="checkbox" type="checkbox" <?php checked( $instance['target'], true ) ?> id="<?php echo esc_attr( $this->get_field_id( 'target' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'target' ) ); ?>" />
	        	<label for="<?php echo esc_attr( $this->get_field_id('target' ) ); ?>"><?php esc_html_e( 'Check to Open Link in new Tab/Window', 'personify-pro' ); ?></label><br />
	        </p>

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'link_text' ) ); ?>"><?php esc_html_e( 'Link text', 'personify-pro' ); ?>:
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'link_text' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'link_text' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['link_text'] ); ?>" /></label></p>
			<?php

		}

		function update( $new_instance, $old_instance ) {
			$instance = $old_instance;

			$instance['title']    = sanitize_text_field( $new_instance['title'] );
			$instance['username'] = sanitize_text_field( $new_instance['username'] );
			$instance['layout']   = sanitize_key( $new_instance['layout'] );
			$instance['number']   = absint( $new_instance['number'] );
			$instance['size']     = sanitize_key( $new_instance['size'] );
			$instance['target']   = personify_pro_sanitize_checkbox( $new_instance['target'] );
			$instance['link_text']     = sanitize_text_field( $new_instance['link_text'] );

			return $instance;
		}

		function widget( $args, $instance ) {
			// Merge with defaults
			$instance = wp_parse_args( (array) $instance, $this->defaults );

			echo $args['before_widget'];

			// Set up the author bio
			if ( ! empty( $instance['title'] ) ) {
				echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];
			}

			$username = empty( $instance['username'] ) ? '' : $instance['username'];
			$number   = empty( $instance['number'] ) ? 9 : $instance['number'];
			$size     = empty( $instance['size'] ) ? 'large' : $instance['size'];
			$link_text     = empty( $instance['link_text'] ) ? '' : $instance['link_text'];

			$target = '_self';


			if ( $instance['target'] ) {
				$target = '_blank';
			}

			if ( '' != $username ) {

				$media_array = $this->scrape_instagram( $username, $number );

				if ( is_wp_error( $media_array ) ) {

					echo wp_kses_post( $media_array->get_error_message() );

				}
				else {
					?>

					<ul class="<?php echo esc_attr( $instance['layout'] ); ?>">
					<?php
						foreach ( $media_array['data'] as $item ) {
							echo '
							<li class="hentry">
								<a href="'. esc_url( $item['link'] ) .'" target="'. esc_attr( $target ) .'">
									<img src="'. esc_url( $item[$size] ) .'"  alt="'. esc_attr( $item['description'] ) .'" title="'. esc_attr( $item['description'] ).'"/>
								</a>
							</li>';
						}
					?>
					</ul>
				<?php
				}
			}

			$linkclass = apply_filters( 'personify_pro_link_class', 'clear' );

			if ( '' != $link_text ) {
				?>
				<p class="<?php echo esc_attr( $linkclass ); ?>">
					<a class="genericon genericon-instagram" href="//instagram.com/<?php echo esc_attr( trim( $media_array['meta']['username'] ) ); ?>" rel="me" target="<?php echo esc_attr( $target ); ?>"><span><?php echo esc_html( $link_text ); ?></span></a>
				</p>
				<?php
			}

			echo $args['after_widget'];
		}

		// based on https://gist.github.com/cosmocatalano/4544576
		function scrape_instagram( $username, $slice = 9 ) {

			$username = trim( strtolower( $username ) );
            $transient_prefix = 'tp';


            if ( false === ( $instagram = get_transient( 'insta-a3-' . $transient_prefix . '-' . sanitize_title_with_dashes( $username ) ) ) ) {

                $remote =  wp_remote_get( "https://api.instagram.com/v1/users/self/media/recent/?access_token=". $username );

                if ( is_wp_error( $remote ) ) {
                    return new WP_Error( 'site_down', esc_html__( 'Unable to communicate with Instagram.', 'personify-pro' ) );
                }

                if ( 200 !== wp_remote_retrieve_response_code( $remote ) ) {
                    return new WP_Error( 'invalid_response', esc_html__( 'Instagram did not return a 200.', 'personify-pro' ) );
                }

                $insta_array = json_decode( $remote['body'] );
                $insta_data = $insta_array->data;

                $instagram = array();
                $instagram['data'] = array();
                $instagram['meta'] = array();
                

                $instagram['meta']['username'] = $insta_data[0]->user->username;
                $instagram['meta']['full_name'] = $insta_data[0]->user->full_name;
                $instagram['meta']['proifle_pic_url'] = $insta_data[0]->user->profile_picture;

                foreach ( $insta_data as $insta ) :
                    $instagram['data'][] = array(
                        'description'   => ! empty( $insta->caption->text ) ? $insta->caption->text : '',
                        'link'          => $insta->link,
                        'time'          => $insta->created_time,
                        'comments'      => $insta->comments,
                        'likes'         => $insta->likes->count,
                        'thumbnail'     => $insta->images->thumbnail->url,
                        'small'         => $insta->images->low_resolution->url,
                        'large'         => $insta->images->standard_resolution->url,
                        'type'          => $insta->type,
                    );
                endforeach; // End foreach().

                // do not set an empty transient - should help catch private or empty accounts.
                if ( ! empty( $instagram ) ) {

                    set_transient( 'insta-a3-' . $transient_prefix . '-' . sanitize_title_with_dashes( $username ), $instagram, apply_filters( 'personify_pro_instagram_cache_time', HOUR_IN_SECONDS * 2 ) );
                }
            }
            if ( ! empty( $instagram ) ) {

                $instagram['data'] = array_slice( $instagram['data'], 0, $slice );
                return $instagram;

            } else {

                return new WP_Error( 'no_images', esc_html__( 'Instagram did not return any images.', 'personify-pro' ) );

            }
		}
	}
endif;
