<?php 
	class Calendarista_FeedHandler
	{
		public $appKey;
		public $projectId;
		public $availabilities;
		public $status;
		public function __construct(){
			$this->appKey = isset($_GET['calendarista_appkey']) ? sanitize_text_field($_GET['calendarista_appkey']) : null;
			$this->projectId = isset($_GET['calendarista_service']) ? (int)$_GET['calendarista_service'] : null;
			$this->availabilities = isset($_GET['calendarista_availability']) ? array((int)$_GET['calendarista_availability']) : null;
			$this->status = (isset($_GET['calendarista_status']) && trim($_GET['calendarista_status']) != '') ? (int)$_GET['calendarista_status'] : -1;
		}
		public function render(){
			$repo = new Calendarista_BookedAvailabilityRepository();
			$today = new Calendarista_DateTime();
			$result = $repo->readAll(array(
				'projectId'=>$this->projectId
				, 'availabilities'=>$this->availabilities
				, 'toDate'=>$today->format(CALENDARISTA_FULL_DATEFORMAT)
				, 'syncDataFilter'=>1/*exclude synced data*/
			));
			$events = array();
			$serverTimezone = null;
			if($result){
				foreach($result['resultset'] as $r){
					if($this->status !== -1 && (int)$r['status'] !== $this->status){
						continue;
					}
					$dtend = $r['toDate'] ? new Calendarista_DateTime($r['toDate']) : new Calendarista_DateTime($r['fromDate']);
					$dtstart = new Calendarista_DateTime($r['fromDate']);
					$calendarMode = (int)$r['calendarMode'];
					$geo = null;
					if($r['regionLat'] && $r['regionLng']){
						$geo = $r['regionLat'] . ';' . $r['regionLng'];
					}
					$fullDay = !in_array($calendarMode, Calendarista_CalendarMode::$SUPPORTS_TIMESLOTS);
					$dtEndKey = $fullDay ? 'dtend;value=date' : 'dtend;value=date-time';
					$dtStartKey = $fullDay ? 'dtstart;value=date' : 'dtstart;value=date-time';
					$ics = new Calendarista_ICSWriterHelper(array(
						$dtEndKey=>$dtend
						, $dtStartKey=>$dtstart
						, 'summary'=>$r['fullName'] . ' (' . Calendarista_FeedHelper::trimString($r['fullName'], $r['availabilityName']) . ')'
						, 'description'=>$this->getBookingDescription($r)
						, 'location'=>$r['regionAddress']
						, 'geo'=>$geo
						, 'uid'=>sprintf('%s%d@calendarista.com', $this->appKey, $r['orderId'])
						, 'seats'=>$r['seats']
					), $fullDay);
					array_push($events, $ics->to_string());
				}
			}
			return Calendarista_ICSWriterHelper::to_calendar($events);
		}
		protected function getBookingDescription($booking){
			$description = array();
			$orderId = (int)$booking['orderId'];
			array_push($description, sprintf('%s: %s', __('Name', 'calendarista'), $booking['fullName']));
			array_push($description, sprintf('%s: %s', __('Email', 'calendarista'), $booking['email']));
			array_push($description, sprintf('%s: %s', __('Service', 'calendarista'), $booking['projectName']));
			array_push($description, sprintf('%s: %s', __('Availability', 'calendarista'), $booking['availabilityName']));
			array_push($description, sprintf('%s: %s', __('Seats', 'calendarista'), $booking['seats']));
			$optionals = Calendarista_GoogleCalendarHelper::getOptionals($orderId);
			if($optionals){
				array_push($description, $optionals);
			}
			$customFormFields = Calendarista_GoogleCalendarHelper::getCustomFormElements($orderId);
			if($customFormFields){
				array_push($description, $customFormFields);
			}
			$dynamicFields = Calendarista_GoogleCalendarHelper::getDynamicFields($orderId);
			if($dynamicFields){
				array_push($description, $dynamicFields);
			}
			$providerName = Calendarista_GoogleCalendarHelper::getServiceProviderName((int)$booking['availabilityId']);
			if($providerName){
				array_push($description, $providerName);
			}
			$map = Calendarista_GoogleCalendarHelper::getMap($orderId, (int)$booking['projectId']);
			if($map){
				$description = array_merge($description, $map);
			}
			return $this->linefold('DESCRIPTION:', join("\\n", $description));
		}
		function linefold($preamble, $value) {
		  $value = trim($value);
		  $value = strip_tags($value);
		  $value = preg_replace('/\n+/', ' ', $value);
		  $value = preg_replace('/\s{2,}/', ' ', $value);

		  $preamble_len = strlen($preamble);

		  $lines = array();
		  while (strlen($value)>(75-$preamble_len)) {
			$space = (75-$preamble_len);
			$mbcc = $space;
			while ($mbcc) {
			  $line = mb_substr($value, 0, $mbcc);
			  $oct = strlen($line);
			  if ($oct > $space) {
				$mbcc -= $oct-$space;
			  }
			  else {
				$lines[] = $line;
				$preamble_len = 1; // Still take the tab into account
				$value = mb_substr($value, $mbcc);
				break;
			  }
			}
		  }
		  if (!empty($value)) {
			$lines[] = $value;
		  }

		  return implode("\n\t", $lines);
		}
		protected function getStatus($status){
			switch ($event['status']){
				case 0:
					return 'TENTATIVE';
				break;
				case 1:
					return 'CONFIRMED';
				break;
				default:
					return 'CANCELLED';
			}
		}
	}
?>
