<?php 
	header('Access-Control-Allow-Origin: *');
	header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
	error_reporting(E_ALL);
	include_once 'inc/functions.php';
	include 'inc/database.php';

	require_once __DIR__ . '/vendor/autoload.php';
	use Bigcommerce\Api\Client as Bigcommerce;

	if(isset($_REQUEST['store_hash']) && isset($_REQUEST['action']) && $_REQUEST["action"] == "get_wishlist_products"){
		$page = $_REQUEST["page"];
		$hash = $_REQUEST["store_hash"];
		$local_data = json_decode($_POST["localData"], true);
		$request_time = $_REQUEST["request_time"] + 3600;
		if(time() < $request_time){
			$return_result = array(
				"status"=> false,
				"message"=> "use local storage"
			);
			echo json_encode($return_result);
			exit();
		}
		if(empty($local_data)){
			$local_data = array();
		}
		$store_details = $db->select("stores","*" ,array( "store_id" => $hash) );
		if($store_details){
			$store_id		= $store_details['store_id'];
			$access_token	= $store_details['access_token'];		
			$config = array(
				'client_id'  => CLIENT_ID,
				'auth_token' => $access_token,
				'store_hash' => $store_id
			);
			Bigcommerce::configure($config);
			Bigcommerce::verifyPeer(false);
			$url = $API_URL."".$store_id."/v3/wishlists?limit=250&page=".$page;
			$wishlist_resp = getRequest($url, CLIENT_ID, $access_token);
			$products_data = array();
			$return_result = array();
			if($wishlist_resp['data']){
				foreach($wishlist_resp['data'] as $key => $wishlist_data){
					if(!empty($wishlist_data['items'] )){
						foreach($wishlist_data['items'] as $item){
							$id = $item["product_id"];
							if(!$local_data[$id]){
								$url = $API_URL."".$store_id."/v3/catalog/products/".$id;
								$prodcut_data = getRequest($url, CLIENT_ID, $access_token);
								if($prodcut_data['data']){
									$local_data[$id] = 1;
									$prodcut_data 	= $prodcut_data['data'];
									$products_data[$id] = array(
										"id"=> $prodcut_data["id"],
										"name"=> $prodcut_data["name"],
									);
								}
							}
							else{
								$local_data[$id] = $local_data[$id] + 1;
							}
						}
					}
				}
				if(empty($products_data)){
					$products_data = "";
				}
				$return_result = array(
					"status"=> true,
					"data"=> $products_data,
					"localData"=> $local_data,
				);
			}
			else{
				$return_result = array(
					"status"=> false,
					"time"=> time()
				);
			}
			// echo "<hr/>";
			echo json_encode($return_result);
		}
		

	}
?>
