<?php 
/*
* This Ajax call used to go paperless update-billing-contact-information.
*/

function whpp_get_the_user_ip() {
	if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
	//check ip from share internet
	$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
	//to check ip is pass from proxy
	$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
	$ip = $_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}


add_action('wp_ajax_setupautopay', 'whpp_setupautopay');
add_action('wp_ajax_nopriv_setupautopay', 'whpp_setupautopay');

function whpp_setupautopay(){
		$url = 'https://wsdl.wyndhamap.com:3443/';
		
		$financeStartOpt = false;
		$financeStartDate =  '';
		$arg = "";
		if('specific_date' == $_POST['financeStartOpt']){
			$financeStartOpt = true;
			$financeStartDate = date('c' , strtotime( $_POST['financeStartDate']) );
		}
		
	if('cc' == esc_attr($_POST['paymentMethod'])){
		
		$arg = array( "clientDetail" => array("name"=>"AUTOPAY"),"paymentMethod" => array("name"=>"Credit Card"),
					  "ownerNumber"=> esc_attr($_POST['ownerNum']),
					  "contractNumber"=> esc_attr($_POST['contractNumber']),
					
					"cardDetail" => array("cardName" =>  esc_attr($_POST["creditCardName"]),"cardNumber" => esc_attr($_POST["creditCardNumber"]),
					"cardType" => array("name" => esc_attr($_POST["creditCardType"])),
					"expiryMm" => esc_attr($_POST["creditCardExpiryMonth"]),
					"expiryYy" => esc_attr($_POST["creditCardExpiryYear"]),
					),
					
					"autopayPayment" => array("arrearsReqDate" => date('c' , strtotime( $_POST['arrearsReqDate']) ),"captureDate" => date('c' , strtotime("now") ) , "financeFrequencyOpt" => true,"financeFrequency" => esc_attr($_POST['financeFreq']),"financeStartOpt" => $financeStartOpt,"financeStartDate" => $financeStartDate,"leviesFrequencyOpt" => false,"leviesPrivilegesFrequencyOpt" => esc_attr($_POST["leviesPrivFees"]) 
					),
						
					"createdBy"=>"WMSP",
					"clientIp"=> "'".whpp_get_the_user_ip()."'",
					"active" => false
		
		
		);

	}
	
	if('bank' == esc_attr($_POST['paymentMethod'])){
		

		
		$arg = array( "clientDetail"=>array("name"=>"AUTOPAY"),
						"paymentMethod" => array("name"=>"Bank Deposit"),
						"ownerNumber"=> esc_attr($_POST['ownerNum']),
						"contractNumber"=> esc_attr($_POST['contractNumber']),
						"bankAccountDetail" =>array("accountName" => esc_attr($_POST['accountName']),"accountNumber" => esc_attr($_POST['accountNumber']),"bankName" => esc_attr($_POST['bankName']),"branchName"=> esc_attr($_POST['branchName']) ,"bsb"=> esc_attr($_POST['bsbNumber']) ),
						
						"autopayPayment" => array("arrearsReqDate" => date('c' , strtotime( $_POST['arrearsReqDate']) ),"captureDate" => date('c' , strtotime("now") ) , "financeFrequencyOpt" => true,"financeFrequency" => esc_attr($_POST['financeFreq']),"financeStartOpt" => $financeStartOpt,"financeStartDate" => $financeStartDate,"leviesFrequencyOpt" => false,"leviesPrivilegesFrequencyOpt" => esc_attr($_POST["leviesPrivFees"]) ),
											
						"createdBy"=>"WMSP",
						"clientIp"=> "'".whpp_get_the_user_ip()."'",
						"active" => false
		);
		
	}
		
	$args = array(
	'method' => 'POST',
	'timeout' => 45,
	'redirection' => 5,
	'httpversion' => '1.0',
	'blocking' => true,
	'headers' => array('Content-Type'=>'application/json'),
	
	'body' => json_encode( $arg ),
	'cookies' => array()
	);
	
	$response = wp_remote_post($url,$args);
	//var_dump($response); exit;
	if (!is_wp_error( $response ) ) {
		
		$response_code  = wp_remote_retrieve_response_code( $response ); 
		
		if(200 == $response_code){
			echo "Data updated successfully it will take 24 hours to update, Thank you for your patience and understanding";
			
		}else{
			echo "Something went wrong please try again after some time..";
		}
	}
	
	//die();
}

add_action('wp_ajax_ownerupdate', 'whpp_ownerupdate');
add_action('wp_ajax_nopriv_ownerupdate', 'whpp_ownerupdate');

function whpp_ownerupdate(){
	$url = 'https://hub.wyndhamap.com/hub-api/crm/membership/owner-address-change';
	$args = array(
	'method' => 'POST',
	'timeout' => 45,
	'redirection' => 5,
	'httpversion' => '1.0',
	'blocking' => true,
	'headers' => array('Content-Type'=>'application/json'),
	
	'body' => json_encode(array("ownerNumber" => esc_attr($_POST['OwnerNumber']),
					"personId" => esc_attr($_POST['personId']),
					"address1" => esc_attr($_POST['Address1']),
					"address2" => esc_attr($_POST['Address2']),
					"suburb" => esc_attr($_POST['suburb']),
					"postcode"  => esc_attr($_POST['Postcode']),
					"state" => esc_attr($_POST['state']),
					"country" => esc_attr($_POST['country']),
					"homePhone" => esc_attr($_POST['homePhone']),
					"mobilePhone" => esc_attr($_POST['mobilePhone']),
					"workPhone" => esc_attr($_POST['workPhone']),
					"email" => esc_attr($_POST['email']),
					)),
	'cookies' => array()
	);
	
		$response = wp_remote_post($url,$args);
		//var_dump($response); exit;
		if (!is_wp_error( $response ) ) {
			
			$response_code  = wp_remote_retrieve_response_code( $response ); 
			
			if(200 == $response_code){
				echo json_encode(array("status"=>true,'msg'=>"It will take up to 72 hours to update your details."));
			}else{
				echo json_encode(array("status"=>false,'msg'=>"Something went wrong please try again after some time."));
			}
		}
	die();
	
	
}

add_action('wp_ajax_gopaperless', 'whpp_gopaperless');
add_action('wp_ajax_nopriv_gopaperless', 'whpp_gopaperless');

function whpp_gopaperless(){
	$url = 'https://wsdl.wyndhamap.com/owner/update-billing-contact-information';
	$args = array(
	'method' => 'POST',
	'timeout' => 45,
	'redirection' => 5,
	'httpversion' => '1.0',
	'blocking' => true,
	'headers' => array('Content-Type'=>'application/x-www-form-urlencoded'),
	'body' => array( "ownerNum" => $_POST['ownerNum'],
					"contactMethod" =>  $_POST['contactMethod'],
					"emailAddress" => $_POST["emailAddress"],
					"streetAddress" => $_POST["streetAddress"],
					"city" => $_POST["city"],
					"state" => $_POST["state"],
					"postcode" => $_POST["postcode"],
					"country" => $_POST["country"],
					"changedBy" => "Owner",
					"changeType" => "Owners"),
				'cookies' => array()
				);
		$response = wp_remote_post($url,$args);
		
		if (!is_wp_error( $response ) ) {
			$response = wp_remote_retrieve_body($response);
			$response = json_decode($response);
			
			if(isset($response->success) && 1 == $response->success){
				echo json_encode($response);
			}
		}
	die();
	
}

add_action('wp_ajax_getdatagopaperless', 'whpp_get_gopaperless');
add_action('wp_ajax_nopriv_getdatagopaperless', 'whpp_get_gopaperless');

function whpp_get_gopaperless(){
	$res = '';
	if(isset($_SESSION["ownerinfo"][0])){
	$url = 'https://wsdl.wyndhamap.com/owner/get-billing-contact-information/owner/'.$_SESSION["ownerinfo"][0];
	$response = wp_remote_get($url);
	
		if ( !is_wp_error( $response ) ) {
			$response = wp_remote_retrieve_body($response);
			$response = json_decode($response);
			$res = json_encode(array("status"=>true, "data" => $response));
		}
	}else{
		$res = json_encode(array("status"=>false, "data" => "No Data available"));
	}
	echo $res;
	die();
}

add_action('wp_ajax_hold', 'hold');
add_action('wp_ajax_nopriv_hold', 'hold');

function hold() {
	
	$errorList = array();
	
	$ownerDetails = $_SESSION["OWNER_DETAILS"];
	
	if($_POST['mode']=='SEARCH_CALENDAR') {
		
		$nights = $_POST['numberOfNights'];
		$dayIntVal = $_POST['dayIntVal'];
		$monthIntVal = $_POST['monthIntVal'];
		$yearIntVal = $_POST['yearIntVal']; 
		$points = $_POST['pointsTotal'];

		$resortId = $_POST['iris_resort'];
		$resRoomTypeId = $_POST['iris_room'];
		
		$checkIn = new DateTime($yearIntVal."-".$monthIntVal."-".$dayIntVal);
		$checkOut = new DateTime($yearIntVal."-".$monthIntVal."-".$dayIntVal);
		$checkOut->modify('+'.$nights.' day');
		
	} else if($_POST['mode']=='SEARCH_STANDARD') {
		
		$resortId = $_POST['iris_resort'];
		$resRoomTypeId = $_POST['iris_room'];
		
		$checkIn = new DateTime($_POST['checkIn']);
		$checkOut = new DateTime($_POST['checkOut']);
		
	} else if($_POST['mode']=='SEARCH_BONUS_FUN') {

        $resortId = $_POST['iris_resort'];
		$resRoomTypeId = $_POST['iris_room'];

        $firstColWithValCounter = 0;
		$validSelection = 0;
		$invalidSelection = 0;
		$validCheckBoxSelection = true;

		$colWithValueCounter = 0;
		$colWithOutValueCounter = 0;

        for ($colCount = 3; $colCount <= 14; $colCount++) {

            $coloumPostName = 'col'.$colCount;
            if(($_POST[$coloumPostName] != null || $_POST[$coloumPostName] != '')  && $firstColWithValCounter == 0 ){
				$firstColWithValCounter =  $colCount;
				$checkIn = new DateTime($_POST[$coloumPostName]);    
				$colWithValueCounter++;
            }else{
				if($_POST[$coloumPostName] != null || $_POST[$coloumPostName] != ''){
					if($invalidSelection > 0){
					  $validCheckBoxSelection = false;
					  break;
					}
					$checkOut = new DateTime($_POST[$coloumPostName]);
					$checkOut = new DateTime(date('Y-m-d', strtotime($_POST[$coloumPostName]. ' + 1 days')));
					$validSelection = $colCount;
					$colWithValueCounter++;
				}else{
					$invalidSelection = $colCount;
					// $validCheckBoxSelection = false;
				}
            }
        }

		if($colWithValueCounter < 2){
			$validCheckBoxSelection = false;
		}

		if(!$validCheckBoxSelection){
			//add error
			array_push($errorList, "Invalid date selection");
		}

			//return errors
		if (!empty($errorList)) {
			$res = json_encode(array("status"=>false, "errors"=>$errorList));
			echo $res;
			die();
		}

		// add one night for the last selected date
		// $checkOut = new DateTime(date('Y-m-d', strtotime($checkOut. ' + 1 days')));
	}
	
	$inputdata = json_encode(array(
		"AccountID" => $ownerDetails->accountId, 
		"CheckInDate" => date_format($checkIn,"Y-m-d")."T00:00:00.000", 
		"CheckOutDate" => date_format($checkOut,"Y-m-d")."T00:00:00.000",
		"ResortID" => $resortId, 
		"ReservationRoomTypeID" => $resRoomTypeId
	));
	
    $whpp_api = new ApiWhppLogin();
	
	$response = $whpp_api->hold($inputdata);
	$result = json_decode($response);
	
	if($result->data->code == "400" || $result->status == "fail") {
		$error = $result->data->message;
		if (strpos($error, '[') !== false) {
			$error = trim(substr($error, 0, strpos($error,"["))); 			//remove id information, making error generic
		}		
		$error = $whpp_api->getValue($error,$whpp_api->errorMessages); 		//replace with alternate error, if provided
		array_push($errorList, $error);										//add to error array
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$whpp_api->ReservationInfo->ReservationID = $result->data->ReservationID;
	$whpp_api->ReservationInfo->PaymentAccounts = $result->data->ResAccount->PaymentAccounts;
	$whpp_api->ReservationInfo->CancelDate = $result->data->CancelByDate;
	$whpp_api->ReservationInfo->CheckIn = $checkIn;
	$whpp_api->ReservationInfo->CheckOut = $checkOut;
	$whpp_api->ReservationInfo->Nights = $checkIn->diff($checkOut)->days;

	foreach($result->data->ReservationPrices as $ReservationPrice) {
		if($ReservationPrice->APaymentOption->aPaymentOptionType->Name=="VacationCreditPrice") {
			$points = $ReservationPrice->CreditPools->Amount;
			break;
		}
	}
	$whpp_api->ReservationInfo->Points = $points;
	
	$reservationPrices = array();
	
	//var_dump(json_encode($result->data->ReservationPrices));
	
	foreach($result->data->ReservationPrices as $ReservationPrice) {
		$reservationPrices[$ReservationPrice->APaymentOption->aPaymentOptionType->Name] = $ReservationPrice;
	}
	
	//remove BonusVacationCreditPrice, if both ExoticBonusVacationCreditPrice and BonusVacationCreditPrice exist
	/*if (array_key_exists("ExoticBonusVacationCreditPrice",$reservationPrices) 
		&& array_key_exists("BonusVacationCreditPrice",$reservationPrices)) {
		unset($reservationPrices['BonusVacationCreditPrice']);
	}
	
	//remove FunTimeVacationCreditPrice, if both ExoticFunTimeVacationCreditPrice and FunTimeVacationCreditPrice exist
	if (array_key_exists("ExoticFunTimeVacationCreditPrice",$reservationPrices) 
		&& array_key_exists("FunTimeVacationCreditPrice",$reservationPrices)) {
		unset($reservationPrices['FunTimeVacationCreditPrice']);
	}
	
	//remove FunTimeVacationCreditPrice, if both InventorySpecialCreditPrice and FunTimeVacationCreditPrice exist
	if (array_key_exists("InventorySpecialCreditPrice",$reservationPrices) 
		&& array_key_exists("FunTimeVacationCreditPrice",$reservationPrices)) {
		unset($reservationPrices['FunTimeVacationCreditPrice']);
	}
	
	//remove SpecialOfferCreditPrice
	if (array_key_exists("SpecialOfferCreditPrice",$reservationPrices)) {
		unset($reservationPrices['SpecialOfferCreditPrice']);
	}
	
	//remove FaxTimeCreditPrice
	if (array_key_exists("FaxTimeCreditPrice",$reservationPrices)) {
		unset($reservationPrices['FaxTimeCreditPrice']);
	}*/
	
	//var_dump(json_encode(array_values($reservationPrices)));
	
	$whpp_api->ReservationInfo->ReservationPrices = array_values($reservationPrices);
	
	$whpp_api->ReservationInfo->Campaigns = $result->data->Campaigns;
	
	$resortResponse = $whpp_api->getResortInfo($resortId);
	$roomResponse = $whpp_api->getResortRoomInfo($resortId, $resRoomTypeId);
	
	$whpp_api->ReservationInfo->Resort->ResortID = $resortId;
	$whpp_api->ReservationInfo->Resort->Name = $resortResponse->name;
	$whpp_api->ReservationInfo->Resort->Alert = $resortResponse->alert;
	$whpp_api->ReservationInfo->Resort->CheckInTime = $resortResponse->checkInTime;
	$whpp_api->ReservationInfo->Resort->CheckOutTime = $resortResponse->checkOutTime;
	
	$clubRegions = $_SESSION["FILTEREDREGIONS"];
	
	$regionIds = array_reverse($resortResponse->regionIds);
	foreach($regionIds as $region) {
		if (in_array($region, $clubRegions)) {
			$regionId = $region;
			break;
		}
	}
	$whpp_api->ReservationInfo->Resort->RegionId = $regionId;
	
	foreach($resortResponse->addresses as $address) {
		if($address->addressType=="CONTACT") {
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->City = $address->suburb;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->StreetAddress1 = $address->addressLine1;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->StreetAddress2 = $address->addressLine2;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->StreetAddress3 = $address->addressLine3;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->State = $address->state->name;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->CountryName = $address->country->name;
			$whpp_api->ReservationInfo->Resort->ContactInfo->Address->PostCode = $address->postcode;
		}
		else if($address->addressType=="CHECK_IN") {
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->City = $address->suburb;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->StreetAddress1 = $address->addressLine1;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->StreetAddress2 = $address->addressLine2;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->StreetAddress3 = $address->addressLine3;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->State = $address->state->name;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->CountryName = $address->country->name;
			$whpp_api->ReservationInfo->Resort->ContactInfo->CheckInAddress->Address->PostCode = $address->postcode;
		}
	}
	
	$phonesCounter=0;
	foreach($resortResponse->phones as $phone) {
		if($phonesCounter==0) {
			$whpp_api->ReservationInfo->Resort->ContactInfo->Phone1 = 
			$phone->countryCode.'-'.ltrim($phone->areaCode, "0").'-'.$phone->exchange.'-'.$phone->number;
		} else if($phonesCounter==1) {
			$whpp_api->ReservationInfo->Resort->ContactInfo->Phone2 = 
			$phone->countryCode.'-'.ltrim($phone->areaCode, "0").'-'.$phone->exchange.'-'.$phone->number;
		} else if($phonesCounter==2) {
			$whpp_api->ReservationInfo->Resort->ContactInfo->Phone3 = 
			$phone->countryCode.'-'.ltrim($phone->areaCode, "0").'-'.$phone->exchange.'-'.$phone->number;
		}
		$phonesCounter++;
	}
	
	$whpp_api->ReservationInfo->Resort->ReservationRoomType->ReservationRoomTypeID = $resRoomTypeId;
	$whpp_api->ReservationInfo->Resort->ReservationRoomType->Name = $roomResponse->name;
	$whpp_api->ReservationInfo->Resort->ReservationRoomType->Online_Room_Name = $roomResponse->name;
	$whpp_api->ReservationInfo->Resort->ReservationRoomType->Description = $roomResponse->desc;
	$whpp_api->ReservationInfo->Resort->ReservationRoomType->MaxOccupancy = $roomResponse->maxOccupancy;
	
	$whpp_api->ReservationInfo->Status = 'HOLD';
		
	$_SESSION["RESERVATION_INFO"] = $whpp_api->ReservationInfo;
	
	$_SESSION["REQUEST"] = $inputdata;
	$_SESSION["MODEL"] = $result;
	
	$res = json_encode(array("status"=>true));
	
	echo $res;
	die();
}
	
add_action('wp_ajax_confirmCredit', 'confirmCredit');
add_action('wp_ajax_nopriv_confirmCredit', 'confirmCredit');

function confirmCredit() {
	
	$errorList = array();
	
	$ReservationInfo = $_SESSION["RESERVATION_INFO"];
	
	$paymentOption = $_POST['paymentOption'];
    $borrowFlag = $_POST['borrowHK'];
	
    $reservationID = $ReservationInfo->ReservationID;
    $borrowFlagVal = ($borrowFlag == "Y" ? "true" : "false");
	
	if(!empty($_POST['promoCode'])) {
		$promoCodeMatch = false;
		foreach($ReservationInfo->Campaigns as $Campaigns) {
		  	if($_POST['promoCode'] == $Campaigns->Name) {
		  		$promoCodeMatch = true;
				$selectedCampaign = $Campaigns;
		  		break;
		  	}
		}
		if(!$promoCodeMatch) {
			array_push($errorList, "The promotional code does not exist");
		}
	}
	
	//return errors
	if (!empty($errorList)) {
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	//no validation errors, continue
	$inputdata = array(
		"ReservationID" => $reservationID, 
		"borrowHKFlag" => $borrowFlagVal, 
		"aPaymentOptionType" => array(
			"Name" => $paymentOption
		)
	);	
	if($promoCodeMatch) {
		$inputdata["campaign"] = array(
			"Name" => $selectedCampaign->Name,
			"Id" => $selectedCampaign->Id
		);
	}
	
	$whpp_api = new ApiWhppLogin();
	$response = $whpp_api->confirmCredit(json_encode($inputdata));
	$result = json_decode($response);
	
	if($result->data->code == "400" || $result->status == "fail") {
		$error = $result->data->message;
		if (strpos($error, '[') !== false) {
			$error = trim(substr($error, 0, strpos($error,"["))); 			//remove id information, making error generic
		}
		$error = $whpp_api->getValue($error,$whpp_api->errorMessages); 		//replace with alternate error, if provided
		array_push($errorList, $error);										//add to error array
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$ReservationInfo->Resort->Alert = $result->data->ResortAlert;
	$ReservationInfo->PaymentOption = $paymentOption;
	$ReservationInfo->TotalDueInDollars = $result->data->TotalDueInDollars->Amount;
	$ReservationInfo->Currency = $result->data->TotalDueInDollars->Currency;
	
	$ReservationInfo->Status = 'CONFIRM_CREDIT';
	
	$_SESSION["RESERVATION_INFO"] = $ReservationInfo;
	
	$_SESSION["REQUEST"] = json_encode($inputdata);
	$_SESSION["MODEL"] = $result;
	
	$res = json_encode(array("status"=>true));
	
	echo $res;
	die();
}
	
add_action('wp_ajax_book', 'book');
add_action('wp_ajax_nopriv_book', 'book');

function book() {
	
	$errorList = array();
	
	$ReservationInfo = $_SESSION["RESERVATION_INFO"];
	
	//validate form
	
	//return validation errors
	if (!empty($errorList)) {
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$whpp_api = new ApiWhppLogin();
	
	if(isset($_POST['paymentAccounts'])) {
		
		if($_POST['paymentAccounts']=='N') {
			
			if(empty($_POST['cardType'])) {
				array_push($errorList, "The card type cannot be empty");
			}
			if(empty($_POST['cardNumber'])) {
				array_push($errorList, "The card number cannot be empty");
			}
			if(empty($_POST['cardExpiryMonth'])) {
				array_push($errorList, "The card expiry month cannot be empty");
			}
			if(empty($_POST['cardExpiryYear'])) {
				array_push($errorList, "The card expiry year cannot be empty");
			}
			if(empty($_POST['cardFirstName'])) {
				array_push($errorList, "The card first name cannot be empty");
			}
			if(empty($_POST['cardLastName'])) {
				array_push($errorList, "The card last name cannot be empty");
			}
			if(empty($_POST['cardAddress'])) {
				array_push($errorList, "The card address cannot be empty");
			}
			if(empty($_POST['cardCity'])) {
				array_push($errorList, "The card city cannot be empty");
			}
			if(empty($_POST['cardState'])) {
				array_push($errorList, "The card state cannot be empty");
			}
			if(empty($_POST['cardCountry'])) {
				array_push($errorList, "The card country cannot be empty");
			}
			if(empty($_POST['cardPostCode'])) {
				array_push($errorList, "The card post code cannot be empty");
			}
			if(empty($_POST['cardPhone'])) {
				array_push($errorList, "The card phone cannot be empty");
			}
			
			if(!empty($_POST['bookFor']) && $_POST['bookFor']=='G') {
				if(empty($_POST['guestFirstName'])) {
					array_push($errorList, "Guest first name cannot be empty");
				}
				if(empty($_POST['guestLastName'])) {
					array_push($errorList, "Guest last name cannot be empty");
				}
			}
			
			//return validation errors
			if (!empty($errorList)) {
				$res = json_encode(array("status"=>false, "errors"=>$errorList));
				echo $res;
				die();
			}
			
			$cardNumber = $_POST['cardNumber'];
			$cardNumber = preg_replace("/[^0-9]/", "", $cardNumber);
			
			//tokenize card 
			$billTo = array(
				"lastName" => $_POST['cardLastName'], 
				"firstName" => $_POST['cardFirstName'],
				"postalCode" => $_POST['cardPostCode'], 
				"country" => $_POST['cardCountry'],
			);
			
			$card = array(
				"accountNumber" => $cardNumber, 
				"expirationMonth" => $_POST['cardExpiryMonth'],
				"expirationYear" => $_POST['cardExpiryYear'], 
				"cardType" => $_POST['cardType'],
			);
			
			$tokenResponse = json_decode($whpp_api->getCardToken($billTo, $card));	
			
			$token = $tokenResponse->data->wvoToken;
			
			if(empty($token)) {
				array_push($errorList, "There is a problem with the system, the credit card account appears to be invalid(token)");
			}
			
			//return tokenization errors
			if (!empty($errorList)) {
				$res = json_encode(array("status"=>false, "errors"=>$errorList));
				echo $res;
				die();
			}
			
			$transPaymentAccount = array(
				"Name" => $whpp_api->getValue($_POST['cardType'],$whpp_api->cardTypes),
				"AccountType" => "Credit Card",
				"CcExpirationDate" => $_POST['cardExpiryYear']."-".$_POST['cardExpiryMonth']."-01T00:00:00.000",
				"NameOnAccount" => $_POST['cardFirstName']." ".$_POST['cardLastName'],
				"AccountAddress" => array(
					"StreetAddress1" => $_POST['cardAddress'],
					"City" => $_POST['cardCity'],
					"StateProvince" => $_POST['cardState'],
					"Country" => array(
						"DisplayName" => $_POST['cardCountry'],
						//"ID" => "1",
						//"CountryLocale" => array(
						//	"Language" => "en",
						//	"CountryName" => "1"
						//)
					),
					"ZipPostalCode" => $_POST['cardPostCode']
				),
				"SaveMe" => $_POST['cardSave']=='Y'?'true':'false',
				"EncryptedAccountNumber" => $token,
				"CcTypeID" => $whpp_api->getValue($_POST['cardType'],$whpp_api->cardTypeIrisId),
				"Phone" => $_POST['cardPhone']
			);
		}
		else {
			$counter=0;
			if(isset($ReservationInfo->PaymentAccounts)){
				if(is_array($ReservationInfo->PaymentAccounts)) {
					foreach ($ReservationInfo->PaymentAccounts as $paymentAccount) {
						if($counter == $_POST['paymentAccounts']) {
							$transPaymentAccount = $paymentAccount;
						}
					}
				}
				if(is_object($ReservationInfo->PaymentAccounts)) {
					$paymentAccount = $ReservationInfo->PaymentAccounts;
					$transPaymentAccount = $paymentAccount;
				}
			}
		}
	}
	
	$inputdata = array(
		"ReservationID" => $ReservationInfo->ReservationID
	);
	
	if(!empty($_POST['bookFor']) && $_POST['bookFor']=='G') {
		$inputdata["GuestFirstName"] = $_POST['guestFirstName'];
		$inputdata["GuestLastName"] = $_POST['guestLastName'];
	}
	
	if(isset($ReservationInfo->TotalDueInDollars) && $ReservationInfo->TotalDueInDollars>0) { //TO_DO negate		
		$inputdata["ReservationMoneyTransactions"] = array(
			"Amount" => array(
				"Amount"=> $ReservationInfo->TotalDueInDollars,
				"Currency"=> $ReservationInfo->Currency
			),
			"TransPaymentAccount" => $transPaymentAccount
		);
	}
	
	$inputdata = json_encode($inputdata);	
	$response = $whpp_api->book($inputdata);
	$result = json_decode($response);
	
	if($result->data->code == "400" || $result->status == "fail") {
		$error = $result->data->message;
		if (strpos($error, '[') !== false) {
			$error = trim(substr($error, 0, strpos($error,"["))); 			//remove id information, making error generic
		}		
		$error = $whpp_api->getValue($error,$whpp_api->errorMessages); 		//replace with alternate error, if provided
		array_push($errorList, $error);										//add to error array
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$ReservationInfo->TotalDueInDollars = $result->data->TotalDueInDollars->Amount;
	$ReservationInfo->Currency = $result->data->TotalDueInDollars->Currency;
	$ReservationInfo->Status = 'BOOK';
		
	$ownerDetails = $_SESSION["OWNER_DETAILS"];
	$ownerDetails = $whpp_api->getOwnerDetail($ownerDetails->ownerNumber);
	$_SESSION["OWNER_DETAILS"] = $ownerDetails;
	
	$_SESSION["RESERVATION_INFO"] = $ReservationInfo;
	
	$_SESSION["REQUEST"] = $inputdata;
	$_SESSION["MODEL"] = $result;
	
	$res = json_encode(array("status"=>true));
	
	echo $res;
	die();
}

add_action('wp_ajax_confirmCancel', 'confirmCancel');
add_action('wp_ajax_nopriv_confirmCancel', 'confirmCancel');

function confirmCancel() {
	
	$errorList = array();
	
	$reservationID = $_POST['reservationID'];
	
	$whpp_api = new ApiWhppLogin();
	$response = $whpp_api->reservationCancel($reservationID);
	$result = json_decode($response);
	
	if($result->data->code == "400" || $result->status == "fail"){
		array_push($errorList, $result->data->message);
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$_SESSION["MODEL"] = $result;
	
	$res = json_encode(array("status"=>true));
	
	echo $res;
	die();
}

add_action('wp_ajax_cancelHold', 'cancelHold');
add_action('wp_ajax_nopriv_cancelHold', 'cancelHold');

function cancelHold() {
	
	$errorList = array();
	
	$ReservationInfo = $_SESSION["RESERVATION_INFO"];
	$reservationID = $ReservationInfo->ReservationID;
	
	$whpp_api = new ApiWhppLogin();
	$response = $whpp_api->reservationCancel($reservationID);
	$result = json_decode($response);
	
	if($result->data->code == "400" || $result->status == "fail"){
		array_push($errorList, $result->data->message);
		$res = json_encode(array("status"=>false, "errors"=>$errorList));
		echo $res;
		die();
	}
	
	$res = json_encode(array("status"=>true));
	echo $res;
	die();
}

add_action('wp_ajax_getResorts', 'getResorts');
add_action('wp_ajax_nopriv_getResorts', 'getResorts');

function getResorts(){
	
	$whpp_api = new ApiWhppLogin();

	if(!empty($_GET['searchType']) 
		&& ($_GET['searchType']=='standard' || $_GET['searchType']=='bonus')) {
		$response = $whpp_api->getAllResorts();
	} else if(!empty($_GET['searchType']) 
		&& ($_GET['searchType']=='fun')) {
		$response = $whpp_api->getFuntimeResorts();
	}
	echo json_encode($response);
	die();
}
