<?php
defined('PRODUCT_NAME') or die;
class BookingModule extends ModuleInstance
{
	public function __construct()
	{
		parent::__construct();
		$this->scripts = array("<script async src=\"modules/booking/fullcalendar.js\"></script>");

		if(!Mainframe::site()->recaptcha)
		{
			$this->scripts[] = array("<script async src='https://www.google.com/recaptcha/api.js'></script>");
		}
		$this->enable_jquery         = true;
		$this->enable_jquery_ui      = true;
		$this->cache_config->enabled = false;
	}

	function render()
	{
		$recipients				= explode(";", $this->setting("recipients"));
		$publickey 				= $this->setting("recaptcha_public_key");
		$privatekey				= $this->setting("recaptcha_private_key");
		$services				= explode("\n", $this->setting("services"));
		$staffs					= explode("\n", $this->setting("practitioner"));
		$staffs_emails			= explode("\n", $this->setting("practitioner_emails"));
		$open_at				= $this->setting("open_at");
		$close_at				= $this->setting("close_at");
		$appointment_duration	= $this->setting("appointment_duration");
		$show_appointments		= $this->setting("show_appointments");
		$success_message		= $this->setting("success_message");
		$error_message			= $this->setting("error_message");
		$title 					= $this->setting("title");
		$title_heading_level 	= $this->setting("title_heading_level");
		$module_class 			= $this->setting("module_class");

		?>
		<div id="module_<?php echo($this->module_instance_id); ?>" class="module booking-module <?php echo($module_class); ?>">
			<?php
			if($title && $title_heading_level)
			{
				?><<?php echo($title_heading_level); ?> class="module-title"><?php echo($title); ?></<?php echo($title_heading_level); ?>><?php
			}

			//hide appointments from month view
			if(!$show_appointments)
			{
				?>
				<style>
					.fc-view-month .fc-event
					{
						display: none;
					}
				</style>
				<?php
			}
			?>
			<script>
				function pad(number, length)
				{
				    var str = '' + number;
				    while (str.length < length) {
				        str = '0' + str;
				    }

				    return str;
				}

				function openDialog_<?php echo $this->module_instance_id?>(nicedate)
				{
					$("#appt-date_<?php echo $this->module_instance_id?>").val(nicedate);
					$( "#book-appt-dialog_<?php echo $this->module_instance_id?>" ).dialog(
		            {
						dialogClass: "book-appt-dialog",
						title: "Book Your Appointment For " + nicedate,
						width: 800,
						height: 600,
						modal: true
						/*
,
						buttons:
						[
						    {
						    	text: "Book Appointment",
						    	click: function()
						    	{
						    		$("#contact_<?php echo $this->module_instance_id?>").submit();
						        	//$( this ).dialog( "close" );
						        }
						    },
						    {
						    	text: "Cancel",
						    	click: function()
						    	{
						        	$( this ).dialog( "close" );
						        }
						    }
					    ]
*/
					});
				}

				$(document).ready(function() {

					var date = new Date();
					var d = date.getDate();
					var m = date.getMonth();
					var y = date.getFullYear();
					var months = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

					$('#calendar_<?php echo $this->module_instance_id?>').fullCalendar({
						editable: true,
						disableDragging: true,
						header: { left: 'title', center: 'month, agendaDay', right:  'prev,next' },
						allDaySlot: false,
						slotMinutes: <?php echo $appointment_duration?>,
						snapMinutes: <?php echo $appointment_duration?>,
						defaultEventMinutes: <?php echo $appointment_duration?>,
						minTime: <?php echo $open_at?>,
						maxTime: <?php echo $close_at?>,
						axisFormat:'h:mm tt',
						weekends: true,
						timeFormat: { 'agenda': 'h:mm tt', '': 'h:mm tt' },
						dayClick: function(date, allDay, jsEvent, view)
						{
							if(allDay && view.name == "month")
							{
								//clicked on a day in month view
					            var now = new Date();
						        var nicedate_clicked = date.getFullYear() + "-" + pad((date.getMonth()+1), 2) + "-" + pad(date.getDate(), 2);
						        var nicedate_now = now.getFullYear() + "-" + pad((now.getMonth()+1), 2) + "-" + pad(now.getDate(), 2);

						        if(nicedate_clicked <= nicedate_now)
						        {
						        	alert("You can only book appointments from tomorrow onward.");
						        }
						        else
						        {
						        	$('#calendar_<?php echo $this->module_instance_id?>').fullCalendar( 'changeView', "agendaDay" );
						        	$('#calendar_<?php echo $this->module_instance_id?>').fullCalendar( 'gotoDate', date);
						        }

					            return;
					        }
					        else if(view.name == "agendaDay");
					        {
					        	//clicked on a time slot in day view
					            var nicedate = months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear() + " at " + pad(date.getHours(), 2) + ":" + pad(date.getMinutes(), 2);

					            openDialog_<?php echo $this->module_instance_id?>(nicedate);

								return;
					        }
					    },
					    eventClick: function(calEvent, jsEvent, view)
					    {
						    var now = new Date();
					        var nicedate_clicked = calEvent.start.getFullYear() + "-" + pad((calEvent.start.getMonth()+1), 2) + "-" + pad(calEvent.start.getDate(), 2);
					        var nicedate_now = now.getFullYear() + "-" + pad((now.getMonth()+1), 2) + "-" + pad(now.getDate(), 2);

					        if(nicedate_clicked <= nicedate_now)
					        {
					        	alert("That date is in the past!");
					        }
					        else
					        {
					        	$('#calendar_<?php echo $this->module_instance_id?>').fullCalendar( 'changeView', "agendaDay" );
					        	$('#calendar_<?php echo $this->module_instance_id?>').fullCalendar( 'gotoDate', calEvent.start );
					        }

					        return;
					        // change the border color just for fun
					        //$(this).css('border-color', 'red');

					    },
					    eventRender: function(event, element)
					    {
					    	/*if(event.allDay == false)
					    	{
					    		return false;
					    	}
					        element.qtip({
					            content: event.description
					        });*/
					    },
						events: function(start, end, callback)
						{
							var events = [];
							var date;
							var nicedate = start.getFullYear() + "-" + pad((start.getMonth()+1), 2) + "-" + pad(start.getDate(), 2) + " " + pad(start.getHours(), 2) + ":" + pad(start.getMinutes(), 2) + ":00";

					        //convert common time intervals to decimal for calculating number of hours open
					        var hours = <?php echo str_replace(array(":00", ":15", ":30", ":45"), array("", ".25", ".5", ".75"), $close_at)?>-<?php echo str_replace(array(":00", ":15", ":30", ":45"), array("", ".25", ".5", ".75"), $open_at)?>;
					        var slots_per_hour = Math.floor(60/<?php echo $appointment_duration?>);
					        var slots = (hours * slots_per_hour);

							/*for(i=0; i<42; i++)
							{
								date = new Date(start.getTime() + ((24 * 60 * 60 * 1000) * i));

								events.push({
					                        title: "x Slots Available",
					                        start: date // will be parsed
					                    });
							}
							callback(events);*/
					        $.ajax({
					            url: '<?php echo LIVE_SITE?>/ajax/get_appointments_for_module',
					            dataType: 'xml',
					            data: {
					                start: start,
					                end: end,
					                duration: <?php echo $appointment_duration?>,
					                slots: slots
					            },
					            success: function(doc) {
					            	var events = [];
					                $(doc).find('event').each(function() {
					                	events.push({
					                        title: $(this).attr('title'),
					                        start: $(this).attr('start'),
					                        end: $(this).attr('end'),
					                        allDay: ($(this).attr('allDay') == "true" ? true : false),
					                        editable: false
					                    });
					                });
					                callback(events);
					            }
					        });
					    }
					});
				});


			</script>

			<div id="calendar_<?php echo $this->module_instance_id?>"></div>

			<div id="book-appt-dialog_<?php echo $this->module_instance_id?>" class="book-appt-dialog" style="display: none;">
				<?php
				$sent = false;

				if($this->input->post("sendmail") == "1")
				{
					csrf_verify();
					?>
					<script>
						jQuery(window).on("load", function()
						{
							openDialog_<?php echo $this->module_instance_id?>("<?php echo date("F j, Y \a\\t H:i", strtotime(str_replace("at", "", $this->input->post("appt-date_" . $this->module_instance_id))))?>");
						});
					</script>
					<?php
					$message = "";
					$sent = false;

					if($this->input->post("sendmail") == "1" && $publickey && $privatekey)
					{
						$this->load->helper("captcha");
						$recaptcha = verify_recaptcha_v2($this->input->post("g-recaptcha-response"), $privatekey);
					}

					if($this->input->post("sendmail") && $publickey && $privatekey && $recaptcha)
					{
						//send email
						$site = Mainframe::site();
						$mail = get_mailer();
						$mail->SetFrom($site->mail_username, ($site->mail_from ? $site->mail_from : COMPANY_NAME));
						$mail->addReplyTo($this->input->post("email"), $this->input->post("name"));

						foreach($recipients as $recipient)
						{
							$recipient = trim($recipient);

							if($recipient)
							{
								$mail->AddAddress("$recipient");
							}
						}

						if(trim($this->input->post("staff_email")))
						{
							$mail->AddAddress($this->input->post("staff_email"));
						}

						$mail->Subject = ($this->input->post("subject") ? $this->input->post("subject") : "Website Contact Form");
						$mail->Body = "Name: \t\t" . $this->input->post("name") . "\n";
						$mail->Body .= "Phone: \t\t" . $this->input->post("phone") . "\n";
						$mail->Body .= "E-mail: \t\t" . $this->input->post("email") . "\n";
						$mail->Body .= "Date: \t\t" . $this->input->post("appt-date_$this->module_instance_id") . "\n";
						$mail->Body .= "For: \t\t\t" . urldecode($this->input->post("appt-for")) . "\n";
						$mail->Body .= "With: \t\t" . $this->input->post("staff") . "\n\n";
						$mail->Body .= $this->input->post("message");

						if($mail->Send())
						{
							?><div class="alert alert-success"><?php echo $success_message?></div><?php
							$sent = true;

							$sql = "INSERT INTO booking_appointments SET
								`name`=?,
								`email`=?,
								`phone`=?,
								`appointment_date`=?,
								`appointment_for`=?,
								`appointment_with`=?,
								`notes`=?";

							$this->db->query($sql, array($this->input->post("name"),
							                             $this->input->post("email"),
							                             $this->input->post("phone"),
							                             date("Y-m-d H:i:s", strtotime(str_replace("at", "", $this->input->post("appt-date_" . $this->module_instance_id)))),
							                             $this->input->post("appt-for"),
							                             $this->input->post("staff"),
							                             $this->input->post("message")));
							$_POST = "";

							?>
							<script>
								jQuery(window).on("load", function()
								{
									$( "#book-appt-dialog_<?php echo $this->module_instance_id?>" ).dialog('option', 'buttons',
									    [{
									    	text: "Close",
									    	click: function()
									    	{
									        	$( this ).dialog( "close" );
									        	location.reload();
									        }
									    }]
								    );
								});
							</script>
							<?php
						}
						else
						{
							?><div class="alert alert-danger"><?php echo $error_message?></div><?php
						}
					}
					else if($this->input->post("sendmail") == "1" && !$recaptcha)
					{
						?><div class="alert alert-danger">Invalid Captcha Response</div><?php
					}
				}

				if(!$sent)
				{
					?>

					<form name="contact_<?php echo $this->module_instance_id?>" id="contact_<?php echo $this->module_instance_id?>" method="post" action="">
						<?php csrf(); ?>
						<input type="hidden" name="sendmail" id="sendmail" value="1" />
						<input type="hidden" name="appt-date_<?php echo $this->module_instance_id?>" id="appt-date_<?php echo $this->module_instance_id?>" value="<?php echo(html_escape($this->input->post("appt-date_$this->module_instance_id")));?>" />
						<input type="hidden" name="subject" id="subject" value="Online Appointment Request" />

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="name">Name <sup class="required">*</sup>:</label></div>
							<div class="<?php echo(FIELD_COL); ?>"><input type="text" name="name" id="name" value="<?php echo(html_escape($this->input->post("name")));?>" required class="form-control" /></div>
						</div>

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="email">E-mail Address <sup class="required">*</sup>:</label></div>
							<div class="<?php echo(FIELD_COL); ?>"><input type="email" name="email" id="email" value="<?php echo(html_escape($this->input->post("email")));?>" required class="form-control" /></div>
						</div>

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="phone">Phone Number <sup class="required">*</sup>:</label></div>
							<div class="<?php echo(FIELD_COL); ?>"><input type="tel" name="phone" id="phone" value="<?php echo(html_escape($this->input->post("phone")));?>" required class="form-control" /></div>
						</div>

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="appt-for">Appointment For <sup class="required">*</sup>:</label></div>
							<div class="<?php echo(FIELD_COL); ?>">
								<?php
								$wgt = new FeralBasicSelectWidget("appt-for", $this->input->post("appt-for"), "form-control custom-select");

								foreach($services as $service)
								{
									$wgt->AddOption(rawurlencode(trim("$service")), trim("$service"));
								}
								$wgt->Create();
								?>
							</div>
						</div>

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="staff">Appointment With <sup class="required">*</sup>:</label></div>
							<div class="<?php echo(FIELD_COL); ?>">
								<script>
									var emails = Array(<?php echo count($staffs_emails)?>);
									<?php
									$count = 0;
									foreach($staffs_emails as $email)
									{
										?>
										emails[<?php echo $count?>]="<?php echo trim($email)?>";
										<?php
										$count++;
									}
									?>

									function updateEmail()
									{
										var index = document.getElementById("staff").selectedIndex;
										document.getElementById("staff_email").value = emails[index];
									}
								</script>
								<?php
								FeralHidden("staff_email", $staffs_emails[0]);

								$wgt = new FeralBasicSelectWidget("staff", $this->input->post("staff"), "form-control custom-select");
								$wgt->SetAttribute("onchange", "updateEmail()");

								foreach($staffs as $staff)
								{
									$wgt->AddOption(trim("$staff"));
								}
								$wgt->Create();
								?>
							</div>
						</div>

						<div class="<?php echo(FORM_ROW); ?>">
							<div class="<?php echo(LABEL_COL); ?>"><label for="message">Additional Info:</label></div>
							<div class="<?php echo(FIELD_COL); ?>"><textarea name="message" id="message" class="form-control"><?php echo(html_escape($this->input->post("message")));?></textarea></div>
						</div>

						<?php
						if($publickey && $privatekey)
						{
							?>
							<div class="<?php echo(FORM_ROW); ?>">
								<div class="<?php echo(LABEL_COL); ?>">Please type the words you see.  If you have trouble reading them, you can generate new words or try an audio challenge.</div>
								<div class="<?php echo(FIELD_COL); ?> recaptcha"><div class="g-recaptcha" style="display: inline-block;" data-sitekey="<?php echo($publickey); ?>"></div></div>
							</div>
							<?php
						}
						?>
						<div class="<?php echo(FORM_ROW); ?> text-center">
							<button type="submit" class="btn btn-primary">Book Appointment</button>
						</div>
					</form>
					<?php
				}
				?>
			</div>
		</div>
		<?php
	}
}
