<?php
/* Class To integrate google api product listing ads*/

class Googleapi 
{
	public $ObjClient;
	public $ObjException;
	public $ObjService;
	public $config;
	public $authorizeUrl;

    public function  __construct($clientID,$clientSecret,$merchantID,$applicationName,$redirectUri,$loginHint)
    {
		
        $this->setGoogleapi();
		$this->ObjClient = new Google_Client();
		$this->setAPIKey($clientID,$clientSecret,$applicationName,$redirectUri,$loginHint);
		$this->merchant_id = $merchantID;
		$this->ObjService = new Google_Service_ShoppingContent($this->ObjClient);
	}
	
	/* Including google api */
	public function setGoogleapi()
    {
		$googleapi_class_file = __LIBRARY_PATH.'/googleapi/src/Google/Client.php';
		$googleapi_service_file = __LIBRARY_PATH.'/googleapi/src/Google/Service/ShoppingContent.php';
		if(file_exists($googleapi_class_file)) 
		{ 
            require_once($googleapi_class_file);
        } 
		else 
		{
            return false;
        }	
		
		if(file_exists($googleapi_service_file)) 
		{ 
            require_once($googleapi_class_file);
        } 
		else 
		{
            return false;
        }	
	}
	
	/* Define API Key */
	public function setAPIKey($clientID,$clientSecret,$applicationName,$redirectUri,$loginHint)
	{
		$this->ObjClient->setApplicationName($applicationName);
		//$this->ObjClient->setDeveloperKey(API_KEY);
		$this->ObjClient->setClientId($clientID);
		$this->ObjClient->setClientSecret($clientSecret);
		$this->ObjClient->setRedirectUri($redirectUri);
		$this->ObjClient->setScopes('https://www.googleapis.com/auth/content');
		$this->ObjClient->setAccessType('offline'); // So that we get a refresh token
		$this->ObjClient->setApprovalPrompt('force');
		$this->ObjClient->setLoginHint($loginHint);
	}
	
	public function refreshToken($dbToken)
	{
		$refreshToken	= $this->ObjClient->refreshToken($dbToken);
		return $refreshToken;
	}
	
	public function callException()
	{
		$this->ObjException = new Google_Auth_Exception();
		return $this->ObjException;
	}
	
	public function getAuthUrl()
	{
		$this->authorizeUrl = $this->ObjClient->createAuthUrl();
		return $this->authorizeUrl;
	}
	
	public function getRefreshToken($code) 
	{
		$result	= $this->ObjClient->authenticate($code);
		$token = $this->ObjClient->getAccessToken();
		$decoded_token = json_decode($token);
		return $decoded_token->refresh_token;
	}
	

	// Retry a function with back off
	protected function retry($function, $parameter, $max_attempts = 5) 
	{
		$attempts = 1;

		while ($attempts <= $max_attempts) 
		{
		  try {
			return call_user_func(array($this, $function), $parameter);
		  } catch (Google_Service_Exception $exception) {
			sleep($attempts * $attempts);
			$attempts++;
		  }
		}
	}
	/* List Data Feeds */
	public function listDatafeeds() 
	{
		// There is a low limit on the number of datafeeds per account, so the list
		// method always returns all datafeeds.
		$datafeeds = $this->ObjService->datafeeds->listDatafeeds($this->merchant_id);
		return $datafeeds;
	}
	/* List Feed Status */
	public function listDatafeedStatus() 
	{
		// There is a low limit on the number of datafeeds per account, so the list
		// method always returns all datafeeds.
		$datafeedsStatus = $this->ObjService->datafeedstatuses->listDatafeedstatuses($this->merchant_id);
		return $datafeedsStatus;
	}
	/* List Active Products */
	public function listProducts() 
	{
		// There is a low limit on the number of datafeeds per account, so the list
		// method always returns all datafeeds.
		$products = $this->ObjService->products->listProducts($this->merchant_id);
		return $products;
	}
	/* List Product Status */
	public function listProductStatus() 
	{
		// There is a low limit on the number of datafeeds per account, so the list
		// method always returns all datafeeds.
		$productStatus = $this->ObjService->productstatuses->listProductstatuses($this->merchant_id);
		return $productStatus;
	}
	
	/* Set authorization token */
	public function addDataFeed($POST)
	{	
		$example_datafeed		= $this->insertDatafeed($this->createExampleDatafeed($POST));
		$example_datafeed_id	= $example_datafeed->getId();
		return $example_datafeed_id; 
	}
	
	public function insertDatafeed(Google_Service_ShoppingContent_Datafeed $datafeed) 
	{
		$response = $this->ObjService->datafeeds->insert($this->merchant_id, $datafeed);
		printf("Datafeed created with ID %d\n", $response->getId());
		return $response;
	}
  
	private function createExampleDatafeed($POST) 
	{
		$datafeed = new Google_Service_ShoppingContent_Datafeed();

		// The file name must unique per account, so we add a unique part to avoid
		// clashing with any existing feeds.
		$filename = str_replace(' ', '', $POST['feedTitile']);

		$datafeed->setName($POST['feedTitile']);
		$datafeed->setContentType($POST['feedType']);
		$datafeed->setAttributeLanguage($POST['feedAttrLn']);
		$datafeed->setContentLanguage($POST['feedContLn']);
		$datafeed->setIntendedDestinations(array('Shopping'));
		$datafeed->setFileName($filename . '.txt');
		$datafeed->setTargetCountry($POST['countryIsoA2']);

		$fetch_schedule =
			new Google_Service_ShoppingContent_DatafeedFetchSchedule();
		if($POST['feedShed']=='Monthly')
		{
			$fetch_schedule->setDayOfMonth($POST['feedShedDate']);
			$fetch_schedule->setHour($POST['feedShedTime']);
		}
		else if($POST['feedShed']=='Weekly')
		{
			$fetch_schedule->setWeekday($POST['feedShedDay']);
			$fetch_schedule->setHour($POST['feedShedTime']);
		}
		else if($POST['feedShed']=='Daily')
		{
			$fetch_schedule->setHour($POST['feedShedTime']);
		}

		$fetch_schedule->setTimeZone($POST['timeZoneDetail']);
		$fetch_schedule->setFetchUrl($POST['feedURL'].$filename.'.txt');
		$fetch_schedule->setUsername($POST['feedUsername']);
		$fetch_schedule->setPassword($POST['feedPassword']);

		$format = new Google_Service_ShoppingContent_DatafeedFormat();
		$format->setFileEncoding('utf-8');
		$format->setColumnDelimiter('tab');
		$format->setQuotingMode('value quoting');

		$datafeed->setFetchSchedule($fetch_schedule);
		$datafeed->setFormat($format);
		return $datafeed;
	}
	
	/* Get Data Feed */
	public function getDatafeed($datafeed_id) 
	{
		$datafeed 		= $this->ObjService->datafeeds->get($this->merchant_id, $datafeed_id);
		return $fetchResult	= $this->getDataSchedule($datafeed);
	}
	
	/* Get Data schedule */
	public function getDataSchedule(Google_Service_ShoppingContent_Datafeed $datafeed) 
	{
		// Getting scheduled fetch time
		return $original = $datafeed->getFetchSchedule();	
	}
	
	public function updatefeed($POST) 
	{
		$datafeed 		= $this->ObjService->datafeeds->get($this->merchant_id, $POST['feedID']);
		return $updateResult	= $this->updateDatafeed($POST,$datafeed);
	}
	
	/* Update Data feed */
	public function updateDatafeed($POST,Google_Service_ShoppingContent_Datafeed $datafeed) 
	{	
		// Changing the scheduled fetch time
		if($POST['feedShed']=='Monthly')
		{
			$datafeed->getFetchSchedule()->setDayOfMonth($POST['feedShedDate']);
			$datafeed->getFetchSchedule()->setHour($POST['feedShedTime']);
		}
		else if($POST['feedShed']=='Weekly')
		{
			$datafeed->getFetchSchedule()->setWeekday($POST['feedShedDay']);
			$datafeed->getFetchSchedule()->setHour($POST['feedShedTime']);
		}
		else if($POST['feedShed']=='Daily')
		{
			$datafeed->getFetchSchedule()->setHour($POST['feedShedTime']);
		}
		$datafeed->getFetchSchedule()->setTimeZone($POST['timeZoneDetail']);
		$datafeed->getFetchSchedule()->setFetchUrl($POST['feedURL']);
		$datafeed->getFetchSchedule()->setUsername($POST['feedUsername']);
		$datafeed->getFetchSchedule()->setPassword($POST['feedPassword']);

		return $response = $this->ObjService->datafeeds->update($this->merchant_id, $datafeed->getId(), $datafeed);
	}
	
	/* Delete data feed */
	public function deleteDatafeed($datafeed_id) 
	{
		// The response for a successful delete is empty
		return $this->ObjService->datafeeds->delete($this->merchant_id, $datafeed_id);

	}
	
	/* Get Data Feed Errors */
	public function getfeedErrors($datafeed_id) 
	{
		$feedstatus 		= $this->ObjService->datafeedstatuses->get($this->merchant_id, $datafeed_id);
		return $fetchResult	= $this->feedErrors($feedstatus);
	}
	
	/* Get Feed Errors */
	public function feedErrors(Google_Service_ShoppingContent_DatafeedStatus $feedstatus) 
	{
		// Getting errors
		return $original = $feedstatus->getErrors();	
	}
	
	/* Get Data Feed Errors */
	public function getfeedWarnings($datafeed_id) 
	{
		$feedWarn 		= $this->ObjService->datafeedstatuses->get($this->merchant_id, $datafeed_id);
		return $warnings	= $this->feedWarnings($feedWarn);
	}
	
	/* Get Feed Warnings */
	public function feedWarnings(Google_Service_ShoppingContent_DatafeedStatus $feedWarn) 
	{
		// Getting errors
		return $fwarnings = $feedWarn->getWarnings();	
	}
		
	/* Get Data Feed Name*/
	public function getDatafeedTitle($datafeed_id) 
	{
		$datafeed 		= $this->ObjService->datafeeds->get($this->merchant_id, $datafeed_id);
		return $fetchResult	= $this->getFeedName($datafeed);
	}
	
	/* Get Feed Name */
	public function getFeedName(Google_Service_ShoppingContent_Datafeed $datafeed) 
	{
		// Getting Name
		return $original = $datafeed->getName();	
	}
	
	/* Get Data Feed Target Country*/
	public function getfeedTgCountry($datafeed_id) 
	{
		$datafeed 		= $this->ObjService->datafeeds->get($this->merchant_id, $datafeed_id);
		return $countryResult	= $this->getTgCountry($datafeed);
	}
	
	/* Get Data Target Country */
	public function getTgCountry(Google_Service_ShoppingContent_Datafeed $datafeed) 
	{
		// Getting Name
		return $country = $datafeed->getTargetCountry();	
	}
	
	/* Delete Product */
	public function deleteProduct($product_id) 
	{
		// The response for a successful delete is empty
		return $this->ObjService->products->delete($this->merchant_id, $product_id);

	}
}