<?php

class Leap_Tweets_Widget extends WP_Widget {

	function __construct() {
		$widget_ops = array( 'classname' => 'tweets', 'description' => '' );

		$control_ops = array( 'id_base' => 'tweets-widget' );

		parent::__construct( 'tweets-widget', 'LEAP: Recent Tweets', $widget_ops, $control_ops );
	}

	/**
	 * Get user tweets
	 * https://dev.twitter.com/rest/reference/get/statuses/user_timeline
	 * @param string $consumerKey
	 * @param string $consumerSecret
	 * @param string $screenName
	 */
	function get_tweetes( $consumerKey, $consumerSecret, $screenName, $count ) {

		$token	 = get_theme_mod( 'twitter_token_' . $this->id, array() );
		$tweets	 = get_transient( 'leap_tweets_' . $this->id );

		if ( false === $tweets ) {
			if ( !$token ) {
				$credentials = $consumerKey . ':' . $consumerSecret;
				$toSend		 = base64_encode( $credentials );

				// http post arguments
				$args		 = array(
					'method'		 => 'POST',
					'httpversion'	 => '1.1',
					'blocking'		 => true,
					'headers'		 => array(
						'Authorization'	 => 'Basic ' . $toSend,
						'Content-Type'	 => 'application/x-www-form-urlencoded;charset=UTF-8'
					),
					'body'			 => array( 'grant_type' => 'client_credentials' )
				);
				$response	 = wp_remote_post( 'https://api.twitter.com/oauth2/token', $args );

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

				if ( $keys ) {
					$token = $keys->access_token;
					set_theme_mod( 'twitter_token_' . $this->id, $token );
				}
			}

			// we have bearer token wether we obtained it from API or from options
			$args		 = array(
				'httpversion'	 => '1.1',
				'blocking'		 => true,
				'headers'		 => array(
					'Authorization' => "Bearer $token"
				)
			);
			$api_url	 = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=$screenName&count=$count";
			$response	 = wp_remote_get( $api_url, $args );

			if ( !is_wp_error( $response ) ) {
				$tweets_data = json_decode( wp_remote_retrieve_body( $response ), true );

				$tweets = array();
				if ( empty( $tweets_data[ 'errors' ] ) && is_array( $tweets_data ) ) {
					foreach ( $tweets_data as $tweet ) {
						$tweets[] = array(
							'id'		 => $tweet[ 'id' ],
							'created_at' => $tweet[ 'created_at' ],
							'text'		 => $tweet[ 'text' ]
						);
					}
				}
			} else {
				$tweets = get_theme_mod( 'twitter_tweets_' . $this->id, array() );
			}

			// cache for an hour
			set_transient( 'leap_tweets_' . $this->id, $tweets, HOUR_IN_SECONDS );
			set_theme_mod( 'twitter_tweets_' . $this->id, $tweets );
		}
		
		return $tweets;
	}

	function widget( $args, $instance ) {
		extract( $args );
		
		$defaults	 = array( 'title' => 'Recent Tweets', 'twitter_id' => '', 'count' => 3, 'consumer_key' => '', 'consumer_secret' => '', 'access_token' => '', 'access_token_secret' => '' );
		$instance	 = wp_parse_args( (array) $instance, $defaults );
		
		$title				 = apply_filters( 'widget_title', $instance[ 'title' ], $instance, $this->id_base );
		$twitter_id			 = apply_filters( 'leap_widget_twitter_id', $instance[ 'twitter_id' ], $instance, $this->id_base );
		$count				 = $instance[ 'count' ];
		$consumer_key		 = apply_filters( 'leap_widget_consumer_key', $instance[ 'consumer_key' ], $instance, $this->id_base );
		$consumer_secret	 = apply_filters( 'leap_widget_consumer_secret', $instance[ 'consumer_secret' ], $instance, $this->id_base );
		$access_token		 = apply_filters( 'leap_widget_access_token', $instance[ 'access_token' ], $instance, $this->id_base );
		$access_token_secret = apply_filters( 'leap_widget_access_token_secret', $instance[ 'access_token_secret' ], $instance, $this->id_base );

		echo $before_widget;
		if ( !empty( $title ) ) {
			echo $before_title;
			echo $title;
			echo $after_title;
		}


		if ( $twitter_id && $consumer_key && $consumer_secret && $access_token && $access_token_secret && $count ) {
			
			$tweets = $this->get_tweetes($consumer_key, $consumer_secret, $twitter_id, $count);

			if ( $tweets && is_array( $tweets ) ) {
				//var_dump($twitter);
				?>
				<div class="tweets-container">
					<ul class="tweets-list">
				<?php foreach ( $tweets as $tweet ): ?>
							<li>
								<p><?php echo esc_html( $tweet['text'] ); ?></p>
					<?php
					$twitterTime = strtotime( $tweet['created_at'] );
					$timeAgo	 = $this->ago( $twitterTime );
					?>
								<a target="_blank" href="https://twitter.com/<?php echo $twitter_id; ?>/status/<?php echo $tweet['id']; ?>" class="twt_date"><small class="small"><?php echo $timeAgo; ?></small></a>
							</li>
				<?php endforeach; ?>
					</ul>
				</div>
				<?php
			}
		}

		echo $after_widget;
	}

	function ago( $time ) {
		$periods = array( "second", "minute", "hour", "day", "week", "month", "year", "decade" );
		$lengths = array( "60", "60", "24", "7", "4.35", "12", "10" );

		$now = time();

		$difference	 = $now - $time;
		$tense		 = "ago";

		for ( $j = 0; $difference >= $lengths[ $j ] && $j < count( $lengths ) - 1; $j++ ) {
			$difference /= $lengths[ $j ];
		}

		$difference = round( $difference );

		if ( $difference != 1 ) {
			$periods[ $j ].= "s";
		}

		return $difference . ' ' . $periods[ $j ] . ' ago';
	}

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

		$instance[ 'title' ]				 = sanitize_text_field( $new_instance[ 'title' ] );
		$instance[ 'twitter_id' ]			 = sanitize_text_field($new_instance[ 'twitter_id' ]);
		$instance[ 'count' ]				 = absint($new_instance[ 'count' ]);
		$instance[ 'consumer_key' ]			 = sanitize_text_field($new_instance[ 'consumer_key' ]);
		$instance[ 'consumer_secret' ]		 = sanitize_text_field($new_instance[ 'consumer_secret' ]);
		$instance[ 'access_token' ]			 = sanitize_text_field($new_instance[ 'access_token' ]);
		$instance[ 'access_token_secret' ]	 = sanitize_text_field($new_instance[ 'access_token_secret' ]);
		
		delete_transient( 'leap_tweets_'.$this->id );

		return $instance;
	}

	function form( $instance ) {
		$defaults	 = array( 'title' => 'Recent Tweets', 'twitter_id' => '', 'count' => 3, 'consumer_key' => '', 'consumer_secret' => '', 'access_token' => '', 'access_token_secret' => '' );
		$instance	 = wp_parse_args( (array) $instance, $defaults );
		?>

		<p>You need to create <a href="<?php echo esc_url( 'https://dev.twitter.com/apps' ) ?>" target="_blank">Twitter APP</a> to get this info.</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
			<input class="widefat" 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' ); ?>">Twitter Username:</label>
			<input class="widefat" 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( 'count' ); ?>">Number of Tweets:</label>
			<input class="widefat" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" value="<?php echo $instance[ 'count' ]; ?>" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'consumer_key' ); ?>">Consumer Key:</label>
			<input class="widefat" 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' ); ?>">Consumer Secret:</label>
			<input class="widefat" 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' ); ?>">Access Token:</label>
			<input class="widefat" 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' ); ?>">Access Token Secret:</label>
			<input class="widefat" 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>

		<?php
	}

}

function leap_tweets_load_widgets() {
	register_widget( 'Leap_Tweets_Widget' );
}

add_action( 'widgets_init', 'leap_tweets_load_widgets' );