<?php	
	include_once('constants.inc.php');
	require_once('Firebase/JWT/JWT.php');
	require_once('Firebase/JWT/BeforeValidException.php');
	require_once('Firebase/JWT/ExpiredException.php');
	require_once('Firebase/JWT/SignatureInvalidException.php');
	include_once('class.features.inc.php');
	include_once('class.users.inc.php');
	
	use \Firebase\JWT\JWT;
	/**
	 * Handles Refill Requests to ScriptPro 
	 *
	 * PHP version 5
	 */
	
	class rewards{
		
		private $url = REWARDS_API_URL;
		private $userXref = null;
		private $userPhone = null;
		public $token = "";
		public $idNumber = null;
		public $rewardAmount = null;
		public $responseCode = null;
		public $responseText = null;
		public $transactions = null;
		public $preferredStore = null;
		public $userWallet = null;
		public $firstname = null;
		public $lastname = null;
		public $phone = null;
		public $instoreCredit = null;
		public $instorePoints = null;
		public $errorMsg = "None";
		
		
		public function __construct($userPhone){
			$this->token = $this->getToken();
			$this->userPhone = $userPhone;
			$this->getUserWallet();
		}
		
		private function getToken(){
			$theFile = $this->getCachedFile("rewardsToken");
			
			if(!$theFile){
				$url = $this->url . "/AuthenticationAPI/Identity/ClientAuthenticate?grant_type=client_credentials";
				
				$headers = array(
					'Authorization: Basic ' . base64_encode(REWARDS_ID . ":" . REWARDS_SECRET),
					'Content-Length: ' . 0,
					'Content-Type: application/x-www-form-urlencoded'
				);
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				
				$result=curl_exec($ch);
				
				$information = curl_getinfo($ch);
				
				$token = json_decode($result, true);
				
				curl_close($ch);
				
				
				if(isset($token['access_token'])){
					$cacheFile = $this->getFileName("rewardsToken");
					file_put_contents($cacheFile, $token['access_token']);
					$this->token = $token['access_token'];
					return $token['access_token'];
				}else{
					header("Location: https://" . $_SERVER['SERVER_NAME'] . "/connection-issue");
					die;
				}
			}else{
				$this->token = $theFile;
				return $theFile;
			}
		}
		
		private function getCachedFile($file){
			$cacheFile = $this->getFileName($file);
			
			if(file_exists($cacheFile)){
				return file_get_contents($cacheFile);
			}else{
				return false;
			}
		}
		
		private function getFileName($file){
			$theSiteParts = explode(".", $_SERVER['HTTP_HOST']);
			$theSite = $theSiteParts[0];
			if($theSite == "sso" || $theSite == "new"){
				$theSite = $theSiteParts[1];
			}
			$baseDir = dirname(dirname($_SERVER['DOCUMENT_ROOT']));
			return $baseDir . "/brdata/" . $theSite . "-" . $file . ".php";
		}
		
		public function getUserWallet(){
			if(!isset($_SESSION['userWallet'])){
				$userXRef = $this->getUserXRef($this->userPhone);
				
				if(!is_null($userXRef)){
					//$url = $this->url . "/AFSWalletAPI/Wallets/Open?walletreturnContent=2097410&opendatatype=5&opendata=" . $userXRef;
					$url = $this->url . "/AFSWalletAPI/Wallets/Open?walletreturnContent=2097410&opendatatype=5&opendata=" . $userXRef;
					$authorization = "Authorization: Bearer " . $this->token;
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_HEADER, false);
					curl_setopt($ch, CURLOPT_POST, 0);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					$result=curl_exec($ch);
					
					$walletReturn = json_decode($result, true);
					
					curl_close($ch);					
				}

				if(!isset($walletReturn['Wallet'])){
					$userWallet = [
						'Wallet' => [
							'$Identifications$' => [
								0 =>[
									'XRef' => null,
									'Firstname' => null,
									'LastName' => null,
									'Phone' => null,
									'HomeStorenumber' => null,
									'Error' => "bad xref"
								]
							]
						]
					];
				}else{
					$userWallet = $_SESSION['userWallet'] = $walletReturn;
				}
			}else{
				$userWallet = $_SESSION['userWallet'];
			}
			

			$this->userXref = $userWallet['Wallet']['$Identifications$'][0]['XRef'];
			$this->firstname = $userWallet['Wallet']['$Identifications$'][0]['Firstname'];
			$this->lastname = $userWallet['Wallet']['$Identifications$'][0]['LastName'];
			$this->phone = $userWallet['Wallet']['$Identifications$'][0]['Phone'];
			$this->preferredStore = $userWallet['Wallet']['$Identifications$'][0]['HomeStorenumber'];
			$this->error = isset($userWallet['Wallet']['$Identifications$'][0]['Error']) ? $userWallet['Wallet']['$Identifications$'][0]['Error'] : false;
			
			
			return true;
		}
		
		public function getUserCreditPoints(){
			$userXRef = $this->getUserXRef($this->userPhone);
			
			if(isset($_SESSION['instorePoints']) && isset($_SESSION['instorePoints'])){
				return [$_SESSION['instoreCredit'], $_SESSION['instorePoints'], "No Error"];
			}else{
				if(!is_null($userXRef)){
					$url = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/AccountSummarys";
					$authorization = "Authorization: Bearer " . $this->token;
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_HEADER, false);
					curl_setopt($ch, CURLOPT_POST, 0);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					$result=curl_exec($ch);
					
					$accountReturn = json_decode($result, true);
					
					curl_close($ch);
					
					//echo "<pre>";
					//var_dump($accountReturn);
					//echo "</pre>";
					//exit;
					
					if(isset($accountReturn['ElectronicAccountSummarys']) && count($accountReturn['ElectronicAccountSummarys']) > 0){
						$error = false;
						$instoreCredit = null;
						$instorePoints = null;
						
						foreach($accountReturn['ElectronicAccountSummarys'] as $spendable){
							if($spendable['TenderSubType'] == "InStorePnt"){
								$instorePoints = $spendable;
							}else if($spendable['TenderSubType'] == "InStoreCdt"){
								$instoreCredit = $spendable;
							}
						
						}
						
						$this->instoreCredit = $_SESSION['instoreCredit'] = $instoreCredit;
						$this->instorePoints = $_SESSION['instorePoints'] = $instorePoints;
						
						return [$instoreCredit, $instorePoints, $error];
					}
				}
			}
		}
		
		public function getAccountPromotions(){
			//To-Do: remove these
			// if(isset($_SESSION['rewardsCommonPromotions'])){
			// 	unset($_SESSION['rewardsCommonPromotions']);
			// }
			
			// if(isset($_SESSION['rewardsPersonalPromotions'])){
			// 	unset($_SESSION['rewardsPersonalPromotions']);
			// }
			
			
			if(!isset($_SESSION['rewardsCommonPromotions']) || !isset($_SESSION['rewardsPersonalPromotions'])){
				$userXRef = $this->getUserXRef($this->userPhone);
				
				if(!is_null($userXRef)){
					$url = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/Promotions/Level";
					//$urlCommonPromotions = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/Promotions/Available?storenumber=" . $this->preferredStore;
					$urlCommonPromotions = $this->url . "/AFSWalletAPI/Promotions/Instant?storenumber=" . $this->preferredStore;
					//$urlCommonPromotions = $this->url . "/AFSWalletAPI/Promotions/AvailableSinglePoint?storenumber=" . $this->preferredStore;
					$authorization = "Authorization: Bearer " . $this->token;
					
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_HEADER, false);
					curl_setopt($ch, CURLOPT_POST, 0);
					curl_setopt($ch, CURLINFO_HEADER_OUT, true);
					$result=curl_exec($ch);
					
					$levelPromotionsReturn = json_decode($result, true);
					$information = curl_getinfo($ch);
					curl_close($ch);
					
					$ch2 = curl_init();
					curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
					curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch2, CURLOPT_URL, $urlCommonPromotions);
					curl_setopt($ch2, CURLOPT_HEADER, false);
					curl_setopt($ch2, CURLOPT_POST, 0);
					curl_setopt($ch2, CURLINFO_HEADER_OUT, true);
					$result=curl_exec($ch2);
					
					$commonPromotionsReturn = json_decode($result, true);
					$information2 = curl_getinfo($ch2);
					
					curl_close($ch2);

					$levelPromotions = [];

					if(!isset($commonPromotionsReturn['error']) && isset($commonPromotionsReturn['Promotions']) && count($commonPromotionsReturn['Promotions']) > 0){
						
						$commonPromotions = new stdClass();
						$numSkipped = 0;

						foreach($commonPromotionsReturn['Promotions'] as $key => $promotion){
							if($promotion['LevelFlag'] == "False" && $promotion['SubTypeCode'] != "ALLOCATOR"){
								$commonPromotions->{$key} = new stdClass();
								$commonPromotions->{$key}->id = $promotion['PromotionID'];
								$commonPromotions->{$key}->offer = $promotion['SavingsType'] . " " . $promotion['SavingsMsg'];
								$commonPromotions->{$key}->product = $promotion['Description'];
								$commonPromotions->{$key}->image = $promotion['ImagePath'];
								$commonPromotions->{$key}->description = $promotion['OfferDescription'];
								$commonPromotions->{$key}->expires = date("m/d/Y", strtotime($promotion['ExpirationDate']));
								$commonPromotions->{$key}->expiresSort = date("Ymd", strtotime($promotion['ExpirationDate']));
								$commonPromotions->{$key}->limit = $promotion['LimitMsg'];
								$commonPromotions->{$key}->restrictions = $promotion['Restrictions'];
								$commonPromotions->{$key}->clipped = false;
								
								$commonPromotions->{$key}->shortDesc = strlen($promotion['OfferDescription']) > 100 ? substr($promotion['OfferDescription'], 0, 100) . "..." : $promotion['OfferDescription'];
							}else if($promotion['LevelFlag'] == "True") {
								$levelPromotions[] = $promotion;
							}else {
								$numSkipped++;
								// echo "<pre>";
								// var_dump("Skipped");
								// echo "</pre>";
							}
						}
					}else {
						$commonPromotions =  null;
					}

					if(!isset($levelPromotionsReturn['error']) && isset($levelPromotionsReturn['PersonalPromotions']) && count($levelPromotionsReturn['PersonalPromotions']) > 0){
						if(count($levelPromotions) !== count($levelPromotionsReturn['PersonalPromotions'])){
							foreach($levelPromotionsReturn['PersonalPromotions'] as $userLevelPromotion){
								//$userHasPromotion = false;
								foreach($levelPromotions as $key => $blankPromotion){
									if($userLevelPromotion['PromotionID'] == $blankPromotion['PromotionID']){
										unset($levelPromotions[$key]);
										break;
									}
								}
							}
						}
					}else{
						$levelPromotionsReturn['personalPromotions'] = [];
					}

					if(!isset($commonPromotionsReturn['error']) && isset($levelPromotionsReturn['PersonalPromotions']))
					{
					$allLevelPromotions = array_merge($levelPromotionsReturn['PersonalPromotions'], $levelPromotions);
					} else {
						$allLevelPromotions = [];
					}

					if(isset($allLevelPromotions) && count($allLevelPromotions) > 0){
						
						$personalPromotions = new stdClass();

						foreach($allLevelPromotions as $key => $promotion){
							$personalPromotions->{$key} = new stdClass();
							
							if(!is_null($promotion['TriggerAmount'])){
								$personalPromotions->{$key}->amountNeeded = $promotion['TriggerAmount'];
								$personalPromotions->{$key}->amountPurchased = isset($promotion['PurchaseAmount']) ? $promotion['PurchaseAmount'] : 0;
								$personalPromotions->{$key}->couponType = "Amount";
							}else{
								$personalPromotions->{$key}->amountNeeded = $promotion['TriggerQty'];
								$personalPromotions->{$key}->amountPurchased = isset($promotion['PurchaseCount']) ? $promotion['PurchaseCount'] : 0;
								$personalPromotions->{$key}->couponType = "Quantity";
							}
							
							$personalPromotions->{$key}->id = $promotion['PromotionID'];
							$personalPromotions->{$key}->headline = $promotion['Description'];
							
							$personalPromotions->{$key}->percentComplete = number_format(($personalPromotions->{$key}->amountPurchased / $personalPromotions->{$key}->amountNeeded)*100);
							$personalPromotions->{$key}->description = $promotion['OfferDescription'];
							$personalPromotions->{$key}->expires = date("m/d/Y", strtotime($promotion['ExpirationDate']));
							$personalPromotions->{$key}->limit = $promotion['LimitMsg'];
							$personalPromotions->{$key}->restrictions = $promotion['Restrictions'];
							
						}
						
					}else {
						$personalPromotions =  null;
					}

					$_SESSION['rewardsPersonalPromotions'] = $personalPromotions;
					$_SESSION['rewardsCommonPromotions'] = $commonPromotions;
					
					return [$personalPromotions, $commonPromotions];
				}
			}else{
				return [$_SESSION['rewardsPersonalPromotions'], $_SESSION['rewardsCommonPromotions']];
			}
		}
		
		public function getUserOrderSummary(){
			$userXRef = $this->getUserXRef($this->userPhone);
			
			if(!is_null($userXRef)){
				$url = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/OrderTransactionSummary?days=60&includeSecondaryUsers=true";
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				$result=curl_exec($ch);
				
				$orderReturn = json_decode($result, true);
				$information = curl_getinfo($ch);
				
				curl_close($ch);
				
				//echo "<pre>";
				//var_dump($orderReturn);
				//echo "</pre>";
				
				if(isset($orderReturn['OrderTransactionSummarys'][0]['TransactionID'])){
					$theReturn = $orderReturn['OrderTransactionSummarys'];
				}else{
					$theReturn = [
						"error" => "400100",
						"message" => "There are no orders"
					];
				}
			}else{
				$theReturn = [
					"error" => "400000",
					"message" => "Could not get the user's XRef number"
				];
			}
			
			return $theReturn;
		}
		
		public function getUserCharities(){
			$userXRef = $this->getUserXRef($this->userPhone);
			
			if(!is_null($userXRef)){
				$url = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/Charities/Available";
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				$result=curl_exec($ch);
				
				$charitiesReturn = json_decode($result, true);
				$information = curl_getinfo($ch);
				
				curl_close($ch);
				
				if(isset($charitiesReturn['Charitys'])){
					$allCharities = new stdClass();
						
						
					foreach($charitiesReturn['Charitys'] as $charity){
						$key = $charity['CharityID'];
						$allCharities->{$key} = new stdClass();
						$allCharities->{$key}->id = $charity['CharityID'];
						$allCharities->{$key}->name = $charity['Name'];
						$allCharities->{$key}->description = $charity['Description'];
						$allCharities->{$key}->phone = $charity['Phone'];
						$allCharities->{$key}->url = $charity['WebSiteURL'];
					}
					$theReturn = $allCharities;
				}else{
					$theReturn = [
						"error" => "400100",
						"message" => "There are no orders"
					];
				}
			}else{
				$theReturn = [
					"error" => "400000",
					"message" => "Could not get the user's XRef number"
				];
			}
			
			return $theReturn;
		}
		
		public function getUserXRef(){
			if(!is_null($this->userXref)){
				return $this->userXref;
			}else{
				$url = $this->url . "/AFSWalletAPI/Wallets/WalletExists?opendatatype=6&opendata=" . $this->userPhone;
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				$result=curl_exec($ch);
				
				$walletReturn = json_decode($result, true);
				$information = curl_getinfo($ch);
				
				curl_close($ch);
				
				if(isset($walletReturn['Wallet']['$Identifications$'][0])){
					$this->userXref = $walletReturn['Wallet']['$Identifications$'][0]['XRef'];
					return $this->userXref;
				}
			}
		}

		public function getFuelRewardBalance(){
			$userXRef = $this->getUserXRef($this->userPhone);

			if(!is_null($userXRef)){
				$url = $this->url . "/AFSWalletAPI/Wallets/" . $userXRef . "/FuelRewardBalance";
				$authorization = "Authorization: Bearer " . $this->token;
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_HEADER, false);
				curl_setopt($ch, CURLOPT_POST, 0);
				curl_setopt($ch, CURLINFO_HEADER_OUT, true);
				$result=curl_exec($ch);
				
				$fuelRewardBalanceReturn = json_decode($result, true);
				$information = curl_getinfo($ch);
				
				curl_close($ch);
				
				//echo "<pre>";
				//var_dump($fuelRewardBalanceReturn);
				//echo "</pre>";
				
				if(isset($fuelRewardBalanceReturn['FuelRewardBalance']['AvailableCentsPerGallonReward'])){
					$theReturn = $fuelRewardBalanceReturn['FuelRewardBalance'];
				}else{
					$theReturn = [
						"error" => "400100",
						"message" => "Could not retrieve the user's Fuel Reward Balance"
					];
				}
			}else{
				$theReturn = [
					"error" => "400000",
					"message" => "Could not get the user's XRef number"
				];
			}
			
			return $theReturn;
		}
	
	}
?>