<?php
require_once(SABLE_WORKING_PATH.'/booking/booking.php');

$_SESSION['calendar_anchor'] = '#event_items'; //let the page scroll to the event items immediately
$_SESSION['calendar_page'] = 'booking/index.php';//SABLE_THEME_ROOT.'events.php';

function getDisplayDate($eventDate)
{
	return $eventDate->format('l, d F Y');
}

function printDisplayDate($eventDate)
{
	echo(getDisplayDate($eventDate));
}

function buildEventsTable($month, $day, $style, $calendar)
{
	$tmparr = reorderEvents($calendar);
	//there are max 12 event types that can fit into one day 'block':
	$mm = sprintf('%02d', intval($month));
	$dd = sprintf('%02d', intval($day));
					
	$table = "<td ".$style.">
	<table cellpadding='0' cellspacing='0' border='0' class='calendar_events'>
		<tr>
			<td>".$tmparr[$mm][$dd][0]."</td>
			<td>".$tmparr[$mm][$dd][1]."</td>
			<td>".$tmparr[$mm][$dd][2]."</td>
			<td>".$day."</td>
		</tr>
		<tr>
			<td>".$tmparr[$mm][$dd][3]."</td>
			<td>".$tmparr[$mm][$dd][4]."</td>
			<td>".$tmparr[$mm][$dd][5]."</td>
			<td>".$tmparr[$mm][$dd][6]."</td>
		</tr>
		<tr>
			<td>".$tmparr[$mm][$dd][7]."</td>
			<td>".$tmparr[$mm][$dd][8]."</td>
			<td>".$tmparr[$mm][$dd][9]."</td>
			<td>".$tmparr[$mm][$dd][10]."</td>
		</tr>		
	</table>
	</td>";
	return $table;
}

function getLink($eventDate)
{
	$mlink = $_SESSION['calendar_page']; //SABLE_URL_ROOT.'event/calendar.php';
	if (SABLE_SEO_ENABLED)
		$link = $_SESSION['calendar_page'].'/'.$eventDate->format('d').'/'.$eventDate->format('m').'/'.$eventDate->format('Y').'/event-calendar/';
	else
		$link = 
		SableSystem::getParameterLink('booking', 'index.php', $eventDate->format('d').'+'.$eventDate->format('m').'+'.$eventDate->format('Y'));
//		$link = SableSystem::getCallPageLink($mlink.'+'.$dd.'+'.$mm.'+'.$yy);
	if (isset($_SESSION['calendar_anchor']) && !empty($_SESSION['calendar_anchor'])) $link .= $_SESSION['calendar_anchor'];
	return $link;
}

function printLink($eventDate)
{
	echo(getLink($eventDate));
}

function reorderEvents($eventsArray)
{
	/**
		The array of events we get here are keyed by the event_type_id so that we only show 1 icon of each
		type available. This function changes the key of the event_type_id to an ordered number list starting
		at zero.
		The only reason we do this is to display the icons in sequential segments within the calendar's day block - 
		this is purely aesthetic - don't use reorderEvents on a calendar array that is used as a functional calendar.
	**/
	$orderedEvents = array();
	if ($eventsArray)
	{
		foreach($eventsArray as $mKey=>$month)
		{
			foreach($month as $dKey=>$day)
			{
				foreach($day as $iKey=>$icon)
				{
					$orderedEvents[$mKey][$dKey][] = $icon;
				}
			}
		}
	}
	return $orderedEvents;
}

function getDayData($eventDate)
{
	//we want to get the events for the month before and after the date given so we can show event icons for our "off" fields
	global $sableDB;
	
	/**
	booking_time, client_full_name, building_notes, 
	**/
	$sqlPfx = 	"select booking_id, booking_time, concat(client_name, ' ', client_surname) as client_full_name
				from booking 
				inner join client on client.client_id = booking.client_id ";
	$sql = $sqlPfx."where (booking_date = '".$eventDate->format('Y-m-d')."') and (sa_id is null) order by booking_date ASC";
	$srows = $sableDB->getRows($sql);
	
	//here we also need to get all of the recurring booking details to display:
	$calendar 	= getRecurringEvents($eventDate);
	$books		= $calendar[$eventDate->format('m')][$eventDate->format('d')];
	
	$rrows = [];
	if ($books)
	{
		foreach($books as $bid=>$day)
		{
			$rrows[] = $sableDB->getRow($sqlPfx.' where booking.booking_id = '.$bid);
		}
	}
	
	$rows = array_merge($rrows, $srows);
	
	$ret = [];
	foreach($rows as $row)
	{
		$tmp = [];
		$tmp['booking_id']		= $row['booking_id'];
		$tmp['booking_time']	= $row['booking_time'];
		$tmp['client_full_name']= $row['client_full_name'];
		$tmp['service_info']	= [];		
		$sql = 'select area_type_name, area_name, building_name, building_notes, building_notes, service_name, service_price, service_duration
				from booking__service 
				inner join building on building.building_id = booking__service.building_id 
				inner join area on area.area_id = building.area_id 
				inner join area_type on area_type.area_id = area.area_id 
				inner join service on service.service_id = booking__service.service_id 
				where booking_id = '.$row['booking_id'];
		$retrows = $sableDB->getRows($sql);
		$tmp['service_info'] = $retrows;
		$ret[] = $tmp;
	}

	return $ret;
}

function getMonthData($eventDate)
{
	//we want to get the events for the month before and after the date given so we can show event icons for our "off" fields
	global $sableDB;
	
	$tscurrent	= clone $eventDate;
	$tsbefore	= $tscurrent->modify('-1 Month');
	$tsafter	= $tscurrent->modify('+1 Month');
	
	$sql = "select booking.*, concat(client_name, ' ', client_surname) as client_full_name
			from booking 
			inner join client on client.client_id = booking.client_id 
			where (sa_id is null) and 
			(
				(booking_date like '".$tsbefore->format('Y-m')."%')  or 
				(booking_date like '".$tscurrent->format('Y-m')."%') or 
				(booking_date like '".$tsafter->format('Y-m')."%')
			)
			order by booking_date ASC";
	
	return $sableDB->getRows($sql);
}

function getEvents($eventDate)
{
	$rows = getMonthData($eventDate);
	foreach($rows as $row) //	for ($y = 0; $y < $cnt; $y++)
	{
		$dbdt = new DateTime($row['booking_date']);
		$dbd = $dbdt->format('d');
		$dbm = $dbdt->format('m');
		$calendar[$dbm][$dbd][$row['booking_id']] = '<i class="fa fa-square" title="'.$row['client_full_name'].'"></i>';
	}
	//return reorderEvents($calendar);
	return $calendar;
}

function getRecurringEvents($eventDate)
{
	global $sableDB;
	$_booking = new Booking;
	$sql = 'select *, concat(client_name, " ", client_surname) as client_full_name
			from standing_appointment 
			inner join booking on booking.sa_id = standing_appointment.sa_id 
			inner join client on client.client_id = booking.client_id 
			where (booking_repeats = 1) and (sa_active = 1)';
	$rows = $sableDB->getRows($sql);
	
	$idx  = 0;
	
	foreach($rows as $row)
	{
		$startDate		= $row['sa_date']; //create date
		$occurs 		= $row['sa_occurrence']; //edtDayNumber
		$occType 		= $row['sa_occ_type']; //1=day, 2=week, 3=month
		$monthType 		= $row['sa_month_type']; //dom or dow - only applicable if $occType = 3 (Month)
		$monthTypeOcc	= $row['sa_month_dow_occ']; //e.g. 1st Tuesday - only applicable if $monthType = 2 (dow)
		
		$monthTypeOccWord = "";
		switch ($monthTypeOcc)
		{
			case 1:	{$monthTypeOccWord = "first";	break;}
			case 2:	{$monthTypeOccWord = "second";	break;}
			case 3:	{$monthTypeOccWord = "third";	break;}
			case 4:	{$monthTypeOccWord = "fourth";	break;}
			default:{$monthTypeOccWord = "last";	break;}
		}
		
		$startts 	= new DateTime($startDate);
		$eventts 	= clone $eventDate;
		$process	= true; //do we use this date?
		
		if ($eventts >= $startts)
		{
			$numDays	= $eventts->format('t'); 	//number of days in the given timestamp's month - e.g. 30 (June for example)
			$startDay	= $startts->format('d'); 	//the day on which the recurring appointment starts - e.g. 6th June
			/**
			check the current event date against the standing appointment start date. Any day before the the sa_date should not be
			displayed on the calendar, only from that day forward, infinitely.
			**/
			
			if ($startts->format('Y-m') === $eventDate->format('Y-m'))
			{
				$chksd		= intval($startts->format('d'));
				$chked		= intval($eventDate->format('d'));
				$process	= $chked >= $chksd;
			} 
			else 
			{
				$startDay	= 0; //indicates we need to find the correct start day.
			}
			$process = true;
			
			if ($process)
			{
				switch ($occType)
				{
					case 1: //Day
					{
						$recurts = clone $startts; //sa_date
						if (!$startDay)
						{
							/*
							Find the correct start day for this month. For example if we have a standing appointment that occurs
							every 3 days, and starts on 6 June 2021, then the last occurrence of this repeat for June will be on 30th June, 
							thereafter it begins again on July 3rd, so $startDay must be 3 *NOT* 1.
							*/
							
							$workingDate = clone $eventDate; //where we currently are on the calendar
							$workingDate->setDate($eventDate->format('Y'), $eventDate->format('m'), 1);
							while ($recurts < $workingDate)
							{
								$recurts->modify('+'.$occurs.' days');
							}
							$startDay	= $recurts->format('d');
						}
						/*
						if $occurs = 2 then this means the appointment is for every 2 days. 
						So starting on the 6th it would occur on the 8th, 10th, 12th, and so. Each day we need to check if it's a Sunday or public 
						holiday, and if so, ignore that day.
						*/
						$idx		= 0;
						$cday		= $startDay;
						$recurts->setDate($eventDate->format('Y'), $eventDate->format('m'), $startDay);
						$dbd		= $recurts->format('d');
						$dbm		= $recurts->format('m');
						for ($i = $startDay; $i < $numDays; $i++)
						{
							$paramDate  = clone $recurts;
							$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
							unset($paramDate);
							$title		= $conflicted ? $conflicted : $row['client_full_name'];
							$class		= $conflicted ? "fa-exclamation-circle error" : "fa-sync-alt";
							$dd			= sprintf('%02d', $cday);
							$calendar[$dbm][$dd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';

							$cday += $occurs;
							//$recurts->setDate($startts->format('Y'), $startts->format('m'), $cday);
							$recurts->modify('+'.$occurs.' days');
							$dbd = $recurts->format('d');
							$dbm = $recurts->format('m');
							if ($cday > $numDays) break;
						}
						break;
					}
					case 2: //Week
					{						
						$recurts = clone $startts; //sa_date

						$sql = 'select standing_appointment__dow.dow_id, dow_long
								from standing_appointment__dow 
								inner join dow on dow.dow_id = standing_appointment__dow.dow_id
								where sa_id = '.$row['sa_id'].' 
								order by standing_appointment__dow.dow_id';
						$rowsdow = $sableDB->getRows($sql);
						
						$workingDate	= clone $recurts; //based on the standing appointment's start date
						$startDay		= $recurts->format('d');
						$workingDate->setDate($recurts->format('Y'), $recurts->format('m'), $startDay);
						
						foreach($rowsdow as $rowdow)
						{
							$i = 0;
							$workingDate->setDate($recurts->format('Y'), $recurts->format('m'), $startDay);
							do
							{
								SableDebug::debug($workingDate);
								$tmp = 'next '.$rowdow['dow_long'].' +'.$occurs.' weeks';
								$workingDate->modify($tmp);
								SableDebug::debug($workingDate);
								/*
								$roll = ($workingDate->format('m') < $eventDate->format('m')) || 
										($workingDate->format('Y') < $eventDate->format('Y'));
								*/
								$roll = $workingDate <= $eventDate;
								$paramDate = clone $workingDate;
								$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
								unset($paramDate);
								$title		= $conflicted ? $conflicted : $row['client_full_name'];
								$class		= $conflicted ? "fa-exclamation-circle error" : "fa-sync-alt";
								$dbd		= $workingDate->format('d');
								$dbm		= $workingDate->format('m');								
								$calendar[$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';
								$i++;
								if ($i > 2000) break; //safety measure								
							} while ($roll);
						}	
						break;
					}
					case 3: //month
					{
						if ($monthType == 2) //DOW
						{
							$sql = 'select standing_appointment__dow.dow_id, dow_long
									from standing_appointment__dow 
									inner join dow on dow.dow_id = standing_appointment__dow.dow_id
									where sa_id = '.$row['sa_id'].' 
									order by standing_appointment__dow.dow_id 
									limit 0,1';

							$rowdow	= $sableDB->getRow($sql);
							$sz = !empty($rowdow) && is_array($rowdow) ? sizeof($rowdow)-1 : 0;
							$lastdow = $rowdow[$sz]['dow_id']-1; //the db entry is 4, subtract 1 to get 3 = Wednesday

							$recurts = clone $startts; //sa_date
							/*
							Find the correct start day for this month. For example if we have a standing appointment that occurs
							every 3 weeks on a Tuesday & Thursday, and starts on 6 June 2021, then the last occurrence of this repeat 
							for June will be on 30th June, 
							thereafter it begins again on July 3rd, so $startDay must be 3 *NOT* 1.
							*/
							$recurts->setDate($eventDate->format('Y'), $eventDate->format('m'), 1);

							$idx = 0;
							while ($recurts < $eventDate) 
							{
								$tmp = $monthTypeOccWord.' '.$rowdow['dow_long'].' of '.$eventDate->format('F').' '.$eventDate->format('Y');
								$recurts->modify($monthTypeOccWord.' '.$rowdow['dow_long'].' of '.$eventDate->format('F').' '.$eventDate->format('Y'));
								$idx++;
								if ($idx > 50) break; //safety measure.
							}
							$startDay	= $recurts->format('d');

							$idx		= 0;
							$cday		= 1; //$startDay;

							$dbd		= $recurts->format('d');
							$dbm		= $recurts->format('m');
							$break		= false;
							$workingDate = clone $eventDate; //where we currently are on the calendar

							$sql = 'select standing_appointment__dow.dow_id, dow_long
									from standing_appointment__dow 
									inner join dow on dow.dow_id = standing_appointment__dow.dow_id
									where sa_id = '.$row['sa_id'].' 
									order by standing_appointment__dow.dow_id';
							$rowsdow = $sableDB->getRows($sql);
							$workingDate->setDate($eventDate->format('Y'), $eventDate->format('m'), $cday);
							foreach($rowsdow as $rowdow)
							{
								$workingDate->modify($monthTypeOccWord.' '.$rowdow['dow_long'].' of '.$eventDate->format('F').' '.$eventDate->format('Y'));
								$paramDate = clone $workingDate;
								$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
								unset($paramDate);
								$title		= $conflicted ? $conflicted : $row['client_full_name'];
								$class		= $conflicted ? "fa-exclamation-circle error" : "fa-sync-alt";
								$dbd		= $workingDate->format('d');
								$dbm		= $workingDate->format('m');								
								$calendar[$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';
								$workingDate->setDate($eventDate->format('Y'), $eventDate->format('m'), $cday); //reset for each dow
							}
							$cday += $dbd;
							if (($cday > $numDays) || ($workingDate->format('m') !== $recurts->format('m'))) break;
						}
						else //DOM
						{
							$sql = 'select standing_appointment__dom.dom_id, dom_no, dom_desc
									from standing_appointment__dom 
									inner join dom on dom.dom_id = standing_appointment__dom.dom_id
									where sa_id = '.$row['sa_id'];

							$rowdoms = $sableDB->getRows($sql);
							$recurts = clone $startts; //sa_date
							foreach ($rowdoms as $rowdom) 
							{
								$dom = intval($rowdom['dom_no']);
								if ($dom > $numDays)
									$recurts->modify('last day of '.$eventDate->format('F'));
								else
									$recurts->setDate($eventDate->format('Y'), $eventDate->format('m'), $dom);
								$paramDate = clone $recurts;
								$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
								unset($paramDate);
								$title		= $conflicted ? $conflicted : $row['client_full_name'];
								$class		= $conflicted ? "fa-exclamation-circle error" : "fa-sync-alt";
								$dbd		= $recurts->format('d');
								$dbm		= $recurts->format('m');								
								$calendar[$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';	
							}
						}
						break;
					}
				}
			}
		}
	}
	unset($_booking);
	//return reorderEvents($calendar);
	return $calendar;
}

function combineArrays($ar1, $ar2)
{
	/**
	Array
	(
		[06] => Array
			(
				[14] => Array
					(
						[2] => 
					)

			)

	)
	Array
	(
		[06] => Array
			(
				[14] => Array
					(
						[4] => 
					)

				[11] => Array
					(
						[4] => 
					)

			)

	)
	**/
	$ok1 = $ar1 && is_array($ar1);
	$ok2 = $ar2 && is_array($ar2);
	
	if ($ok1 && $ok2)
	{
		$sz1 = sizeof($ar1);
		$sz2 = sizeof($ar2);
		
		$mainarray	= $sz1 > $sz2 ? $ar1 : $ar2;
		$subarray	= $sz1 > $sz2 ? $ar2 : $ar1;
		
		foreach($mainarray as $mkey=>$month) //for each month
		{
			foreach($month as $dkey=>$days)
			{
				if (is_array($subarray[$mkey][$dkey]))
				{
					foreach($subarray[$mkey][$dkey] as $idkey=>$id)
					{
						$mainarray[$mkey][$dkey][$idkey] = $id;
					}
				}
			}
		}
		return $mainarray;
	}
	elseif ($ok1)
	{
		$sz1 = sizeof($ar1);
		if ($sz1) return $ar1; else return [];
	}
	elseif($ok2)
	{
		$sz2 = sizeof($ar2);
		if ($sz2) return $sz2; else return [];
	}
}

function printCalendar($eventDate, $field_id)
{
	$singleBookings	= getEvents($eventDate);
	$recurBookings	= getRecurringEvents($eventDate);
	
	$sbok = $singleBookings && is_array($singleBookings[$eventDate->format('m')]);
	$rbok = $recurBookings  && is_array($recurBookings [$eventDate->format('m')]);
	
	if ($sbok && $rbok)
	{
		//$calendar[$eventDate->format('m')] = $singleBookings[$eventDate->format('m')] + $recurBookings[$eventDate->format('m')];
		$calendar = combineArrays($singleBookings, $recurBookings);
	}
	elseif ($sbok)
	{
		$calendar[$eventDate->format('m')] = $singleBookings[$eventDate->format('m')];
	}
	elseif ($rbok)
	{
		$calendar[$eventDate->format('m')] = $recurBookings[$eventDate->format('m')];
	}

	$prevDate = clone $eventDate;
	$nextDate = clone $eventDate;
	$prevDate->modify('-1 month');
	$nextDate->modify('+1 month');
	
	$td_head_style = "class='calendar_heading'"; 
	$td_cal_style = "class='calendar_style'";

	$table = "<table border='0' class='calendar_table'>";
	/**
	$table .= "	<tr>
					<td class='pointer' onclick='window.location = \"".getLink($prevDate)."\"'>
						<i class='fa fa-arrow-left fa-3x' title='".getDisplayDate($prevDate)."'></i>
					</td>
					<td colspan='5' class='heading3'>".getDisplayDate($eventDate)."</td>
					<td align='right' class='pointer' onclick='window.location = \"".getLink($nextDate)."\"'>
						<i class='fa fa-arrow-right fa-3x' title='".getDisplayDate($nextDate)."'></i>
					</td>
				</tr>";
	
	
	//Add a toolbar in here:
	$params = null;
	$addClick = 'window.location = \''.SableSystem::getParameterLink('booking', "add.php", $params, false).'\'';
	$viewClick = 'window.location = \''.SableSystem::getSableLinkPath('booking/list.php').'\'';
	$table .= "	<tr class='forms-grid'>
					<td colspan='2'>
						<button type='button' onclick=\"".$addClick."\"><i class='fa fa-plus'></i>&nbsp;Add Booking</button>
					</td>
					<td colspan='2'>
						<button type='button' onclick=\"".$viewClick."\"><i class='fa fa-eye'></i>&nbsp;View All</button>
					</td>
					<td colspan='3'>
					</td>					
				</tr>";
	**/
	
	$table .= "	<tr>";
	$table .= "		<td ".$td_head_style.">Sun</td>";
	$table .= "		<td ".$td_head_style.">Mon</td>";
	$table .= "		<td ".$td_head_style.">Tue</td>";
	$table .= "		<td ".$td_head_style.">Wed</td>";
	$table .= "		<td ".$td_head_style.">Thu</td>";
	$table .= "		<td ".$td_head_style.">Fri</td>";
	$table .= "		<td ".$td_head_style.">Sat</td>";
	$table .= "	</tr>";

	$moved = false;
	
	$selected_day 	= $eventDate->format('d'); //keep this day to highlight the current date
	$cdate 			= new DateTime();
	$day 	= 1;
	$cdate->setDate($eventDate->format('Y'), $eventDate->format('m'), $day);
	$month 	= $cdate->format('m');
	$year 	= $cdate->format('Y');
	$max 	= $cdate->format('t');
	
	//any days from the previous month that displays on our current calendar before the 1st DOM
	$prevDate->setDate($prevDate->format('Y'), $prevDate->format('m'), $prevDate->format('t'));

	//any days from the next month that displays on our current calendar after the last DOM
	$nextDate->setDate($nextDate->format('Y'), $nextDate->format('m'), 1); 	
	
	for ($i=0; $i<7; $i++) //number of columns
	{
		$table 		.= "<tr>";
		for ($x=0; $x<=6; $x++) // For each day of the week
		{
			$week_day = $cdate->format('w'); //weekday,  0 = Sunday.. 6 = Monday
			if ($week_day == $x)
			{
				if ($week_day == 0) //Sunday
					$action = "alert(\"Please be aware you have selected a Sunday.\"); ";
				else
				{
					//check if this is a public holiday:
					$_booking	= new Booking;
					$paramDate	= clone $eventDate;
					$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
					unset($paramDate);
					unset($_booking);
					if ($conflicted) 
						$action = "alert(\"Please be aware you have selected a Public Holiday.\"); ";
					else
						$action = "";
				}
				
				//$cdate->modify('+1 day');
				$action .= "window.location = \"".getLink($cdate)."\"";
				if ($day == $selected_day)
				{
					$td_cal_style = " class='calendar_day_select pointer' onclick='".$action."'";
					$selected_day=0; //so that we don't repeat this on the calendar
				}
				else
				{
					if (!$moved)
						$td_cal_style = " class='calendar_day pointer' onclick='".$action."'";
					else
						$td_cal_style = " class='calendar_off_month pointer' onclick='".$action."'";
				}
				
				if ($day > $max)
				{
					$td_cal_style = " class='calendar_off_month pointer' onclick='".$action."'";
					$day = 1; //reset for the next month
					$month++;
					if ($month > 12)
					{
						$month = 1;
						$year++;
					}
					$moved = true; //to the next month
				}
				$table .= buildEventsTable($month, $day, $td_cal_style, $calendar);
				$day++;
			}
			else
			{
				if ($week_day > $x) //MISSING YEAR ON CALENDAR ARRAY TO MAKE THIS WORK!!!
				{
					$val = $prevDate->format('d');
					$cdate->setDate($prevDate->format('Y'), $prevDate->format('m'), $prevDate->format('d'));//days before the 1st of this month
					$prevDate->modify('-1 day');
				}
				elseif ($week_day < $x)
				{
					$val = $nextDate->format('d');
					$cdate->setDate($nextDate->format('Y'), $nextDate->format('m'), $nextDate->format('d'));//days before the 1st of this month
					$nextDate->modify('+1 day');
				}
					
				$action = "window.location = \"".getLink($cdate)."\"";
				$td_cal_style = " class='calendar_off_month pointer' onclick='".$action."'";	
				$table .= buildEventsTable($cdate->format('m'), $val, $td_cal_style, $calendar);
				//$val++;
			}

			$cdate->setDate($year, $month, $day);
			
		}
		$table .= "</tr>";
	}
	$table .= "</table>";
	echo($table);
}

function printDayBookings($eventDate, $field_id)
{
	$rows = getDayData($eventDate);
	/**
	Array
	(
		[0] => Array
			(
				[booking_id] => 1
				[booking_time] => 
				[client_name] => Marietjie van Gerve
				[service_info] => Array
					(
						[0] => Array
							(
								[area_type_name] => Dog
								[area_name] => Yorkshire Terrier
								[building_name] => Noah
								[building_notes] => 2017-01-31
								[building_notes] => 
								[service_name] => Groom (Large Dog)
								[service_price] => 280
								[service_duration] => 30
							)

						[1] => Array
							(
								[area_type_name] => Dog
								[area_name] => Yorkshire Terrier
								[building_name] => Melina
								[building_notes] => 2018-12-10
								[building_notes] => 
								[service_name] => Groom (Large Dog)
								[service_price] => 280
								[service_duration] => 30
							)

						[2] => Array
							(
								[area_type_name] => Dog
								[area_name] => Yorkshire Terrier
								[building_name] => Mitzi
								[building_notes] => 2020-04-09
								[building_notes] => Needs to be lightly sedated.
								[service_name] => Groom (Large Dog)
								[service_price] => 280
								[service_duration] => 30
							)

					)

			)

		[1] => Array
			(
				[booking_id] => 3
				[booking_time] => 
				[client_name] => Jason Pieterse 
				[service_info] => Array
					(
						[0] => Array
							(
								[area_type_name] => Dog
								[area_name] => Yorkshire Terrier
								[building_name] => Noah
								[building_notes] => 2017-01-31
								[building_notes] => 
								[service_name] => Groom (Large Dog)
								[service_price] => 280
								[service_duration] => 30
							)

					)

			)

	)	
	**/
	$html ="<table style='width:100%;' class='calendar_table text-left'>
				<tr><td colspan='2'><p style='height:6.5em;'></p></td></tr>";
	$x = 0;
	if (empty($rows))
	{
		$html .= "<tr>";
		$html .= "	<td colspan='3'>";
		$html .= "		<h3 class='title'>No events for ".getDisplayDate($eventDate)."</h3>";
		$html .= "	</td>";
		$html .= "</tr>";
	}
	else
	{
		$html .='<tr>
					<td class="booking_heading" style="width:15%">Client</td>
					<td class="booking_heading" style="width:85%">Buildings</td>
				</tr>';
		$ci = true;
		$ic = true;
		foreach($rows as $row)
		{
			
			$ci = !$ci;
			$cls = $ci ? 'booking_info_alt' : 'booking_info';			
			$html.="<tr>
						<td class='".$cls." calendar_day'>".$row['client_full_name']."</td>
						<td class='".$cls." calendar_day'>
							<table style='width:100%;'>";
			
			
			foreach($row['service_info'] as $serv)
			{
				$ic = !$ic;
				$cli = $ic ? 'service_info_alt' : 'service_info';
				$html.="			<tr><td class='".$cli." service_info_label'>Name:</td><td class='".$cli."'>".$serv['building_name']." (".$serv['area_type_name'].")</td></tr>
									<tr><td class='".$cli." service_info_label'>Area:</td><td class='".$cli."'>".$serv['area_name']."</td></tr>";
				if ($serv['building_notes'])
					$html .= "		<tr><td class='".$cli." service_info_label'>Needs</td><td class='".$cli."'>".$serv['building_notes']."</td></tr>";
			}
			
			$html.="		</table>
						</td>
					</tr>";

		}

	}
	$html .= '</table>';
	echo($html);
}