<?php

require_once '../vendor/autoload.php';
use OAuth\Client;

$client = new Etsy\OAuth\Client('b7re5rwr6of8w9j2jboi3ryx');

require("etsyDBConfig.php");
if(!isset($_GET['state']) || strlen($_GET['state']) < 1){
    die("Unauthorized Access!");
}

$sbkey = trim($_GET['state']);

        [$verifier, $code_challenge] = $client->generateChallengeCode();
        $nonce = $client->createNonce();
        $scopes = ["listings_d", "listings_r", "listings_w", "profile_r"];
        
        if(isset($_GET['code'])){
            [$access_token, $refresh_token] = $client->requestAccessToken(
              'https://apps.infoshore.biz/bigcom/etsyimport/cp/etsyv3/src/example.php',
              $_GET['code'],
              $verifier
            );
            echo "access token : ".$access_token;echo "<br>";echo "refresh token : ".$refresh_token;
            
            $header = array("Authorization: Bearer ".$access_token,"x-api-key: b7re5rwr6of8w9j2jboi3ryx");
            $user = explode(".",$access_token);
        	$curl = curl_init();
        	curl_setopt_array($curl, array(
        		CURLOPT_URL => 'https://openapi.etsy.com/v3/application/users/'.$user[0].'/shops',
        		CURLOPT_HTTPHEADER => $header,
        		CURLOPT_SSL_VERIFYPEER => false,
        		CURLOPT_RETURNTRANSFER => true
        	));
        	$response = curl_exec($curl);
        	curl_close($curl);	
	        $shopResult = json_decode($response);
	        
	        $shop_id = '';
	        if($shopResult != ""){
	            if(isset($shopResult->shop_id)){
	               $shop_id = $shopResult->shop_id;
	            }
	        }
	        
            $result = $connection->query("select * from users where id = ".$sbkey);
			if($result->num_rows < 1){
				die("Unauthorized access!");
			}
			$row = $result->fetch_assoc();
			$tempcode = $row['tempcode'];
			$etsyresult = $connection->query("select id from etsy_keys where user_id = ".$sbkey);
			if($etsyresult->num_rows > 0){
				$etsyrow = $etsyresult->fetch_assoc();
				$connection->query("update etsy_keys set shop_id= '".mysqli_real_escape_string($connection, $shop_id)."',access_token = '".mysqli_real_escape_string($connection, $access_token)."',refresh_token = '".mysqli_real_escape_string($connection, $refresh_token)."', updated_at = now() where user_id = ".$sbkey." and id = ".$etsyrow['id']);
			} else {
				$connection->query("insert into etsy_keys(shop_id, access_token, refresh_token, valid, user_id, created_at, updated_at) values ('".mysqli_real_escape_string($connection, $shop_id)."','".mysqli_real_escape_string($connection, $access_token)."','".mysqli_real_escape_string($connection, $refresh_token)."', 1, '".mysqli_real_escape_string($connection, $sbkey)."', now(), now())");
			}	
			$connection->query("insert into etsy_requests(user_id, status, created_at, updated_at) values(".$sbkey.", 'pending', now(), now())");
			header("Location: https://apps.infoshore.biz/bigcom/etsyimport/cp/#/login/".$tempcode);
				
        }else{
            $url = $client->getAuthorizationUrl(
              'https://apps.infoshore.biz/bigcom/etsyimport/cp/etsyv3/src/example.php',
              $scopes,
              $code_challenge,
              $sbkey
            );
	        header('Location: '.$url);
	    }
	    
/* $etsy = new Etsy('b7re5rwr6of8w9j2jboi3ryx', '92221985.RV_pjL-ko-SGu7w1MDfIxPo5jMAAUbCRi1jPKMzOOvUzjoPfOJ5Yri-DWtf0OeIYMxy06TOxMTFlkc-MOeLSyqV-Hzc');
$user = $etsy->getPublicListings([]);
print_r($user); */