<?php

add_action( 'widgets_init', 'latest_tweet_widget' );
function latest_tweet_widget() {
	register_widget( 'Latest_Tweets' );
}
class Latest_Tweets extends WP_Widget {

	function Latest_Tweets() {
		$widget_ops = array( 'classname' => 'twitter-widget'  );
		$control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'latest-tweets-widget' );
		$this->WP_Widget('latest-tweets',__('( LioIT ) Latest Twitts', 'lioit'),$widget_ops);
	}
	
	function widget($args, $instance){
    global $lioit_data;
    extract($args);
    $title = apply_filters('widget_title', $instance['title']);
    $count = $instance['count'];
global $smof_data;
    	$twitter_username 		= $smof_data['twitter_username'];
		$consumer_key 			= $smof_data['twitter_consumer_key'];
		$consumer_secret		= $smof_data['twitter_consumer_secret'];
		$access_token 			= $smof_data['twitter_access_token'];
		$access_token_secret 	= $smof_data['twitter_access_token_secret'];
    echo $before_widget;
    if($title) {
        echo $before_title.'<a href="http://twitter.com/'. $twitter_username .'" target="_blank">'.$title.'</a>'.$after_title;
    }
    if($twitter_username && $consumer_key && $consumer_secret && $access_token && $access_token_secret && $count) {
        $transName = 'list_tweets';
        $cacheTime = 10;
        if(false === ($twitterData = get_transient($transName))) {
            $twitterConnection = new TwitterOAuth(
                $consumer_key,
                $consumer_secret,
                $access_token,
                $access_token_secret
            );
            $twitterData = $twitterConnection->get(
                'statuses/user_timeline',
                    array(
                        'screen_name'     => $twitter_username,
                        'count'           => $count,
                        'exclude_replies' => false
                    )
            );
            if($twitterConnection->http_code != 200){
                $twitterData = get_transient($transName);
            }
            set_transient($transName, $twitterData, 60 * $cacheTime);
        }
        $twitter = get_transient($transName);
        if($twitter && is_array($twitter)) {
        ?>
            <a href="https://twitter.com/<?php echo $twitter_username ?>" class="twitter-follow-button" data-show-count="false" data-size="large">Follow @<?php echo $twitter_username ?></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 class="clear"></div>

            <div class="lioit-twitter-widget" id="tweets_<?php echo $args['widget_id']; ?>">
                <ul class="tweet_list">
                    <?php
                        foreach($twitter as $tweet):
                    ?>
                    <li class="twitter-item">
                        <p class="twitter-text">
                            <i class="icon social_icon-twitter"></i>
                            <?php
                                $latestTweet = $tweet->text;
                                $latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
                                $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
                                echo $latestTweet;
                            ?>
                        </p>
                        <?php
                            $twitterTime = strtotime($tweet->created_at);
                            $timeAgo = $this->ago($twitterTime);
                        ?>
                        <a href="http://twitter.com/<?php echo $tweet->user->screen_name; ?>/statuses/<?php echo $tweet->id_str; ?>" class="jtwt_date"><?php echo $timeAgo; ?></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'] = strip_tags($new_instance['title']);
    $instance['count'] = $new_instance['count'];
    return $instance;
}
function form($instance){
    $defaults = array('title' => __('Recent Tweets' , 'lioit'),'count' => 4);
    $instance = wp_parse_args((array) $instance, $defaults);
    ?>
    <p style="color: #e94b35;">
        <?php _e('Make sure you Setup Twitter API OAuth settings under Theme Options > Social tab .','lioit') ?>
    <p>
        <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','lioit') ?></label>
        <input style="width: 216px;" 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('count'); ?>"><?php _e('Number of Tweets:','lioit') ?></label>
        <input style="width: 216px;" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>" value="<?php echo $instance['count']; ?>" />
    </p>
<?php
}

}
?>