<?php

namespace ElementsKit;

use ElementsKit\Libs\Framework\Attr;

class Elementskit_Widget_Instagram_Feed_Handler extends Core\Handler_Widget
{

    protected static $transient_name = 'ekit_instagram_feeds';

    public function wp_init()
    {
        include(self::get_dir() . 'classes/settings.php');
    }

    static function get_name()
    {
        return 'elementskit-instagram-feed';
    }

    static function get_title()
    {
        return esc_html__('Instagram Feed', 'elementskit');
    }

    static function get_icon()
    {
        return 'ekit ekit-instagram ekit-widget-icon ';
    }

    static function get_categories()
    {
        return ['elementskit'];
    }

    static function get_dir()
    {
        return \ElementsKit::widget_dir() . 'instagram-feed/';
    }

    static function get_url()
    {
        return \ElementsKit::widget_url() . 'instagram-feed/';
    }

    static function get_data()
    {
        $data = Attr::instance()->utils->get_option('user_data', []);

        $user_id = (isset($data['instragram']) && !empty($data['instragram']['user_id'])) ? $data['instragram']['user_id'] : '';

        $token = (isset($data['instragram']) && !empty($data['instragram']['token'])) ? $data['instragram']['token'] : '';

        $username = (isset($data['instragram']) && !empty($data['instragram']['username'])) ? $data['instragram']['username'] : '';

        return [
            'user_id' => $user_id,
            'token' => $token,
            'username' => $username
        ];
    }

    static function get_instagram_feed()
    {
        $transient_name = self::$transient_name;
        $transient_value = get_transient($transient_name);

        if (false !== $transient_value) {
            return $transient_value;
        } else {

            $user_name = self::get_data()['username'];
            $request = wp_remote_get('https://www.instagram.com/' . $user_name . '/?__a=1');

            if (is_wp_error($request)) {
                return false;
            }

            $body = wp_remote_retrieve_body($request);
            $data = json_decode($body);
            $result = $data->graphql->user;

            $expiration_time = 86400;//in second
            set_transient($transient_name, $result, $expiration_time);
            return $result;
        }

    }

    static function reset_cache()
    {
        delete_transient(self::$transient_name);
    }

}