<?php

/*
 * User authenticate & user Info 3rd party integration.
 */

include_once 'lib/api-crypter.php';
//include_once 'lib/owner-detail.php';
// $firstDayOfMonth = mktime (0, 0, 0, date("m"), 1, date("Y"));
// $firstDayOfFirstMonth = date("Y-m-d", $firstDayOfMonth);
// $firstDayOfLastMonth = new DateTime($firstDayOfFirstMonth);
// $firstDayOfLastMonth->modify('first day of +4 month');


Class ApiWhppLogin {
	
	private $hubBaseURL = "https://hub-stage.wyndhamap.com/hub-api";
	private $cardTokenBaseUrl = "https://consumerapitest.wvc.wyndhamdestinations.com/api";	
	private $loginBaseUrl = "https://login.wyndhamap.com/security/securityAPI";
	private $irisBaseURL = "https://test1api.wvc.wyndhamdestinations.com";
	
	private $clientId = "KRuKUV7iCAarJTsZedG9pDBqXCTKpevq";
	private $clientSecret = "LLjMBPGeCQzInOIK";

    private $LoginAuthUrl = "/external/authenticate-basic.json";
	
	private $LoginOAuthUrl  = "/oauth/v2/accesstoken?grant_type=client_credentials";
	private $LoginIrisAuthUrl = "/v1/wd/owner-services/apac/accounts/authorization";
    private $OwnerDetailIrisUrl = "/v1/wd/owner-services/apac/accounts/details";
	private $HoldUrl = "/v1/wd/owner-services/apac/reservations/hold";
	private $ConfirmCreditUrl = "/v1/wd/owner-services/apac/reservations/confirm-credit";
	private $BookUrl = "/v1/wd/owner-services/apac/reservations/book";
	private $AvailabilityUrl = "/v1/wd/owner-services/apac/resorts/availability";
    private $UserInfoUrl = "/crm/membership/"; //.$member_id"
	private $ReservationDetails = "/v1/wd/owner-services/apac/reservations/details";
	private $ReservationsSearch = "/v1/wd/owner-services/apac/reservations/search";
	private $ReservationCancelDetails = "/v1/wd/owner-services/apac/reservations/cancel-details";
	private $ReservationCancel = "/v1/wd/owner-services/apac/reservations/cancel";
	private $ClubDetails = "/v1/wd/owner-services/apac/resorts/clubs";
	
	private $ResortURL = "/iris/get-resort-by-id/";
	private $ResortAllURL = "/iris/get-all-resorts";
	private $RoomTypesByResortURL = "/iris/get-room-type-list-by-resort-id/";
	private $ResortsByRegionURL = "/iris/get-iris-resorts-by-iris-region-id/";
	private $OwnerReservationsURL = "/resorts/get-owner-reservations/";
	private $OwnerInfoURL = "/crm/membership/";
	
	private $CountriesURL = "/crm/countries";	
	
	private $cardTokenUrl = "/marketing/payment/card/token";
	
	public $errorMessages = array(
		"This room type is currently off-line. Please choose another room type or try your search again later."=>
			"This room type is currently off-line. Please choose another room type or contact your Owner Services team for assistance.",
		"OVERRIDABLE: This account's status doesn't allow a reservation to be booked at this time. Account Status is Past Due or Bankrupt or Defaulted."=>
			"This account’s status doesn’t allow a reservation to be booked at this time. Please contact your Owner Services team.",
		"Error: OVERRIDABLE: Weekend stays must include both Friday and Saturday nights."=>
			"Weekend stays must include both Friday and Saturday nights.",
		"Please add reason for Open Balance in the Comments field."=>"Please contact your Owner Services team to complete this reservation",
		"Error confirming reservation : | The Reservation you are trying to confirm reflects data which is no longer valid."=>
			"Error: Please review your booking here: <a target=\"_blank\" href=\"https://clubwyndhamsp.com/book-now-new-view-cancel-reservation/\">View/Cancel Reservations</a>"
	);
	
	public $cardTypes = array(
		"001"=>"Visa",
		"002"=>"MasterCard",
		"003"=>"American Express",
		"004"=>"Discover",
		"005"=>"Diners Club",
		"006"=>"Diner's Club",
		"007"=>"JCB"
	);
	
	public $cardTypeIrisId = array(
		"001"=>"6",
		"002"=>"5",
		"003"=>"1",
		"004"=>"4",
		"005"=>"3",
		"006"=>"3"
	);
		
	public $months = array(
		"01"=>"Jan",
		"02"=>"Feb",
		"03"=>"Mar",
		"04"=>"Apr",
		"05"=>"May",
		"06"=>"Jun",
		"07"=>"Jul",
		"08"=>"Aug",
		"09"=>"Sep",
		"10"=>"Oct",
		"11"=>"Nov",
		"12"=>"Dec"
	);
	
	public $currencies = array(
		"AUD"=>"Australian Dollars",
		"NZD"=>"New Zealand Dollars"
	);
	
	public $paymentOptionTypes = array(
		"BonusVacationCreditPrice"=>"Bonus Time",
		"FunTimeVacationCreditPrice"=>"Fun Time",
		"EliteRentalCreditPrice"=>"One Time",
		"SpecialOfferCreditPrice"=>"Special Offer Credit",
		"VacationCreditPrice"=>"Holiday Credit",
		"InventorySpecialCreditPrice"=>"Exotic Fun Time",
		"ExoticBonusVacationCreditPrice"=>"Exotic Bonus Time",
		"AffiliateRentalCreditPrice"=>"US Time",
		"FaxTimeCreditPrice"=>"Fax Time Credit"
	);
	
    private $b = 2;

    function __construct() {

        add_action('init', array($this, 'whppSession'));
        add_action('whppEndSession', array($this, 'whpp_end_session'));

        add_action('wp_ajax_whpp_login', array($this, 'whppLogin'));
        add_action('wp_ajax_nopriv_whpp_login', array($this, 'whppLogin'));

        add_action('wp_ajax_whpp_logout', array($this, 'whppLogout'));
        add_action('wp_ajax_nopriv_whpp_logout', array($this, 'whppLogout'));

        add_action('wp_ajax_filter_rooms_by_resort', array($this, 'filterRoomsByResort'));
        add_action('wp_ajax_nopriv_filter_rooms_by_resort', array($this, 'filterRoomsByResort'));

        add_action('wp_ajax_filter_resort_by_region', array($this, 'filterResortByRegion'));
        add_action('wp_ajax_nopriv_filter_resort_by_region', array($this, 'filterResortByRegion'));

        add_action('wp_ajax_get_four_months_availability', array($this, 'getFourMonthsAvailability'));
        add_action('wp_ajax_nopriv_get_four_months_availability', array($this, 'getFourMonthsAvailability'));
		
		//login APIs
		$this->LoginAuthUrl = $this->loginBaseUrl . $this->LoginAuthUrl;
		
		//Iris APIs
		$this->LoginOAuthUrl = $this->irisBaseURL . $this->LoginOAuthUrl;
		$this->LoginIrisAuthUrl = $this->irisBaseURL . $this->LoginIrisAuthUrl;
		$this->OwnerDetailIrisUrl = $this->irisBaseURL . $this->OwnerDetailIrisUrl;
		$this->HoldUrl = $this->irisBaseURL . $this->HoldUrl;
		$this->ConfirmCreditUrl = $this->irisBaseURL . $this->ConfirmCreditUrl;
		$this->BookUrl = $this->irisBaseURL . $this->BookUrl;
		$this->AvailabilityUrl = $this->irisBaseURL . $this->AvailabilityUrl;
		$this->ReservationDetails = $this->irisBaseURL . $this->ReservationDetails;        
		$this->ReservationsSearch = $this->irisBaseURL . $this->ReservationsSearch;        
		$this->ReservationCancelDetails = $this->irisBaseURL . $this->ReservationCancelDetails;        
		$this->ReservationCancel = $this->irisBaseURL . $this->ReservationCancel;
		$this->ClubDetails = $this->irisBaseURL . $this->ClubDetails;
		
		$this->cardTokenUrl = $this->cardTokenBaseUrl . $this->cardTokenUrl;
		
		//hub APIs
		$this->UserInfoUrl = $this->hubBaseURL . $this->UserInfoUrl;
		$this->RoomTypesByResortURL = $this->hubBaseURL . $this->RoomTypesByResortURL;
		$this->ResortsByRegionURL = $this->hubBaseURL . $this->ResortsByRegionURL;
		$this->CountriesURL = $this->hubBaseURL . $this->CountriesURL;
		$this->ResortURL = $this->hubBaseURL . $this->ResortURL;
		$this->ResortAllURL = $this->hubBaseURL . $this->ResortAllURL;
		$this->OwnerReservationsURL = $this->hubBaseURL . $this->OwnerReservationsURL;	
		$this->OwnerInfoURL = $this->hubBaseURL . $this->OwnerInfoURL;			
    }

    function whppSession() {
        if (!session_id()) {
            session_start();
        }
    }

    function whpp_end_session() {
        session_destroy();
    }

    function whppLogout() {
        check_ajax_referer('Whpp_nonce', 'security');
        $this->whpp_end_session();
        echo json_encode(array("status" => "success"));
        die();
    }

    function whppLogin() {
		
		check_ajax_referer('Whpp_nonce', 'security');

        $memberID = $_POST['memberid'];
        $password = $_POST['password'];
		
		/* check user exist on API */
		
		$data = $this->loginIrisApi($memberID, $password);
		
		//$data = $this->loginApi($memberID, $password);
		$res = json_decode($data);
		
		
		if ($res->status == 'success') {
			if($memberID == '00201026014') {
				$memberID = '00071005400'; /// login as functionality
			}

			$udata = $this->getUserInfo($memberID);
			$resudata = json_decode($udata);

			if ($resudata->status == 'success') {

				$_SESSION["WHPPDATA"] = $resudata->data;
				$_SESSION["ownerinfo"] = [$memberID, $password];
				$_SESSION["ownerNumber"] = $memberID;
				
				$ownerDetail = $this->getOwnerDetail($memberID);
				$_SESSION["OWNER_DETAILS"] = $ownerDetail;
			}
		} else {
			$status = 'fail';
			$error = "Please check owner number and password." . $res->msg . ".";
		}
		
    echo $data;

    die();
    }


    function getAccessToken() {

		if($this->isAccessTokenExpired()) {
			
			$inputdata = array(
				"client_id" => $this->clientId, 
				"client_secret" => $this->clientSecret
				);
			$accessToken = '';
            $status = 'fail';
            $error = "";
            $apidata = "";

            $response = wp_remote_post(
                    $url = $this->LoginOAuthUrl, array(
                'method' => 'POST',
                'sslverify' => false,
                'data_format' => 'body',
                'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
                'body' => $inputdata
                    )
            );

			error_log( 'Oauth Authentication Response Code: ' . wp_remote_retrieve_response_code( $response ) );
			error_log( 'Oauth Authentication Response Message: ' . wp_remote_retrieve_response_message( $response ) );
			error_log( 'Oauth Authentication Response Body: ' . wp_remote_retrieve_body( $response ) );

			if (is_wp_error($response)) {
                $status = 'fail';
                $error = "Problem calling the OAuthAPI:" . $response->get_error_message() . ".";
            } else {
                $data = json_decode(wp_remote_retrieve_body($response));

                if (! empty($data)) {
					$accessToken = $data->access_token;
					
					if (empty($accessToken)) {
							$status = 'fail';
							$error = "Oauth access token is empty" . $response->get_error_message . ".";
					} else {
						$_SESSION["accessToken"] = $accessToken;
                        $_SESSION["token_issued_at"] = $data->issued_at;
                        $apidata = $data;
					}
                } else {
					$status = 'fail';
					$error = "Problem getting oauth access token:";
				}
            }
			//return json_encode(array("status" => $status, "msg" => $error, "data" => $apidata));
		}
		return $_SESSION["accessToken"];
    }
	
	
	    /*
     * This function provide user authentication.
     * param @memberID String
     * param @password String
     */

    function loginIrisApi($memberId, $passWord) {

        if (isset($memberId) && isset($passWord)) {
            $cf = new ApiCrypter;
            $memberId = $cf->encrypt($memberId);
            $passWord = $cf->encrypt($passWord);
			
			$memberId = "00004004424";
			$passWord = "242-224-211-241-161-88-193-8";

            $inputdata = json_encode(array("MemberNumber" => $memberId, "Password" => $passWord));
            $status = 'fail';
            $error = "";
            $apidata = "";

			$date = new DateTime();
			$timestamp = $date->format(DateTime::ATOM);
			
            $response = wp_remote_post(
                $url = $this->LoginIrisAuthUrl, array(
                'method' => 'POST',
                'sslverify' => false,
                'data_format' => 'body',
                'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'X-REQUEST-TIMESTAMP' => $timestamp, 'Authorization' => 'Bearer ' . $this->getAccessToken()),
                'body' => $inputdata
                    )
            );
			
			error_log( 'IRIS Authentication Response Code: ' . wp_remote_retrieve_response_code( $response ) );
			error_log( 'IRIS Authentication Response Message: ' . wp_remote_retrieve_response_message( $response ) );
			error_log( 'IRIS Authentication Response Body: ' . wp_remote_retrieve_body( $response ) );
			
			if (is_wp_error($response)) {

                $status = 'fail';
                $error = "Problem calling IRIS authentication API:" . $response->get_error_message() . ".";
            } else {
                $data = json_decode(wp_remote_retrieve_body($response));
                if ($data->Success == "true") {
                    $status = 'success';
                    $apidata = $data;
                } else if ($data->code == "400"){
                    $status = 'fail';
                    $error = "Please check owner number and password for IRIS authentication API. ";
                }
            }

        } else {
			$status = 'fail';
            $error = "Please check owner number and password should not empty.";
        }
        return json_encode(array("status" => $status, "msg" => $error, "data" => $apidata));
    }
	
	function getOwnerDetail($memberId) {
		
		$inputdata = json_encode(array("MemberNumber" => $memberId));
		
		$irisData = $this->irisCall($inputdata, $this->OwnerDetailIrisUrl, 'getOwnerDetail');
		
		$ownerDetails  = json_decode($irisData);		
		
		if ($ownerDetails->status == 'success') {
			
			$ownerDetail = new OwnerDetail();				
			$ownerDetail->ownerNumber = $memberId;
			$ownerDetail->accountId = $ownerDetails->data->AccountID;
			$ownerDetail->accountType = $ownerDetails->data->AccountType;
			$ownerDetail->tierName = $ownerDetails->data->ProgramTiers->Name; //e.g. LifestyleSilver
			$ownerDetail->tier = $ownerDetails->data->ProgramTiers->Description; //e.g. Lifestyle Silver
			if($ownerDetails->data->WMTSAnnualCredit>=100000) {
				$ownerDetail->tier = "100 Club";
			}
			$ownerDetail->ausContact = "1300 850 160";
			$ownerDetail->nzContact = "0800 850 160";
			$ownerDetail->fijiContact = "008 003 263";
			if($ownerDetails->data->WMTSAnnualCredit>=63000) { //Platimum tier numbers
				$ownerDetail->ausContact = "1800 076 077";
				$ownerDetail->nzContact = "0800 176 077";
			}
			$ownerDetail->EmailAddress = $ownerDetails->data->EmailAddress;
			$ownerDetail->Available_HK_Tokens = 0;
			$ownerDetail->Avail_Bonus_HK_Tokens  = $ownerDetails->data->IRCredits->Avail_Bonus_HK_Tokens;//HK token available to borrow
			$ownerDetail->Avail_Bonus_Credit  = $ownerDetails->data->IRCredits->Avail_Bonus_Credit;
			$ownerDetail->accountStatus = $ownerDetails->data->AccountStatusID==5?"PAST_DUE":"";
			$ownerDetail->reservationEnabled = $ownerDetail->accountStatus=="PAST_DUE"?false:true;	
			if(is_array($ownerDetails->data->IRContract)) {
				$ownerDetails->data->IRContract = $ownerDetails->data->IRContract[0];
			}
			if(isset($ownerDetails->data->IRContract->CreditsPerPeriod)) {
				if(is_object($ownerDetails->data->IRContract->CreditsPerPeriod)) {
					$ownerDetails->data->IRContract->CreditsPerPeriod = array($ownerDetails->data->IRContract->CreditsPerPeriod);
				}
				if(is_array($ownerDetails->data->IRContract->CreditsPerPeriod)) {
					foreach ($ownerDetails->data->IRContract->CreditsPerPeriod as $CreditsPerPeriod) {
						$ownerDetail->CreditsPerPeriod[$CreditsPerPeriod->CreditType->Name] = $CreditsPerPeriod->Amount;
					}
				}
			}
			if(isset($ownerDetails->data->CreditsToBorrow)) {
				if(is_object($ownerDetails->data->CreditsToBorrow)) {
					$ownerDetails->data->CreditsToBorrow = array($ownerDetails->data->CreditsToBorrow);
				}
				if(is_array($ownerDetails->data->CreditsToBorrow)) {
					foreach ($ownerDetails->data->CreditsToBorrow as $CreditsToBorrow) {
						$ownerDetail->CreditsToBorrow[$CreditsToBorrow->CreditType->Name] = $CreditsToBorrow->Amount;
					}
				}
			}
			if(isset($ownerDetails->data->IRCredits->AvailableCredits)) {
				if(is_object($ownerDetails->data->IRCredits->AvailableCredits)) {
					$ownerDetails->data->IRCredits->AvailableCredits = array($ownerDetails->data->IRCredits->AvailableCredits);
				}
				if(is_array($ownerDetails->data->IRCredits->AvailableCredits)) {
					foreach ($ownerDetails->data->IRCredits->AvailableCredits as $AvailableCredits) {
						$ownerDetail->AvailableCredits[$AvailableCredits->EligibiltyType]['Amount'] = $AvailableCredits->Amount;
						$ownerDetail->AvailableCredits[$AvailableCredits->EligibiltyType]['ExpirationDate'] = $AvailableCredits->ExpirationDate;
						if($AvailableCredits->CreditType->Name == "Housekeeping") {
							$ownerDetail->Available_HK_Tokens = $AvailableCredits->Amount;
						}
					}
				}
			}
			if(isset($ownerDetails->data->IROwner)) {
				if(is_object($ownerDetails->data->IROwner)) {
					$ownerDetails->data->IROwner = array($ownerDetails->data->IROwner);
				}
				if(is_array($ownerDetails->data->IROwner)) {
					$ownerCount = 1;
					foreach ($ownerDetails->data->IROwner as $IROwner) {
						$ownerDetail->IROwner[$ownerCount]->FirstName = $IROwner->FirstName;
						$ownerDetail->IROwner[$ownerCount]->LastName = $IROwner->LastName;
						
						if($ownerCount==1) {
							$ownerLastName = $IROwner->LastName;
							$ownerNamesMatch = $ownerNamesMatch . $IROwner->FirstName;
							$ownerNamesNoMatch = $ownerNamesNoMatch . $IROwner->FirstName .' '.$IROwner->LastName;
						}
						if($ownerCount==2) {
							if($IROwner->LastName == $ownerLastName) {
								$ownerLastNameMatch = true;
							}
							$ownerNamesMatch = $ownerNamesMatch . ' & ' . $IROwner->FirstName .' '.$IROwner->LastName;
							$ownerNamesNoMatch = $ownerNamesNoMatch . ' & ' . $IROwner->FirstName .' '.$IROwner->LastName;
						}
						$ownerCount++;
					}
					if($ownerLastNameMatch) {
						$ownerDetail->ownerNamesCorrespondence = $ownerNamesMatch;
					}else{
						$ownerDetail->ownerNamesCorrespondence = $ownerNamesNoMatch;
					}
				}
			}
			return $ownerDetail;
		}
		return null;
    }

    /*
     * This function provide user authentication.
     * param @memberID String
     * param @password String
     */

    function loginApi($memberId, $passWord) {

        if ($memberId != "" && $passWord != "") {

            $cf = new ApiCrypter;
            $memberId = $cf->encrypt($memberId);
            $passWord = $cf->encrypt($passWord);

            $inputdata = json_encode(array("username" => $memberId, "password" => $passWord));
            $status = 'fail';
            $error = "";
            $apidata = "";

            $response = wp_remote_post(
                    $url = $this->LoginAuthUrl, array(
                'method' => 'POST',
                'sslverify' => false,
                'data_format' => 'body',
                'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
                'body' => $inputdata
                    )
            );

			if (is_wp_error($response)) {

                $status = 'fail';
                $error = "Something went wrong:" . $response->get_error_message() . ".";
            } else {

                $data = json_decode(wp_remote_retrieve_body($response));
                if ($data->status == "SUCCESS") {
                    $status = 'success';
                    $apidata = $data;
                } else {
                    $status = 'fail';
                    $error = "Please check owner number and password.";
                }
            }
        } else {
            $status = 'fail';
            $error = "Please check owner number and password should not empty. 3";
        }

        return json_encode(array("status" => $status, "msg" => $error, "data" => $apidata));
    }

    /*
     * getUser Information by Member ID
     * This will get user info from Hub Api
     * param @menberId String
     */
    function getUserInfo($memberId) {

        $url = $this->UserInfoUrl . $memberId;
        $status = 'fail';
        $error = '';
        $data = '';

        $response = wp_remote_get($url);

        if (is_array($response)) {
            $data = json_decode(wp_remote_retrieve_body($response));
            ;
            $status = 'success';
        } else {
            $status = 'fail';
            $error = "Something went wrong:" . $response->get_error_message() . ".";
        }

        return json_encode(array("status" => $status, "data" => $data, "msg" => $error));
    }

    function isAccessTokenExpired() {
		
		if (isset($_SESSION["accessToken"]) && isset($_SESSION["token_issued_at"])) {
            $accessToken = $_SESSION["accessToken"];
            $issuedTime = $_SESSION["token_issued_at"];
			
			//die('isset issuedTime >>'.$issuedTime);
			
			//token expiry is set to 3599 sec ~ 1hr
            //check if token expire in 5 mins (300 sec)
            $expiryTime = $issuedTime/1000 + 3599 - 300;
			
			//die('isset issuedTime >>'.$issuedTime. ' expiryTime ' .$expiryTime . ' time() ' . time());
            if (time()>intval($expiryTime)) {
                // token is going to expire soon, get a new token.
                return true;
            }
        } else {
			//no value in session
			return true;
		}
		return false;
    }
	
	//Availability (You are here) -> Hold -> Confirm Credit -> Book
	function availability($fromDate, $toDate, $regionId, $resortId, $searchType) {
		
		$inputdata = array(
			"AccountID" => $_SESSION["OWNER_DETAILS"]->accountId,
			"RegionId" => $regionId,
			"ResortId" => $resortId
		);
		
		if($searchType == 'standard') {
			$inputdata["FromDate"] = $fromDate->format('Y-m-d');
			$inputdata["ToDate"] = $toDate->format('Y-m-d');
			
			echo "  dateFromStr>>>>> ".$fromDate->format('Y-m-d');
			echo "  dateToStr>>>>> ".$toDate->format('Y-m-d');
		} else {
			if($fromDate==null){
				$fromDate =  date("Y-m-d", strtotime(date("Y/m/d")));
                $fromDate = new DateTime($fromDate);
			    $inputdata["FromDate"] = $fromDate->format('Y-m-d');
				echo "  Null test dateFromStr>>>>> ".$fromDate->format('Y-m-d');
				
				$toDate =  date("Y-m-d", strtotime(date("Y/m/d").'+ 14 days'));
                $toDate = new DateTime($toDate);
			    $inputdata["ToDate"] = $toDate->format('Y-m-d');
			}
			
			
			
			
			echo "  dateFromStr>>>>> ".$fromDate->format('Y-m-d');
			echo "  dateToStr>>>>> ".$toDate->format('Y-m-d');
			
			//$inputdata["FromDate"] = date("Y-m-d", strtotime(date("Y/m/d")));
			//$inputdata["ToDate"] = date("Y-m-d", strtotime(date("Y/m/d").'+ 14 days'));
		}
		
		$inputdata = json_encode($inputdata);
		echo json_encode($inputdata);
		
		return $this->irisCall($inputdata, $this->AvailabilityUrl, 'availability');
    }
	
	//Availability -> Hold (You are here) -> Confirm Credit -> Book
	function hold($inputdata) {
        return $this->irisCall($inputdata, $this->HoldUrl, 'hold');
    }
	
	//Availability -> Hold -> Confirm Credit (You are here) -> Book
	function confirmCredit($inputdata) {
		return $this->irisCall($inputdata, $this->ConfirmCreditUrl, 'confirmCredit');
    }

	//Availability -> Hold -> Confirm Credit -> Book (You are here)
	function book($inputdata) {
		return $this->irisCall($inputdata, $this->BookUrl, 'book');
    }
	
	function reservationDetails($reservationID) {
		  
		$inputdata = json_encode(array(
			  "AccountID" => $_SESSION["OWNER_DETAILS"]->accountId,
			  "ReservationID" => $reservationID
		  ));
		
		return $this->irisCall($inputdata, $this->ReservationDetails, 'reservationDetails');
    }
	
	function reservationSearch() {
		
		$inputdata = json_encode(array(
		  "ResSearchCriteria" => array("AccountID" => $_SESSION["OWNER_DETAILS"]->accountId)
		));
		
		return $this->irisCall($inputdata, $this->ReservationsSearch, 'reservationSearch');
    }
	
	function reservationCancelDetails($reservationID) {
		
		$inputdata = json_encode(array(
			"AccountID" => $_SESSION["OWNER_DETAILS"]->accountId, 
			"ReservationID" => $reservationID
		));
		
		return $this->irisCall($inputdata, $this->ReservationCancelDetails, 'reservationCancelDetails');
    }
	
	function reservationCancel($reservationID) {
		
		$inputdata = json_encode(array(
			"AccountID" => $_SESSION["OWNER_DETAILS"]->accountId, 
			"ReservationID" => $reservationID
		));
		
		return $this->irisCall($inputdata, $this->ReservationCancel, 'reservationCancel');
    }
	
	function getRegions() {
		
		$regionResponse = $this->irisEmptyCall($this->ClubDetails, 'clubDetails');
		
		$regionArray = array();
		$regionData = json_decode($regionResponse);
		if( !empty( $regionData ) ) {
			foreach( $regionData->data->Club as $indclub ) {
				if($indclub->ClubID == 2){
					$regions = $indclub->Regions;
					foreach( $regions as $region ) {
						array_push($regionArray, $region->RegionID);
					}
				}
			}
		}
		$_SESSION["FILTEREDREGIONS"] = $regionArray;
		
		return $regionResponse;
    }
	
	function getCardToken($billTo, $card) {
		
		$inputdata = json_encode(array(
			"billTo" => $billTo, 
			"card" => $card
		));
		
		//print_r($inputdata);
		//die();
		
		$response = wp_remote_post(
            $url = $this->cardTokenUrl, array(
            'method' => 'POST',
            'sslverify' => false,
            'data_format' => 'body',
            'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'X-REQUEST-TIMESTAMP' => $timestamp, 
				'WVO-Header' => 'eyJvcmlnaW5hdG9yQXBwbGljYXRpb24iOiJNYXJrZXRpbmdSZWRlbXB0aW9uIiwiY2xpZW50SWQiOiJXZWIiLC
				JvcmlnaW5hdG9ySG9zdE5hbWUiOiIiLCJ0cmFuc2FjdGlvbklkIjoiIiwicmVxdWVzdFRpbWVzdGFtcCI6IiIsImNsaWVudEV4dGVuc
				2lvbnMiOlt7ImtleSI6IiIsInZhbHVlIjoiIn1dfQ=='),
            'body' => $inputdata
            )
        );

        error_log( 'getCardToken Response Code: ' . wp_remote_retrieve_response_code( $response ) );
        error_log( 'getCardToken Response Message: ' . wp_remote_retrieve_response_message( $response ) );
        error_log( 'getCardToken Response Body: ' . wp_remote_retrieve_body( $response ) );

        if (is_wp_error($response)) {
            $status = 'fail';
            $error = "Something went wrong:" . $response->get_error_message() . ".";
        } else {
            $data = json_decode(wp_remote_retrieve_body($response));
            $status = 'success';
        }
		
		//print_r($data);
		//die();

        return json_encode(array("status" => $status, "data" => $data, "msg" => $error));
    }
	
	function irisCall($inputdata, $callUrl, $callName) {

        $status = 'fail';
        $error = '';
        $data = '';

        $date = new DateTime();
        $timestamp = $date->format(DateTime::ATOM);
        
        $response = wp_remote_post(
            $url = $callUrl, array(
            'method' => 'POST',
            'sslverify' => false,
            'data_format' => 'body',
            'headers' => array('Content-Type' => 'application/json; charset=utf-8', 'X-REQUEST-TIMESTAMP' => $timestamp, 'Authorization' => 'Bearer ' . $this->getAccessToken()),
            'body' => $inputdata
            )
        );

        error_log( 'IRIS '.$callName.' Response Code: ' . wp_remote_retrieve_response_code( $response ) );
        error_log( 'IRIS '.$callName.' Response Message: ' . wp_remote_retrieve_response_message( $response ) );
        error_log( 'IRIS '.$callName.' Response Body: ' . wp_remote_retrieve_body( $response ) );

        if (is_wp_error($response)) {
            $status = 'fail';
            $error = "Something went wrong:" . $response->get_error_message() . ".";
        } else {
            $data = json_decode(wp_remote_retrieve_body($response));
            $status = 'success';
        }

        return json_encode(array("status" => $status, "data" => $data, "msg" => $error));
    }
	
	function irisEmptyCall($callUrl, $callName) {

        $status = 'fail';
        $error = '';
        $data = '';

        $date = new DateTime();
        $timestamp = $date->format(DateTime::ATOM);
        
        $response = wp_remote_post(
            $url = $callUrl, array(
            'method' => 'POST',
            'sslverify' => false,
            'headers' => array('X-REQUEST-TIMESTAMP' => $timestamp, 'Authorization' => 'Bearer ' . $this->getAccessToken())
            )
        );

        error_log( 'IRIS '.$callName.' Response Code: ' . wp_remote_retrieve_response_code( $response ) );
        error_log( 'IRIS '.$callName.' Response Message: ' . wp_remote_retrieve_response_message( $response ) );
        error_log( 'IRIS '.$callName.' Response Body: ' . wp_remote_retrieve_body( $response ) );

        if (is_wp_error($response)) {
            $status = 'fail';
            $error = "Something went wrong:" . $response->get_error_message() . ".";
        } else {
            $data = json_decode(wp_remote_retrieve_body($response));
            $status = 'success';
        }

        return json_encode(array("status" => $status, "data" => $data, "msg" => $error));
    }
			
    function filterRoomsByResort() {
		
		check_ajax_referer('Whpp_nonce', 'security');
		$irisresort  = $_POST['irisresort'];
		$iris_resort  = $_POST['iris_resort'];
		
		$url =   $this->RoomTypesByResortURL.$iris_resort;    
		$allRooms = wp_remote_retrieve_body(wp_remote_get($url));  
		//echo "  rooms>>> ".$allRooms;
		
		$allRooms = json_decode($allRooms);
		$rooms = array();
		
		foreach($allRooms as $room) {
			foreach($room->allowedProgramTiers as $allowedProgramTier) {
				if($_SESSION["OWNER_DETAILS"]->tierName == $allowedProgramTier->name) {
					$rooms[$room->id] = $room;
				}
			}
		}
		// Asc sort
		usort($rooms,function($first,$second){
			return strtolower($first->name) > strtolower($second->name);
		});
		$_SESSION["FILTEREDROOMS"] = json_encode($rooms);
		
		header('Content-Type: application/json; charset=utf-8');
		echo json_encode($rooms);
		die();
    }

    function filterResortByRegion() {
		
		check_ajax_referer('Whpp_nonce', 'security');
        $iris_region  = $_POST['iris_region'];
		$url =   $this->ResortsByRegionURL.$iris_region;   
        $allResorts = wp_remote_retrieve_body(wp_remote_get($url));  

		$allResorts = json_decode($allResorts);
		
		$resorts = array();
		foreach($allResorts as $resort) {
			//if($resort->entity == 'WMSP Club') {
				foreach($resort->allowedProgramTiers as $allowedProgramTier) {
					if($_SESSION["OWNER_DETAILS"]->tierName == $allowedProgramTier->name) {
						$resorts[$resort->irisId] = $resort;
					}
				}
			//} else if($resort->entity == 'Associate') {
			//	$resorts[$resort->irisId] = $resort;
			//}
		}
		
		// Asc sort
		usort($resorts,function($first,$second){
			return strtolower($first->name) > strtolower($second->name);
		});
		$_SESSION["FILTEREDRESORTS"] = json_encode($resorts);
		
		header('Content-Type: application/json; charset=utf-8');
		echo json_encode($resorts);
		die();
	}

	function getCountries() {
		$url =   $this->CountriesURL; 
		$countries = wp_remote_retrieve_body(wp_remote_get($url));  
		//die( "  countries>>>>> ".$countries);
		$countries = json_decode($countries);
		//var_dump($countries->data);
		//die( "  data>>>>> ".);
		//$_SESSION["COUNTRIES"] = $countries->data;	
		//echo "  countries>>>>> ".$countries->data;
		//var_dump($_SESSION["COUNTRIES"]);
		return $countries;
	} 
	
	function getOwnerReservations($ownerNumber) {
		$url =   $this->OwnerReservationsURL.$ownerNumber; 
		$reservations = wp_remote_retrieve_body(wp_remote_get($url));  
		$reservations = json_decode($reservations);
		return $reservations;
	}
	
	function getOwnerInfo($ownerNumber) {
		$url =   $this->OwnerInfoURL.$ownerNumber; 
		$ownerInfo = wp_remote_retrieve_body(wp_remote_get($url));  
		$ownerInfo = json_decode($ownerInfo);
		return $ownerInfo;
	} 
	
	function getAllResorts() {
		$resorts = array();
		
		if(!isset($_SESSION["ALLRESORTS"])) {
			$url = $this->ResortAllURL; 
			$allResorts = wp_remote_retrieve_body(wp_remote_get($url));  
			$allResorts = json_decode($allResorts);
			
			foreach($allResorts as $resort) {
				foreach($resort->allowedProgramTiers as $allowedProgramTier) {
					if($_SESSION["OWNER_DETAILS"]->tierName == $allowedProgramTier->name) {
						$resorts[$resort->irisId] = $resort;
					}
				}			
			}
			$_SESSION["RESORT_INFO"] = $resorts;
			$resorts = array_values($resorts);
			// Asc sort
			usort($resorts,function($first,$second){
				return strtolower($first->name) > strtolower($second->name);
			});
			$_SESSION["ALLRESORTS"] = $resorts;
			//$_SESSION["ALLRESORTS"] = json_encode($resorts);
		}
		$resorts = $_SESSION["ALLRESORTS"];
		return $resorts;
	}
	
	function getFuntimeResorts() {
		$allResorts = $this->getAllResorts();
		$funtimeResorts = array();
		foreach($allResorts as $resort) {
			foreach($resort->allowedProgramTiers as $allowedProgramTier) {
				if($_SESSION["OWNER_DETAILS"]->tierName == $allowedProgramTier->name) {
					foreach($allowedProgramTier->allowedPaymentOptions as $allowedPaymentOption) {
						if("FunTimeVacationCreditPrice" == $allowedPaymentOption->name) {
							$funtimeResorts[$resort->irisId] = $resort;
						}
					}
				}
			}
		}
		$funtimeResorts = array_values($funtimeResorts);
		// Asc sort
		usort($funtimeResorts,function($first,$second){
			return strtolower($first->name) > strtolower($second->name);
		});
		return array_values($funtimeResorts);	
	}
	
	function getResortInfo($resortId) {
		
		$url = $this->ResortURL.$resortId; 
		$resort = wp_remote_retrieve_body(wp_remote_get($url));  
		$resort = json_decode($resort);
		return $resort;	
	}
	
	function getResortRoomsInfo($resortId) {
		
		$url = $this->RoomTypesByResortURL.$resortId;    
		$rooms = wp_remote_retrieve_body(wp_remote_get($url));
		return json_decode($rooms);	
	}
	
	function getResortRoomInfo($resortId, $roomTypeID) {
		
		$url = $this->RoomTypesByResortURL.$resortId;    
		$rooms = wp_remote_retrieve_body(wp_remote_get($url)); 
		$rooms = json_decode($rooms);
		
		foreach($rooms as $room) {
			if($room->id == $roomTypeID) {
				break;
			}
		}
		//var_dump($room);
		return $room;		
	}
	
	function cardTypes() {		
		return $this->cardTypes;
	}
	
	function months() {		
		return $this->months;
	}
	
	function getValue($inputKey, $array) {
		foreach($array as $key => $val) {
			if($key == $inputKey) {
				return $val;
			}
		}
		return $inputKey;
	}
	
	function getKey($inputValue, $array) {
		foreach($array as $key => $val) {
			if($val == $inputValue) {
				return $key;
			}
		}
		return $inputValue;
	}

	function getFourMonthsAvailability() {

		$firstDayOfMonth = mktime (0, 0, 0, date("m"), 1, date("Y"));
		$firstDayOfFirstMonth = date("Y-m-d", $firstDayOfMonth);
		$firstDayOfLastMonth = new DateTime($firstDayOfFirstMonth);
		$firstDayOfLastMonth->modify('first day of +4 month');
		

		$firstDayOfLastMonth = $firstDayOfLastMonth->format('Y-m-d');

		echo "firstDayOfFirstMonth>>>" .$firstDayOfFirstMonth . "\n";
		echo "firstDayOfLastMonth>>>" .$firstDayOfLastMonth . "\n";

		echo "firstDayOfFirstMonth>>>" .date("Y-m-d", $firstDayOfFirstMonth) . "\n";
		echo "firstDayOfLastMonth>>>" .date("Y-m-d", $firstDayOfLastMonth) . "\n";

		$scrool_action_next ="next";
		$scrool_action_previous ="previous";
	 
		check_ajax_referer('Whpp_nonce', 'security');
		
		$iris_resort  = $_POST['iris_resort'];
		$from_date  = $_POST['from_date'];
		$to_date  = $_POST['to_date'];
		$iris_region  = $_POST['iris_region'];
		$iris_room_type  = $_POST['room_type'];
		$scrool_action  = $_POST['scrool_action'];
		$calendarStart =  $_POST['calendar_start'];
		$calendarEnd =  $_POST['calendar_end'];
		echo "calendarStart test>>>" . $calendarStart . "\n";
		echo "calendarend test>>>" . $calendarEnd . "\n";

		if(strcmp($scrool_action, $scrool_action_next) == 0){

			$nextEventCalendarStart = mktime (0, 0, 0, date("m")+$calendarStart, 1, date("Y"));
			$nextEventCalendarEnd = mktime (0, 0, 0, date("m")+$calendarEnd, 1, date("Y"));
			echo "nextEventCalendarStart>>>" .date("Y-m-d", $nextEventCalendarStart) . "\n";
			echo "nextEventCalendarEnd>>>" .date("Y-m-d", $nextEventCalendarEnd) . "\n";
			$firstDayOfFirstMonth = date("Y-m-d", $nextEventCalendarStart);
			$firstDayOfLastMonth = date("Y-m-d", $nextEventCalendarEnd);

		}elseif(strcmp($scrool_action, $scrool_action_previous) == 0){
			if($calendarStart <= 0){
				// $nextEventCalendarStart = mktime (0, 0, 0, date("m")+$calendarStart, 1, date("Y"));
				// $nextEventCalendarEnd = mktime (0, 0, 0, date("m")+$calendarEnd, 1, date("Y"));
				// $nextEventCalendarStart = mktime (0, 0, 0, date("m"), 1, date("Y"));
				
			}else{
				$nextEventCalendarStart = mktime (0, 0, 0, date("m")+$calendarStart, 1, date("Y"));
				$nextEventCalendarEnd = mktime (0, 0, 0, date("m")+$calendarEnd, 1, date("Y"));
				$firstDayOfFirstMonth = date("Y-m-d", $nextEventCalendarStart);
			   $firstDayOfLastMonth = date("Y-m-d", $nextEventCalendarEnd);
			}
			
			echo "global test>>>" . $firstDayOfFirstMonth . "\n";
			echo "global test>>>" .$firstDayOfLastMonth . "\n";
		}


		 $inputdata = json_encode(array(
					  "ResortId" => $iris_resort,
					  "ToDate" => $firstDayOfLastMonth,
					  "FromDate" => $firstDayOfFirstMonth,
					  "ReservationRoomTypeId" => $iris_room_type,
					  "RegionId" => $iris_region,
					  "AccountID" => $_SESSION["OWNER_DETAILS"]->accountId
				  ));

		$fourMonthData = $this->irisCall($inputdata, $this->AvailabilityUrl, 'availability');  
		echo "  fourWeeksData>>> ".$fourMonthData;
		$_SESSION["FOURMONTHAVAILABILITY"] = $fourMonthData;

	}  

	/**
	* Compute the start and end date of some fixed o relative quarter in a specific year.
	* @param mixed $quarter  Integer from 1 to 4 or relative string value:
	*                        'this', 'current', 'previous', 'first' or 'last'.
	*                        'this' is equivalent to 'current'. Any other value
	*                        will be ignored and instead current quarter will be used.
	*                        Default value 'current'. Particulary, 'previous' value
	*                        only make sense with current year so if you use it with
	*                        other year like: get_dates_of_quarter('previous', 1990)
	*                        the year will be ignored and instead the current year
	*                        will be used.
	* @param int $year       Year of the quarter. Any wrong value will be ignored and
	*                        instead the current year will be used.
	*                        Default value null (current year).
	* @param string $format  String to format returned dates
	* @return array          Array with two elements (keys): start and end date.
	*/
	function get_dates_of_quarter($quarter = 'current', $year = null, $format = null)
	{
		if ( !is_int($year) ) {        
		   $year = (new DateTime)->format('Y');
		}
		$current_quarter = ceil((new DateTime)->format('n') / 3);
		switch (  strtolower($quarter) ) {
		case 'this':
		case 'current':
		   $quarter = ceil((new DateTime)->format('n') / 3);
		   break;

		case 'previous':
		   $year = (new DateTime)->format('Y');
		   if ($current_quarter == 1) {
			  $quarter = 4;
			  $year--;
			} else {
			  $quarter =  $current_quarter - 1;
			}
			break;

		case 'first':
			$quarter = 1;
			break;

		case 'last':
			$quarter = 4;
			break;

		default:
			$quarter = (!is_int($quarter) || $quarter < 1 || $quarter > 4) ? $current_quarter : $quarter;
			break;
		}
		if ( $quarter === 'this' ) {
			$quarter = ceil((new DateTime)->format('n') / 3);
		}
		$start = new DateTime($year.'-'.(3*$quarter-2).'-1 00:00:00');
		$end = new DateTime($year.'-'.(3*$quarter).'-'.($quarter == 1 || $quarter == 4 ? 31 : 30) .' 23:59:59');

		return array(
			'start' => $format ? $start->format($format) : $start,
			'end' => $format ? $end->format($format) : $end,
		);
	}
}
new ApiWhppLogin;

Class OwnerDetail {
} new OwnerDetail;

Class ReservationInfo {
} new ReservationInfo;