<?php

/**********Instagram Widget**********/
class Pointify_Instagram_Widget extends WP_Widget {
    public function __construct() {
        parent::__construct(
            'pointify_instagram_widget',
            'Pointify Instagram',
            array('description' => 'A custom widget for displaying Instagram images.', 'pointify')
        );
    }

    public function widget($args, $instance) {
        $instagram_title = isset($instance['instagram_title']) ? $instance['instagram_title'] : '';
        $access_token = isset($instance['access_token']) ? $instance['access_token'] : '';
        $num_images = isset($instance['num_images']) ? absint($instance['num_images']) :'';
        echo $args['before_widget'];
		?><div class="pointify_instagram_widget"><?php
			if(!empty($instagram_title)){ ?>
				<div class="instagram_title">
					<h2 class="widget-title"><?php echo $instagram_title; ?></h2>
				</div><?php
			}
			
			if (!empty($access_token)) {
				// Use the Instagram API to fetch images based on the access token
				$instagram_data = $this->get_instagram_images($access_token, $num_images);
				// Display the images
				if ($instagram_data && !empty($instagram_data->data)) {
					echo '<ul>';
					$insta_image_number=1;
					foreach ($instagram_data->data as $image){
						if(strtolower($image->media_type) == 'image'){
							if($insta_image_number <= $num_images ){
								echo '<li><a target="_blank" href="' . esc_url($image->media_url) .'" title="'. esc_attr( 'Instagram', 'pointify') .'"><img src="' . esc_url($image->media_url) .'" alt="'. esc_attr( 'Instagram', 'pointify') .'"></a></li>';
								$insta_image_number++;
							}
						}
					}
					echo '</ul>';
				} else {
					echo '<p>No images found.</p>';
				}
			} else {
				echo '<p>Please enter a valid access token in the widget settings.</p>';
			}
		?></div><?php
        echo $args['after_widget'];
    }

    public function form($instance) {
        $instagram_title = isset($instance['instagram_title']) ? $instance['instagram_title'] : 'Instagram';
        $access_token = isset($instance['access_token']) ? $instance['access_token'] : '';
        $num_images = isset($instance['num_images']) ? absint($instance['num_images']) : 8;
        ?>
		
		 <p>
            <label for="<?php echo $this->get_field_id('instagram_title'); ?>">Instagram Title:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('instagram_title'); ?>" name="<?php echo $this->get_field_name('instagram_title'); ?>" type="text" value="<?php echo esc_attr($instagram_title); ?>">
        </p>
		
        <p style="margin-bottom: 0;">
            <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'); ?>" type="text" value="<?php echo esc_attr($access_token); ?>">
			<p style="margin-top: 0;"><?php _e( "To generate Instagram access token", 'pointify' ); ?> <a href="<?php echo esc_url( __( 'https://docs.oceanwp.org/article/487-how-to-get-instagram-access-token', 'pointify' ) ); ?> " target = "_blank"><?php printf( __( '%s', 'pointify' ), 'Click here' ); ?> </a>
            </p>
        </p>

        <p>
            <label for="<?php echo $this->get_field_id('num_images'); ?>">Number of Images to Show:</label>
            <input class="widefat" id="<?php echo $this->get_field_id('num_images'); ?>" name="<?php echo $this->get_field_name('num_images'); ?>" type="number" min="1" max="12" value="<?php echo esc_attr($num_images); ?>">
        </p>

        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['instagram_title'] = sanitize_text_field($new_instance['instagram_title']);
        $instance['access_token'] = sanitize_text_field($new_instance['access_token']);
        $instance['num_images'] = absint($new_instance['num_images']);

        return $instance;
    }

    private function get_instagram_images($access_token, $num_images) {
        $api_url = 'https://graph.instagram.com/me/media/?fields=id,username,media,media_url,media_type&access_token=' . $access_token . '&count=' . $num_images;

        $response = wp_remote_get($api_url);

        if (!is_wp_error($response)) {
            return json_decode(wp_remote_retrieve_body($response));
        }

        return false;
    }
}

function register_pointify_instagram_widget() {
    register_widget('Pointify_Instagram_Widget');
}
add_action('widgets_init', 'register_pointify_instagram_widget');