<?php

class Intense_Widget_Twitter extends WP_Widget {

	public function __construct() {
		$widget_options = array( 'classname' => 'tweets', 'description' => __( 'A list of recent tweets', 'intense' ) );
		$control_options = array( 'id_base' => 'tweets-widget' );

		parent::__construct( 'tweets-widget', '(Intense) Twitter', $widget_options, $control_options );
	}

	public function widget( $args, $instance ) {
		extract( $args );

		include_once INTENSE_PLUGIN_FOLDER . '/shortcodes/date/date-shortcode.php';

		$title = apply_filters( 'widget_title', isset( $instance['title'] ) ? $instance['title'] : '' );
		$consumer_key = isset( $instance['consumer_key'] ) ? $instance['consumer_key'] : '';
		$consumer_secret = isset( $instance['consumer_secret'] ) ? $instance['consumer_secret'] : '';
		$access_token = isset( $instance['access_token'] ) ? $instance['access_token'] : '';
		$access_token_secret = isset( $instance['access_token_secret'] ) ? $instance['access_token_secret'] : '';
		$twitter_id = isset( $instance['twitter_id'] ) ? $instance['twitter_id'] : '';
		$count = (int) isset( $instance['count'] ) ? $instance['count'] : 3;
		$show_icon = isset( $instance['show_icon'] ) && $instance['show_icon'] == 'on' ? true : false;
		$show_image = isset( $instance['show_image'] ) && $instance['show_image'] == 'on' ? true : false;
		$show_follow = isset( $instance['show_follow'] ) && $instance['show_follow'] == 'on' ? true : false;
		$widget_id = $args['widget_id'];			

		echo $before_widget;

		if ( $title ) {
			echo $before_title . $title . $after_title;
		}

		if ( $twitter_id && $consumer_key && $consumer_secret && $access_token && $access_token_secret && $count ) {
			$transient_key = 'list_tweets_' . $widget_id;
			$cacheTime = 10;

			if ( false === ( $tweets = get_transient( $transient_key ) ) ) {
				$token = get_option( 'intense_twitter_token_' . $widget_id );
				delete_option( 'intense_twitter_token_' . $widget_id );

				//if we don't have a token, get one
				if( !$token ) {										
					$args = array(
						'method'      => 'POST',
						'httpversion' => '1.1',
						'blocking'    => true,
						'headers'     => array(
							'Authorization' => 'Basic ' . base64_encode( $consumer_key . ':' . $consumer_secret ),
							'Content-Type'  => 'application/x-www-form-urlencoded;charset=UTF-8'
						),
						'body' => array( 
							'grant_type' => 'client_credentials'
						)
					);

					add_filter( 'https_ssl_verify', '__return_false' );
					$response = wp_remote_post( 'https://api.twitter.com/oauth2/token', $args );

					$keys = json_decode( wp_remote_retrieve_body( $response ) );

					// save access token
					if ( $keys ) {						
						update_option( 'intense_twitter_token_' . $widget_id, $keys->access_token );
						$token = $keys->access_token;
					}
				}
				
				$args = array(
					'httpversion' => '1.1',
					'blocking'    => true,
					'headers'     => array( 'Authorization' => "Bearer $token" )
				);

				add_filter( 'https_ssl_verify', '__return_false' );
				$api_url  = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $twitter_id . '&count=' . $count;
				$response = wp_remote_get( $api_url, $args );
				$tweets = wp_remote_retrieve_body( $response );

				set_transient( $transient_key, $tweets, 60 * $cacheTime );
			}

			@$twitter = json_decode( $tweets );


			$GLOBALS['IntensePluginInlineStyle']['widget-twitter'] = "
				.intense.widget-twitter .tweets {
					" . ( !$show_icon && !$show_image ? "padding-left: 0;" : '' ) . "
				}
				.intense.widget-twitter .tweet {
					list-style: none;
				}

				.intense.widget-twitter .tweet-icon, .intense.widget-twitter .tweet-image {
					float: left; 
					margin-left: -43px; 
					margin-top: 3px; 
					width: 38px;
				}

				.intense.widget-twitter .tweet-image {
					" . ( $show_icon && $show_image ? "margin-top: 43px;" : '' ) . "
				}

				.intense.widget-twitter .tweet-text > .tweet-date {
					display: block;
					margin-top: 2px;
				}

				.intense.widget-twitter .tweet-follow {
					margin-bottom: 10px;
				}
			";
			?>

			<?php if ( $twitter && is_array( $twitter ) ) : ?>
				<div id="tweets_<?php echo $widget_id; ?>" class="intense widget-twitter">					
					<ul class="tweets">
						<?php foreach ( $twitter as $tweet ) : ?>							
							<li class="tweet">	

								<?php if ( $show_icon ) : ?>
								<div class="tweet-icon">									
									<?php echo intense_run_shortcode( 'intense_icon', array( 'source' => 'entypo', 'type' => 'twitter', 'width' => '38' ) ); ?>
								</div>
								<?php endif; ?>

								<?php  if ( $show_image ) : ?>
								<div class="tweet-image">	
									<?php echo '<img src="' . $tweet->user->profile_image_url_https . '" />'; ?>
								</div>								
								<?php endif; ?>

								<p class="tweet-text">								
									<?php echo $this->get_tweet_html( $tweet ); ?>
									<a class="tweet-date" href="http://twitter.com/<?php echo $tweet->user->screen_name; ?>/statuses/<?php echo $tweet->id_str; ?>">
										<?php echo Intense_Date::get_relative_time( strtotime( $tweet->created_at ), 1 ); ?>
									</a>
								</p>
							</li>
						<?php endforeach; ?>
					</ul>				
					
					<?php  if ( $show_follow ) : ?>
					<div class="tweet-follow">
						<a href="https://twitter.com/<?php echo $twitter_id; ?>" class="twitter-follow-button" data-show-count="false">Follow @<?php echo $twitter_id; ?></a>
						<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
					</div>
					<?php endif; ?>
					
					<div class="clearfix"></div>
				</div>
			<?php endif;
		}

		echo $after_widget;
	}		

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

		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['twitter_id'] = $new_instance['twitter_id'];
		$instance['consumer_key'] = $new_instance['consumer_key'];
		$instance['consumer_secret'] = $new_instance['consumer_secret'];
		$instance['access_token'] = $new_instance['access_token'];
		$instance['access_token_secret'] = $new_instance['access_token_secret'];		
		$instance['count'] = $new_instance['count'];
		$instance['show_icon'] = $new_instance['show_icon'];
		$instance['show_image'] = $new_instance['show_image'];
		$instance['show_follow'] = $new_instance['show_follow'];

		return $instance;
	}

	public function form( $instance ) {
		$defaults = array(
			'title' => __( 'Recent Tweets', 'intense' ),
			'twitter_id' => '',
			'count' => 3,
			'consumer_key' => '',
			'consumer_secret' => '',
			'access_token' => '',
			'access_token_secret' => '',
			'show_icon' => true,
			'show_image' => false,
			'show_follow' => false
		);

		$instance = wp_parse_args( (array) $instance, $defaults );		

		?>

		<p>
			<a href="http://dev.twitter.com/apps"><?php _e( 'Set up your Twitter App', 'intense' ); ?></a>
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'twitter_id' ); ?>"><?php _e( 'Twitter Username:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'twitter_id' ); ?>" name="<?php echo $this->get_field_name( 'twitter_id' ); ?>" value="<?php echo $instance['twitter_id']; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'consumer_key' ); ?>"><?php _e( 'Consumer Key:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'consumer_key' ); ?>" name="<?php echo $this->get_field_name( 'consumer_key' ); ?>" value="<?php echo $instance['consumer_key']; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'consumer_secret' ); ?>"><?php _e( 'Consumer Secret:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'consumer_secret' ); ?>" name="<?php echo $this->get_field_name( 'consumer_secret' ); ?>" value="<?php echo $instance['consumer_secret']; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'access_token' ); ?>"><?php _e( 'Access Token:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'access_token' ); ?>" name="<?php echo $this->get_field_name( 'access_token' ); ?>" value="<?php echo $instance['access_token']; ?>" />
		</p>
		<p>
			<label for="<?php echo $this->get_field_id( 'access_token_secret' ); ?>"><?php _e( 'Access Token Secret:', 'intense' ); ?></label>
			<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'access_token_secret' ); ?>" name="<?php echo $this->get_field_name( 'access_token_secret' ); ?>" value="<?php echo $instance['access_token_secret']; ?>" />
		</p>		
		<p>
			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Number of tweets to show:', 'intense' ); ?></label>
			<input type="text" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" value="<?php echo $instance['count']; ?>" size="3" />
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $instance['show_icon'], 'on' ); ?> id="<?php echo $this->get_field_id( 'show_icon' ); ?>" name="<?php echo $this->get_field_name( 'show_icon' ); ?>" />
			<label for="<?php echo $this->get_field_id( 'show_icon' ); ?>"><?php _e( 'Show Icon', 'intense' ); ?></label>
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $instance['show_image'], 'on' ); ?> id="<?php echo $this->get_field_id( 'show_image' ); ?>" name="<?php echo $this->get_field_name( 'show_image' ); ?>" />
			<label for="<?php echo $this->get_field_id( 'show_image' ); ?>"><?php _e( 'Show User Image', 'intense' ); ?></label>
		</p>
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $instance['show_follow'], 'on' ); ?> id="<?php echo $this->get_field_id( 'show_follow' ); ?>" name="<?php echo $this->get_field_name( 'show_follow' ); ?>" />
			<label for="<?php echo $this->get_field_id( 'show_follow' ); ?>"><?php _e( 'Show Follow Button', 'intense' ); ?></label>
		</p>

		<?php
	}

	public function get_tweet_html( $tweet, $links = true, $users = true, $hashtags = true ) {
		$return   = $tweet->text;
		$tweets = array();
		$start_index = 0;
		$end_index = 1;

		if ( $links && is_array( $tweet->entities->urls ) ) {
			foreach ( $tweet->entities->urls as $url ) {
				$temp['start'] = $url->indices[ $start_index ];
				$temp['end'] = $url->indices[ $end_index ];
				$temp['replacement'] = '<a href="' . $url->expanded_url . '" target="_blank">' . $url->display_url . '</a>';
				$tweets[] = $temp;
			}
		}

		if ( $users && is_array( $tweet->entities->user_mentions ) ) {
			foreach ( $tweet->entities->user_mentions as $mention ) {
				$temp['start'] = $mention->indices[ $start_index ];
				$temp['end'] = $mention->indices[ $end_index ];
				$temp['replacement'] = '<a href="https://twitter.com/' . $mention->screen_name . '" target="_blank">@' . $mention->screen_name . '</a>';
				$tweets[] = $temp;
			}
		}

		if ( $hashtags && is_array( $tweet->entities->hashtags ) ) {
			foreach ( $tweet->entities->hashtags as $hashtag ) {
				$temp['start'] = $hashtag->indices[ $start_index ];
				$temp['end'] = $hashtag->indices[ $end_index ];
				$temp['replacement'] = '<a href="https://twitter.com/hashtag/' . $hashtag->text . '?src=hash" target="_blank">#' . $hashtag->text . '</a>';
				$tweets[] = $temp;
			}
		}

		usort( $tweets, array( $this, 'sort_tweets' ) );

		foreach ( $tweets as $item ) {
			$return = substr_replace( $return, $item['replacement'], $item['start'], $item['end'] - $item['start'] );
		}

		return $return;
	}

	public function sort_tweets( $a, $b ) { 
		return ( $b['start'] - $a['start'] ); 
	}
}
