<?php

namespace Clevercherry\Backslash4\Services;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use App\Models\Setting;
use Illuminate\Support\Facades\File;

class Instagram {

	/**
	 * Instagram Basic Display Client Id
	 * @var [string]
	 */
	private $clientId;

	/**
	 * Instagram Basic Display Client Secret
	 * @var [string]
	 */
	private $clientSecret;
	
	function __construct() {
		// old codes
		//$this->clientId = '199195144861026';
		//$this->clientSecret = '06b4b43e3d77452e392b08aeda374d88';

		// code on site Jorrel??
		//$this->clientId = '1456280691556678';
		//$this->clientSecret = '4695c40cf03bfebed7a2d62b2272f7f4';

		//from facebook app - Instagram Basic Display
		$this->clientId = Setting::getSetting('instagram_client_id','');  //'671103913875112';
		$this->clientSecret = Setting::getSetting('instagram_secret',''); //'28ce4a4cdf47e3a16226eb733abd05f7';
	}

	/**
	 * Get URL
	 */
	public static function getUrl($clientId=null) {

        if(empty($clientId))
            $clientId = Setting::getSetting('instagram_client_id','');  //'671103913875112';
		
		return "https://api.instagram.com/oauth/authorize?client_id=". $clientId 
             . "&redirect_uri=". route('apis.instagram.response') ."&scope=user_profile,user_media&response_type=code";
	}

	/**
	 * Get Short lived access token 
	 * @param  string $code [authorization code]
	 */
	public function getAccessTokenAndUserId($code = '') {

		$curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://api.instagram.com/oauth/access_token",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_SSL_VERIFYPEER => 0,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => array(
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code' => $code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => route('apis.instagram.response') )
        ));
        
        $response = json_decode(curl_exec($curl),true);
        curl_close($curl);

        $this->shortToLongLivedToken($response['access_token']);

        return true;
	}

	/**
	 * Exchange short lived token for a long lived one
	 * @param  string $shortToken 
	 */
	public function shortToLongLivedToken($shortToken) { 

  		$exchangeUrl = "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=".$this->clientSecret."&access_token=" . $shortToken;

		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $exchangeUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        $output = json_decode($output);
        curl_close($ch);

        // Save long live token to file
        $this->saveTokenToFile($output);

   		return true;
	}

	/**
	 * Check if long live token is close to expiring and refresh if it is
	 */
	public function checkTokenAndRefresh() {

        if(is_file(storage_path('app/instagram/token.txt'))){
            $token = Storage::get('instagram/token.txt');
            $token = json_decode($token);
            if(strtotime($token->date) + 604800 >= strtotime('now')){
				return $token->token;
			} elseif (strtotime($token->date) + $token->expires_in <= strtotime('now')) {
				// they need to reuthenticate 
			}
        	return $this->newToken($token->token);
        } 

        //error 
	}

	/**
	 * Refresh long lived token
	 * @param  [type] $access_token
	 */
	public function newToken($access_token) {
		$refreshUrl = "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=". $access_token;

		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $refreshUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $output = curl_exec($ch);
        $output = json_decode($output);
        curl_close($ch);

        $this->saveTokenToFile($output);
        return $output->access_token;
	}

	/**
	 * Save long lived token to file
	 * @param  [type] $output [curl request long live token response]
	 */
	public function saveTokenToFile($output) {
		try {
            $data = new \stdClass;
            $data->date = date('Y-m-d');

			//if(!isset($output->access_token))
			//	dd($output);

            $data->token = $output->access_token;
            $data->expires_in = $output->expires_in;

            File::ensureDirectoryExists(storage_path('app/instagram/'));
            
            Storage::put('instagram/token.txt', json_encode($data));
            
            return true;

        } catch (Exception $e) {
            \Log::info($e);
        }
	}

	public function getFeed() {
		if(is_file(storage_path('app/instagram/token.txt'))){
            $token = Storage::get('instagram/token.txt');
            $token = json_decode($token);
            $access_token = $this->checkTokenAndRefresh();
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://graph.instagram.com/me/media?fields=id,caption,media_url&access_token=".  $access_token);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $output = curl_exec($ch);
        $output = json_decode($output);

        curl_close($ch);
        return $output;
	}

	public function getFeedNext($nextUrl) {
		if(is_file(storage_path('app/instagram/token.txt'))){
            $token = Storage::get('instagram/token.txt');
            $token = json_decode($token);
            $access_token = $this->checkTokenAndRefresh();
        }

        if(empty($nextUrl)){
           $url = "https://graph.instagram.com/me/media?fields=id,caption,media_url&access_token=".  $access_token;
        } else{
            $url = $nextUrl;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $output = curl_exec($ch);
        $output = json_decode($output);

        curl_close($ch);

        return $output;
	}
}
