<?php
class Kd_Widget_Flickr extends Kd_Widget {
	public $defaults = array(
		'title' => 'Flickr',
		'flickr_id' => '148222464@N02',
		'number_photo' => '9'
	);

	public function __construct() {
		$widget_ops = array(
			'classname' => 'kd-flickr kd-images',
		);
		parent::__construct('kd_flickr', KD_WIDGET_PREFIX . esc_html__('Flickr', 'kendytheme'), $widget_ops);
	}

	public function form($instance) {
		$instance = array_merge($this->defaults, $instance);

		$this->kd_item_text('title', esc_html__('Title', 'kendytheme'), 'title', $instance['title']);
		$this->kd_item_text('flickr_id', esc_html__('Flickr ID', 'kendytheme'), 'flickr_id', $instance['flickr_id']);
		$this->kd_item_description('Eg: 148222464@N02  <a target="_blank" href="http://www.idgettr.com">Get Flickr ID</a>');
		$this->kd_item_text('number_photo', esc_html__('Number Photo', 'kendytheme'), 'number_photo', $instance['number_photo']);
	}

	public function widget($args, $instance) {
		$error = false;
		$title = apply_filters('widget_title', $instance['title']);

		echo wp_kses_post($args['before_widget']);
		if (!empty($title)) {
			echo wp_kses_post($args['before_title'] . $title . $args['after_title']);
		}
		?>
		<div class="kd-content">
			<?php
			if (!empty($instance['flickr_id']) && !empty($instance['number_photo'])) {
				$api_key = '527717749cea38de23ef84c73acfeef8';
				$url = 'https://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key='.esc_attr($api_key).'&user_id='.esc_attr($instance['flickr_id']) .'&per_page='.esc_attr($instance['number_photo']). '&format=json&nojsoncallback=1';
				$response = wp_remote_get(esc_url_raw($url), array('decompress' => false));
				if (!is_wp_error($response)) {
					$response = wp_remote_retrieve_body($response);
					$response = json_decode($response, true);

					if (!empty($response['photos']['photo'])) {
						foreach ($response['photos']['photo'] as $index => $photo) {
							$size = 'q';
							$link = 'https://www.flickr.com/photos/'. esc_attr($instance['flickr_id']) .'/'. $photo['id'];
							$thumb = 'http://farm'. $photo['farm'] .'.staticflickr.com/'. $photo['server'] .'/'. $photo['id'] .'_'. $photo['secret'] .'_'. $size .'.jpg';
							?>
							<div class="item">
								<a href="<?php echo esc_url($link); ?>" title="<?php esc_html_e('Flickr Feed', 'kendytheme'); ?>">
									<img class="lazy" src="<?php echo esc_url($thumb); ?>" alt="<?php esc_html_e('Flickr Feed', 'kendytheme'); ?>" />
								</a>
							</div>
							<?php
						}
					}
					else {
						$error = true;
					}

				}
				else {
					$error = true;
				}
			}
			else {
				$error = true;
			}

			if ($error) {
				?>
				<p>
					<?php esc_html_e('Please check your flickr settings and try again.', 'kendytheme'); ?>
				</p>
				<?php
			}
			?>
		</div>
		<?php
		echo wp_kses_post($args['after_widget']);
	}
}
add_action('widgets_init', 'kd_register_flickr');
function kd_register_flickr() {
	register_widget('Kd_Widget_Flickr');
}

