<?php
set_time_limit(0);

class Expedia_rest_api {
	
	private $cid = "421017"; //"55505";
	private $minorRev = "20";
	private $apiKey = "7zs3uc7cdmhsc8phjwnd9nug";
	
	private $customerUserAgent = '';
	private $customerIpAddress = '';
	private $customerSessionId = '';
	private $locale = "en_GB";
	private $currencyCode = "EUR";
	private $supplierCacheTolerance = "MED_ENHANCED";
	private $stateProvinceCode = "";
	private $countryCode = "CY";
	private $protocol = "http";
	private $useCache = true;
	
	// Search Options
	private $hotelId = '';
	private $city = '';
	private $destinationString = '';
	
	// Room availability
	private $arrivalDate = '';
	private $departureDate = '';
	private $numberOfBedRooms = '';
	private $supplierType = ''; // E, S, W, V
	private $rateKey = '';
	private $numberOfResults = 20;
	private $RoomGroup = array(
		"Room"					=> '',
		"numberOfAdults"		=> '',
		"numberOfChildren"		=> '',
		"childAges"				=> '',
		"includeDetails"		=> ''
	);
	private $includeRoomImages = '';
	private $options = ''; // HOTEL_DETAILS, ROOM_TYPES, ROOM_AMENITIES, PROPERTY_AMENITIES, HOTEL_IMAGES
	
	
	
	/*
	// Available request types
	// HotelList
	
	*/
	

	public function __construct($opts = array() ) {
		if(count($opts) > 0) {
			
			if(isset($opts['arrivalDate']) && $opts['arrivalDate'] != "") $opts ['arrivalDate'] = $this->date_conv(trim($opts['arrivalDate']), 'd/m/Y', 'm/d/Y');
			if(isset($opts['departureDate']) && $opts['departureDate'] != "") $opts ['departureDate'] = $this->date_conv(trim($opts['departureDate']), 'd/m/Y', 'm/d/Y');
			
			
			foreach ($opts as $var=>$value) {
				if(isset($this->$var)) {
					$this->$var = $value;
				}
			}
		}
		
		if($this->customerSessionId == '') {
			
			if(isset($_SESSION['customerSessionId']) && $_SESSION['customerSessionId'] != "") {
				$this->customerSessionId = $_SESSION['customerSessionId'];
			}
			else {
				$ping_response = json_decode($this->ean_ping(), true);
			
			//echo '<pre>$resp = ', var_export($ping_response, true), '</pre>';
			
				$this->customerSessionId = $ping_response['PingResponse']['customerSessionId'];
				$_SESSION['customerSessionId'] = $this->customerSessionId;
			}
		}
		
		$this->customerUserAgent = $_SERVER['HTTP_USER_AGENT'];
		$this->customerIpAddress = $_SERVER['REMOTE_ADDR'];
	}
	
	public function date_conv($date, $from_format, $to_format='Y-m-d') {
		$con_date = DateTime::createFromFormat($from_format, $date);
		
		return $con_date->format($to_format);
	}
	
	public function ean_ping() {
		$url = $this->protocol . '://' . 'api.ean.com/ean-services/rs/hotel/v3/ping' . '?';
		
		$delete_params = array(
			"countryCode", "useCache", "protocol", "numberOfResults", "supplierCacheTolerance", "locale", "currencyCode"
		);
		
		
		$params = array();
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') {
				if(!in_array($p, $delete_params)) {
					$params[$p] = $v;
				}
			}
		}

		$params['echo'] = 'test';
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('PingRequest', $url, $params_str);
	}
	
	
	public function get_hotels_by_city($city) {
		$this->city = trim($city);
		$url = $this->protocol . '://' .  'api.ean.com/ean-services/rs/hotel/v3/list' . '?';
		
		$params = array();
		
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') $params[$p] = $v;
		}
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('HotelList', $url, $params_str);
		
	}
	
	public function get_hotels_by_id($hotelId) {
		$this->hotelId = intval($hotelId);
		$url = $this->protocol . '://' .  'api.ean.com/ean-services/rs/hotel/v3/list' . '?';
		
		$delete_params = array(
			"countryCode", "protocol", "numberOfResults"
		);
		
		$params = array();
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') {
				if(!in_array($p, $delete_params)) {
					$params[$p] = $v;
				}
			}
		}
		
		
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('HotelList', $url, $params_str);
		
	}
	
	public function get_hotels_by_citystring($citystring) {

		$this->destinationString = trim($citystring);
		$url = $this->protocol . '://' .  'api.ean.com/ean-services/rs/hotel/v3/list' . '?';
		
		$params = array();
		
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') $params[$p] = $v;
		}
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('HotelList', $url, $params_str);
		
	}
	
	public function get_hotel_availability($hotelId, $data) {
		if($this->customerSessionId == '') {		
			$ping_response = json_decode($this->ean_ping(), true);
			$this->customerSessionId = $ping_response[0]['customerSessionId'];
		}
		
		$url = $this->protocol . '://' . 'api.ean.com/ean-services/rs/hotel/v3/avail' . '?';
		
		$delete_params = array(
			"countryCode", "useCache", "customerUserAgent", "customerIpAddress", "protocol", "numberOfResults", "supplierCacheTolerance"
		);
		
		
		$params = array();
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') {
				if(!in_array($p, $delete_params)) {
					$params[$p] = $v;
				}
			}
		}
		
		$params ['hotelId']	= $hotelId;

		if(isset($data['arrivalDate']) && $data['arrivalDate'] != "") $params ['arrivalDate'] = $this->date_conv(trim($data['arrivalDate']), 'd/m/Y', 'm/d/Y');
		if(isset($data['departureDate']) && $data['departureDate'] != "") $params ['departureDate'] = $this->date_conv(trim($data['departureDate']), 'd/m/Y', 'm/d/Y');
		
		
		if(isset($data['supplierType']) && $data['supplierType'] != "") $params ['supplierType'] = trim($data['supplierType']);
		if(isset($data['rateKey']) && $data['rateKey'] != "") $params ['rateKey'] = trim($data['rateKey']);
				
		if(isset($data['numberOfBedRooms']) && intval($data['numberOfBedRooms']) > 0) {
			$params ['numberOfBedRooms'] = intval($data['numberOfBedRooms']);
			
			if(isset($data['RoomGroup']) && count($data['RoomGroup']) > 0) {
				foreach ($data['RoomGroup'] as $i=>$room) {
					$room_val = intval($room['numberOfAdults']);
					if(intval($room['numberOfChildren']) > 0) {
						if(is_array($room['childAges'])) $room_val .= ',' . implode(",", $room['childAges']);
					}
					$params['room' . ($i+1)] = $room_val;
				}
			}
			
		}
		
		//echo '<pre>', var_export($params, true), '</pre>';
		
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('HotelAvailability', $url, $params_str);
		
	}
	
	
	public function get_hotels_availability($hotelIdList_array, $data = array()) {
		if($this->customerSessionId == '') {		
			$ping_response = json_decode($this->ean_ping(), true);
			$this->customerSessionId = $ping_response[0]['customerSessionId'];
		}
		
		$this->numberOfResults = count($hotelIdList_array);
		
		$url = $this->protocol . '://' . 'api.ean.com/ean-services/rs/hotel/v3/list' . '?';
		
		$delete_params = array(
			"countryCode"
			//, "useCache"
			, "customerUserAgent"
			, "customerIpAddress"
			, "protocol"
			//, "supplierCacheTolerance"
		);
		
		
		$params = array();
		foreach ($this as $p=>$v) {
			if(!is_array($v) && $v != '') {
				if(!in_array($p, $delete_params)) {
					$params[$p] = $v;
				}
			}
		}
		
		$params ['numberOfResults'] = count($hotelIdList_array);
		$params ['hotelIdList']	= implode(",", $hotelIdList_array);
		//$params ['maxRatePlanCount'] = 1;

		if(isset($data['arrivalDate']) && $data['arrivalDate'] != "") $params ['arrivalDate'] = $this->date_conv(trim($data['arrivalDate']), 'd/m/Y', 'm/d/Y');
		if(isset($data['departureDate']) && $data['departureDate'] != "") $params ['departureDate'] = $this->date_conv(trim($data['departureDate']), 'd/m/Y', 'm/d/Y');
		
		
		//if(isset($data['supplierType']) && $data['supplierType'] != "") $params ['supplierType'] = trim($data['supplierType']);
		//if(isset($data['rateKey']) && $data['rateKey'] != "") $params ['rateKey'] = trim($data['rateKey']);
				
		if(isset($data['numberOfBedRooms']) && intval($data['numberOfBedRooms']) > 0) {
			$params ['numberOfBedRooms'] = intval($data['numberOfBedRooms']);
			
			if(isset($data['RoomGroup']) && count($data['RoomGroup']) > 0) {
				foreach ($data['RoomGroup'] as $i=>$room) {
					$room_val = intval($room['numberOfAdults']);
					if(intval($room['numberOfChildren']) > 0) {
						if(is_array($room['childAges'])) $room_val .= ',' . implode(",", $room['childAges']);
					}
					$params['room' . ($i+1)] = $room_val;
				}
			}
			
		}
		
		//echo '<pre>', var_export($params, true), '</pre>';
		
		
		$params_str = http_build_query($params, '&amp;');
		
		return $this->ean_request('HotelsAvailability', $url, $params_str);
		
	}
	
	
	private function ean_request($rq_type, $url, $post_data) {
		//echo '<br/>', $rq_type;
		//echo '<br/>', $url;
		//echo '<br/>', $post_data;
		
		$post_types = array(
			"HotelList", "HotelsAvailability"
		);
		
		$get_types = array(
			"PingRequest", "HotelAvailability" 
		);
		
		$curl = curl_init();
		
		if(in_array($rq_type, $post_types)) {
			
			curl_setopt($curl,CURLOPT_URL, $url);
			curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curl,CURLOPT_ENCODING, "gzip");
			curl_setopt($curl,CURLOPT_TIMEOUT, 30);
			curl_setopt($curl,CURLOPT_POST, true);
			curl_setopt($curl,CURLOPT_POSTFIELDS, $post_data);
			curl_setopt($curl,CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded', 'Accept: application/json'));
		}
		else {
			$url = $url . $post_data;
			curl_setopt($curl,CURLOPT_URL, $url);
			curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curl,CURLOPT_ENCODING, "gzip");
			curl_setopt($curl,CURLOPT_TIMEOUT, 30);
			curl_setopt($curl,CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded', 'Accept: application/json'));
		}

		$response = trim(curl_exec($curl));
		
		if(curl_errno($curl)) {
			echo '<pre>', var_dump($response), '</pre>';
			echo '<pre>', curl_errno($curl), ':', var_export(curl_error($curl)) . '</pre>';
		}
		
		curl_close($curl);
		
		return $response;
	}
	
	public function set_protocol($protocol) {
		$this->protocol = $protocol;
	}
	
}

/*

$init = array(
	"cid"		=> 55505,
	"apiKey"	=> "7zs3uc7cdmhsc8phjwnd9nug"
);

$e = new ean_rest_api($init);

$cy_hotels = array();
$cy_hotels_repeat = array();

$cy_locations = array('Nicosia', 'Limassol', 'Larnaca', 'Paphos', 'Ayia Napa', 'Protaras', 'Famagusta');

foreach ($cy_locations as $city) {
	$ret = $e->get_hotels_by_city($city);
	$json = json_decode($ret, true);
	$tmp = $json['HotelListResponse']['HotelList']['HotelSummary'];
	foreach ($tmp as $i=>$h) {
		
		$hotelId = $h['hotelId'];
		if(!isset($cy_hotels_repeat[$hotelId])) {
			$cy_hotels_repeat[$hotelId] = array(
				"$city" => 1
			);
		}
		else {
			if(isset($cy_hotels_repeat[$hotelId][$city])) $cy_hotels_repeat[$hotelId][$city] += 1;
			else $cy_hotels_repeat[$hotelId][$city] = 1;
		}
		
		$cy_hotels [$hotelId] = $h;
		
		
		//die();
		
	}
}

echo "<br/><strong>All Hotels:</strong>" . count($cy_hotels);
echo "<br/><strong>Unique Hotels:</strong>" . count($cy_hotels_repeat);

foreach ($cy_hotels as $hotelId=>$h) {
	$hotel = array();
	$hotel_keys = array();
	foreach ($h as $kk=>$kv) {
		if($kk != "@order") {
			$hotel_keys [] = "`" . $kk . "`";
			$hotel[] = "'" . mysql_real_escape_string(trim(stripslashes(html_entity_decode ($kv)))) . "'";
		}
	}
	
	
	$q = "insert into cy_hotels_expedia (".implode(", ", $hotel_keys).") values (".implode(", ", $hotel).");";
	echo "<br/>" . $q;
	
	$r = mysql_query($q) or die("<pre><strong>$q</strong></pre>".mysql_error());
}


//echo '<pre>', var_export($cy_hotels, true), '</pre>';
//echo '<pre>', var_export($cy_hotels_repeat, true), '</pre>';
*/
?>