<?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($year, $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[$year][$mm][$dd][0]."</td>
			<td>".$tmparr[$year][$mm][$dd][1]."</td>
			<td>".$tmparr[$year][$mm][$dd][2]."</td>
			<td>".$day."</td>
		</tr>
		<tr>
			<td>".$tmparr[$year][$mm][$dd][3]."</td>
			<td>".$tmparr[$year][$mm][$dd][4]."</td>
			<td>".$tmparr[$year][$mm][$dd][5]."</td>
			<td>".$tmparr[$year][$mm][$dd][6]."</td>
		</tr>
		<tr>
			<td>".$tmparr[$year][$mm][$dd][7]."</td>
			<td>".$tmparr[$year][$mm][$dd][8]."</td>
			<td>".$tmparr[$year][$mm][$dd][9]."</td>
			<td>".$tmparr[$year][$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 $yKey=>$year)
		{
			foreach($year as $mKey=>$month)
			{
				foreach($month as $dKey=>$day)
				{
					foreach($day as $iKey=>$icon)
					{
						$orderedEvents[$yKey][$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.booking_id, booking.booking_date, client.client_id, 
				concat(client_name, ' ', client_surname) as client_full_name, booking.sa_id, 
				coalesce(sa_description, 'Single Booking') as sa_description, suburb_name, region_name, address.address_id, 
				address_lng, address_lat, address.address, booking_schedule.booking_time, booking_schedule.team_id, 
				coalesce(client_cell, client_phone) as client_phone, bs_completed, client_distance, client_travel_time, 
				client_address_note 
				from booking 
				left join standing_appointment on standing_appointment.sa_id = booking.sa_id
				inner join client on client.client_id = booking.client_id 
				inner join address on address.address_id = client.address_id 
				inner join postal_data on postal_data.post_id = address.post_id 
				left join booking_schedule on booking_schedule.booking_id = booking.booking_id ";
	$sql = $sqlPfx."
	where (booking_date = '".$eventDate->format('Y-m-d')."') and 
		(
			(DATE(booking_schedule.booking_time) = '".$eventDate->format('Y-m-d')."') or ((DATE(booking_schedule.booking_time) is null))
		) 
		and 
		(booking.sa_id is null) 
		order by booking.booking_date ASC, booking_schedule.booking_time ASC";
	
	$srows = $sableDB->getRows($sql); //single events
	
	//here we also need to get all of the recurring booking details to display:
	$calendar 	= getRecurringEvents($eventDate);
	
	$books		= $calendar[$eventDate->format('Y')][$eventDate->format('m')][$eventDate->format('d')];
	
	$rrows = []; //recurring events
	if ($books)
	{
		foreach($books as $bid=>$day)
		{
			$sqlPfx = 'select booking.booking_id, booking.booking_date, client.client_id, 
						concat(client_name, \' \', client_surname) as client_full_name, booking.sa_id, 
						coalesce(sa_description, \'Single Booking\') as sa_description, suburb_name, region_name, address.address_id, 
						address_lng, address_lat, address.address, 
						coalesce(client_cell, client_phone) as client_phone, client_distance, client_travel_time 
						from booking 
						left join standing_appointment on standing_appointment.sa_id = booking.sa_id
						inner join client on client.client_id = booking.client_id 
						inner join address on address.address_id = client.address_id 
						inner join postal_data on postal_data.post_id = address.post_id ';
			$sqry = $sqlPfx.' where booking.booking_id = '.$bid;
			$drow = $sableDB->getRow($sqry);
			if (!empty($drow)) 
			{
				
				$sqry = 'select * from booking_schedule where (booking_id = '.$bid.') and 
						(DATE(booking_time) = "'.$eventDate->format('Y-m-d').'")';
				$bsched = $sableDB->getRow($sqry);
				if (!empty($bsched)) 
					$rrows[] = array_merge($drow, $bsched);
				else
					$rrows[] = $drow;
			}
		}
	}
	
	$rows = array_merge($rrows, $srows);
	
	$ret = [];
	$today = new DateTime(); 
	$today->setTime(0,0); //today
	foreach($rows as $row)
	{
		//if there is not booking scheduled for this date, ensure that the booking_time is blank so the system can update it:
		if (!empty($row['booking_time']))
		{
			$bookTime = new DateTime($row['booking_time']);
			$bookTime->setTime(0,0);
			if ($bookTime < $today) 
			{
				$row['booking_time'] = '';
				$row['team_id'] = '';
				$row['bs_completed'] = '';
			}
		}
		
		$tmp = [];
		$tmp['booking_id']			= $row['booking_id'];
		$tmp['client_id']			= $row['client_id'];
		$tmp['booking_date']		= $row['booking_date'];
		$tmp['booking_time']		= $row['booking_time'];
		$tmp['team_id']				= $row['team_id'];
		$tmp['client_full_name']	= $row['client_full_name'];
		$tmp['client_distance']		= $row['client_distance'];
		$tmp['client_travel_time']	= $row['client_travel_time'];
		$tmp['suburb_name']			= $row['suburb_name'];
		$tmp['region_name']			= $row['region_name'];
		$tmp['sa_description']		= $row['sa_description'];
		$tmp['address_id']			= $row['address_id'];
		$tmp['address']				= $row['address'];
		$tmp['address_lng']			= $row['address_lng'];
		$tmp['address_lat']			= $row['address_lat'];
		$tmp['client_phone']		= $row['client_phone'];
		$tmp['bs_completed']		= $row['bs_completed'];
		$tmp['sa_id']				= $row['sa_id'];
		$tmp['client_address_note'] = $row['client_address_note'];
		$tmp['service_info']	= [];		
		$sql = 'select booking__service.service_id, area_type_name, area_name, building.building_id, building_name, building_notes, building_notes, 
						service_name, service_price, service_duration, bs_price_override  
				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'].') and (booking__service.service_active = 1)';
		$retrows = $sableDB->getRows($sql);
		//SableDebug::debug($sql);
		//SableDebug::debug($retrows);
		$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']);
		$dby = $dbdt->format('Y');
		$dbd = $dbdt->format('d');
		$dbm = $dbdt->format('m');
		$calendar[$dby][$dbm][$dbd][$row['booking_id']] = '<i class="fa fa-square" title="'.$row['client_full_name'].'"></i>';
	}
	return $calendar;
}

function getRecurringEvents($eventDate, $bookingId=0)
{
	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)';
	
	if ($bookingId) $sql .= ' and (booking.booking_id = '.$bookingId.')';
	
	$rows = $sableDB->getRows($sql);
	
	$idx  = 0;
	
	foreach($rows as $row)
	{
		$startDate		= $row['sa_start_date']; //commencement date
		$occurs 		= intval($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;

		$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_start_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'));
		} 
		else 
		{
			$startDay	= 0; //indicates we need to find the correct start day.
		}

		switch ($occType)
		{
			case 1: //Day
			{
				$recurts = clone $startts; //sa_date
				$workingDate = clone $eventDate;
				$workingDate->setDate($workingDate->format('Y'), $workingDate->format('m'), $workingDate->format('t'));

				/*
				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;
				$roll	= ($recurts < $workingDate);
				do 
				{
					$recurts->modify('+'.$occurs.' days');

					$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";

					$dby = $recurts->format('Y');
					$dbd = $recurts->format('d');
					$dbm = $recurts->format('m');
					$calendar[$dby][$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';

					$roll	= ($recurts < $workingDate);

					$idx++;
					if ($idx > 6000) break; //safety
				} while ($roll);
				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
					{
						$currdow = $workingDate->format('N'); //1 = Monday, 7 = Sunday
						if ($i)
						{
							$tmp = '+'.$occurs.' weeks';
						}
						else
						{
							//$tmp = 'next '.$rowdow['dow_long']; //get to the next day
							$tmp = ($currdow == $rowdow['dow_id']) ? null : 'next '.$rowdow['dow_long'];
						}

						if (!empty($tmp)) 
						{
							$workingDate->modify($tmp);
						}

						/*
						$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";
						$dby		= $workingDate->format('Y');
						$dbd		= $workingDate->format('d');
						$dbm		= $workingDate->format('m');								
						$calendar[$dby][$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
				{
					$recurts = clone $startts; //sa_start_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.
					*/

					$idx = 0;
						
					do 
					{
						$workingDate = clone $recurts;

						$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);
						foreach($rowsdow as $rowdow)
						{
							$tmp = $monthTypeOccWord.' '.$rowdow['dow_long'].' of '.$recurts->format('F').' '.$recurts->format('Y');
							$recurts->modify($tmp);	

							$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";

							$dby		= $recurts->format('Y');
							$dbd		= $recurts->format('d');
							$dbm		= $recurts->format('m');
							$calendar[$dby][$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';
							$recurts->setDate($recurts->format('Y'), $recurts->format('m'), 1);
						}

						$tmp = '+'.$occurs.' months';
						$recurts->modify($tmp); //every 2nd, 3rd month, etc.
						unset($workingDate);
						$idx++;
						if ($idx > 1500) break; //safety measure.
					} while ($recurts < $eventDate);
				}
				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
					$workingDate	= clone $eventDate;
					$workingDate->modify('first day of '.$workingDate->format('F'));

					$roll 			= $recurts < $workingDate;
					while ($recurts < $workingDate)
					{
						$recurts->modify('+'.$occurs.' months'); //e.g. every 2nd or 3rd month
						foreach ($rowdoms as $rowdom) 
						{
							//$recurts->modify('last day of '.$workingDate->format('F'));
							$dom = intval($rowdom['dom_no'])+1;
							if ($dom > $recurts->format('t'))
								$recurts->modify('last day of '.$recurts->format('F'));
							else
								$recurts->setDate($recurts->format('Y'), $recurts->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";
							$dby		= $recurts->format('Y');
							$dbd		= $recurts->format('d');
							$dbm		= $recurts->format('m');								
							$calendar[$dby][$dbm][$dbd][$row['booking_id']] = '<i class="fa '.$class.'" title="'.$title.'"></i>';
						}
						//$roll 		= $recurts <= $workingDate;
					}
				}
				break;
			}
		}
	}
	unset($_booking);
	return $calendar;
}

function combineArrays($ar1, $ar2)
{
	/**
	Array
	(
		[2021] => Array
		(
			[06] => Array
			(
				[14] => Array
				(
					[2] => 
				)
			)
		)
	)
	Array
	(
		[2021] => 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 $ykey=>$year) //for each year
		{
			foreach($year as $mkey=>$month) //for each month
			{
				foreach($month as $dkey=>$days)
				{
					if (is_array($subarray[$ykey][$mkey]))
					{
						foreach($subarray[$ykey][$mkey] as $iddkey=>$idd)
						{
							$mainarray[$ykey][$mkey][$iddkey] = $idd;
						}
					}
				}
			}
		}
		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, $tabNo)
{
	$singleBookings	= getEvents($eventDate);
	$recurBookings	= getRecurringEvents($eventDate);
	
	$sbok = $singleBookings && is_array($singleBookings[$eventDate->format('Y')][$eventDate->format('m')]);
	$rbok = $recurBookings  && is_array($recurBookings [$eventDate->format('Y')][$eventDate->format('m')]);
		
	
	if ($sbok && $rbok)
	{
		$calendar = combineArrays($singleBookings, $recurBookings);
	}
	elseif ($sbok)
	{
		$calendar[$eventDate->format('Y')] = $singleBookings[$eventDate->format('Y')];
	}
	elseif ($rbok)
	{
		$calendar[$eventDate->format('Y')] = $recurBookings[$eventDate->format('Y')];
	}

	$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)
			{
				$classnm =  "calendar_day";
				if ($week_day == 0) //Sunday
				{
					$action = "alert(\"Please be aware you have selected a Sunday.\"); ";
					$classnm =  "calendar_day_sunday";
				}
				else
				{
					//check if this is a public holiday:
					$_booking	= new Booking;
					$paramDate	= clone $eventDate;
					$paramDate->setDate($year, $month, $day);
					$conflicted = $_booking->checkHolidayConflicts($paramDate, true); //silent
					unset($paramDate);
					unset($_booking);
					if ($conflicted) 
					{
						$action = "alert(\"Please be aware you have selected a Public Holiday.\"); ";
						$classnm =  "calendar_day_holiday";
					}
					else
					{
						$action = "";
						$classnm =  "calendar_day";
					}
				}
				
				//$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='".$classnm." 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($year, $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('Y'), $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_birthday] => 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%">Details</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';
				$rand = number_format(floatval($serv['service_price']), 2);
				
				$durval = floatval($serv['service_duration']);
				if ($durval == 60)
				{
					$dur = "1 hour";
				}
				elseif ($durval > 60)
				{					
					$durHrs = (floatval($serv['service_duration']) / 60); //gives us the number of hours
					$durMin = $durHrs - (int)($durHrs); //get the minutes of the remainder
					$hrttl	= (int)($durHrs) == 1 ? "hour" : "hours";
					$dur	= (int)($durHrs)." ".$hrttl." and ".number_format((float)($durMin * 60), 0)." minutes";
				}
				else
				{
					$dur = $durval." minutes";
				}
					
				$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>
									<tr>
										<td class='".$cli." service_info_label'>Service:</td>
										<td class='".$cli."'>".$serv['service_name']."</td>
									</tr>
									<tr>
										<td class='".$cli." service_info_label'>Price:</td>
										<td class='".$cli."'>R".$rand."</td>
									</tr>
									<tr>
										<td class='".$cli." service_info_label'>Duration:</td>
										<td class='".$cli."'>".$dur."</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);
}