<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

$doAutentication = false;
$no_visible_elements = true;

if ($_GET){
	$calLang = (isset($_GET['lang'])) ? $_GET['lang'] : NULL;
	$title = (isset($_GET['title']) && $_GET['title'] == '0') ? 0 : 1;
	$disabled = (isset($_GET['disabled']) && $_GET['disabled'] == '0') ? 0 : 1;
}elseif ($_POST){
	$calLang = (isset($_POST['lang'])) ? $_POST['lang'] : NULL;
	$title = (isset($_POST['title']) && $_POST['title'] == '0') ? 0 : 1;
	$disabled = (isset($_GET['disabled']) && $_GET['disabled'] == '0') ? 0 : 1;
}else{
	$title = 1;
}

	require "../_container/container_top.php";
	require_once ('business/TenantMgr.php');
	require_once ('business/TenancyMgr.php');
	require_once ('business/ReservationMgr.php');
	require_once("config/Tagger.php");

	$tenantMgr = new TenantMgr();
	$tenancyMgr = new TenancyMgr();
	$reservationMgr = new ReservationMgr();

	Logger::info('BEGIN User Form rendering');
	
	// print_r($_GET);
	// print_r($_POST);
// TODO: Add into Config
	$captcha = new Zend\Captcha\Image(array(
		'wordLen' => 4,
		'font' => ROOT . 'front/user/tahoma.ttf',
		'fontSize' => 36,
		'width' => 250,
		'height' => 100,
		'dotNoiseLevel' => 40,
		'lineNoiseLevel' => 3,
		'suffix' => ".png",
		'imgDir' => "out",
		'imgUrl' => "out",
		'setExpiration' => 10)
	);
	$captcha->setSession($session);

	$action = getPost('action');

	$inputTitle = htmlentities(getPost('inputTitle'), ENT_QUOTES, "UTF-8");
	$inputLastname = htmlentities(getPost('inputLastname'), ENT_QUOTES, "UTF-8");
	$inputName = htmlentities(getPost('inputName'), ENT_QUOTES, "UTF-8");
	$inputAddress1 = htmlentities(getPost('inputAddress1'), ENT_QUOTES, "UTF-8");
	$inputAddress2 = htmlentities(getPost('inputAddress2'), ENT_QUOTES, "UTF-8");
	$inputCity = htmlentities(getPost('inputCity'), ENT_QUOTES, "UTF-8");
	$inputZipcode = htmlentities(getPost('inputZipcode'), ENT_QUOTES, "UTF-8");
	$inputCountry = htmlentities(getPost('inputCountry'), ENT_QUOTES, "UTF-8");
	$inputPhone = htmlentities(getPost('inputPhone'), ENT_QUOTES, "UTF-8");
	$inputCellphone = htmlentities(getPost('inputCellphone'), ENT_QUOTES, "UTF-8");
	$inputEmail = htmlentities(getPost('inputEmail'), ENT_QUOTES, "UTF-8");
	$inputCommentReserv = htmlentities(getPost('inputCommentReserv'), ENT_QUOTES, "UTF-8");
	$start_date = getPost('start_date');
	$end_date = getPost('end_date');
	
	$inputAdults = getPost('inputAdults');
	$inputChilds = getPost('inputChilds');
	$inputBaby = getPost('inputBaby');
	$inputDisabled = getPost('inputDisabled');

	$tenancyid = isset($_GET['id']) ? $_GET['id'] : getPost('tenancyid');
	$lang = (isset($calLang)) ? $calLang : $config['language'];
	
	$arrTenancy = $tenancyMgr->getTenancy($tenancyid);
	if (empty($arrTenancy)) $arrTenancy = array(new TenancyVo());
	

	if (!empty($action)){
		Logger::info(' action: [' . $action . ']');
		if ($action == "RE_CAPTCHA") {
			Logger::debug('Action RE_CAPTCHA: The captcha is being re-generated.');
			$captcha->generate();
		}
		if ($action == "send") {
			Logger::debug('Action Send.');
			$date_enreg = date("Y-m-d");
			$captchaArray = array(
				'id' => $session->getName(),
				'input' => getPost('inputCaptcha')
			);
			if ($captcha->isValid($captchaArray)){
					Logger::debug('Captcha is validated.');
					$tenant = array();
					$tenant['title'] = getPost('inputTitle');
					$tenant['name'] = getPost('inputName');
					$tenant['lastname'] = getPost('inputLastname');
					$tenant['address1'] = getPost('inputAddress1');
					$tenant['address2'] = getPost('inputAddress2');
					$tenant['zipcode'] = getPost('inputZipcode');
					$tenant['city'] = getPost('inputCity');
					$tenant['country'] = getPost('inputCountry');
					$tenant['phone'] = getPost('inputPhone');
					$tenant['cellphone'] = getPost('inputCellphone');
					$tenant['email'] = getPost('inputEmail');
					$tenant['newsletter'] = 1;
					// $tenant['comment'] = getPost('inputComment');
					$newTenantId = $tenantMgr->insert($tenant);
					Logger::debug('Add tenant result ID: ' . $newTenantId);
				if ($newTenantId > 0) {
					$reservation = array();
					$reservation['tenancy_id'] = $tenancyid;
					$reservation['tenant_id'] = $newTenantId;
					$reservation['arrival_date'] = getPost('start_date');
					$reservation['departure_date'] = getPost('end_date');
					$reservation['adults_nb'] = getPost('inputAdults');
					$reservation['childs_nb'] = getPost('inputChilds');
					$reservation['baby_nb'] = getPost('inputBaby');
					$reservation['price'] = 0;
					$reservation['vat'] = $arrTenancy[0]->vat;
					$reservation['disabled'] = getPost('inputDisabled');
					$reservation['comment'] = getPost('inputCommentReserv');
					$reservation['status'] = ReservationMgr::RESERV_NEW;
					$res = $reservationMgr->insert($reservation);
					Logger::debug('Add reserv: ' . $res);

					if ($res > 1) {
						require_once ('business/MailMgr.php');
						$mailMgr = new MailMgr();
						$tagger = new Tagger();
						$inputEmail = getPost('inputEmail');
							$mail = $mailMgr->getMail(1);
							if (isset($mail) && !empty($mail[0]->enable)){
								$tagger->setReservationId($res);
								$mail[0]->from = $config['renter_email'];
								$mail[0]->to = $tagger->tag($mail[0]->to);
								if (empty($mail[0]->to)) $mail[0]->to = $config['renter_email'];
								$mail[0]->cc = $tagger->tag($mail[0]->cc);
								$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
								$mail[0]->subject = $tagger->tag($mail[0]->subject);
								$mail[0]->content = $tagger->tag($mail[0]->content);
								if (empty($inputEmail)) {
									$mail[0]->content = $tr->translate("msgUserformNoSender") . $mail[0]->content;
								}
								

								include_once ('config/Mailer.php');
								$m = new Mailer($config);
								$r = $m->sendMail($mail);
								if (!$r) {
									$msgType = "error";
									$msg = $tr->translate("msgMailError", "default", $lang);
								}
							}
						$msgType = "success";
						$msg = $tr->translate("msgUserformReservAdded", "default", $lang);
					}else{
						Logger::err('The Reservation could not be added.');
						$msgType = "error";
						$msg = $tr->translate("msgUserformReservAddError", "default", $lang);
					}
				}else{
					Logger::err('The Tenant could not be added.');
					$msgType = "error";
					$msg = $tr->translate("msgUserformTenantAddError", "default", $lang);
				}
			}else{ // captcha is not valid
				Logger::err('The Captcha is not valid.');
				$msgType = "error";
				$msg = $tr->translate("msgUserformWrongCaptcha", "default", $lang);
			}
		} // $action == "ADD_RESERV"
	}
	$captcha->generate();

?>
	<div class="container">
		<h1><?php if ($title) echo $tr->translate('thUserformHeader', "default", $lang); ?> <strong>
			<?php
			if (empty($arrTenancy[0]->tenancy_id)) {
					$msgType = "error";
					$msg = $tr->translate("msgUserformTenancyNotFound", "default", $lang);
					echo '<div class="alert alert-'.$msgType . '">
							<strong>' . $msg . '</strong>
							</div>';		
			}else{
				if ($title) echo $arrTenancy[0]->name;
				if (isset($msgType) && $msgType == "success"){
					echo '<div class="alert alert-'.$msgType . '">
						<strong>' . $msg . '</strong>
						</div>';
					require "../_container/container_bottom.php";
					die();
				}else{
					if (isset($msgType) && $msgType == "error"){
					echo '<div class="alert alert-'.$msgType . '">
						<strong>' . $msg . '</strong>
						</div>';
					}

			echo "</strong>";
			if ($title) echo "<hr>";
			if ($userPageMaintenanceMode) {
				$msgType = "error";
				$msg = $tr->translate("msgUserformMaintenanceMode", "default", $lang);
				echo '<div class="alert alert-'.$msgType . '">
					<strong>' . $msg . '</strong>
					</div>';
				require "../_container/container_bottom.php";
				die();
			}

			?>
			</h1>
			<form class="form-horizontal" method="post" name="userForm" id="userForm" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				<input type="hidden" name="captcha[id]" value="<?php echo $captcha->getId() ?>" />
				<input type="hidden" name="action" id="action" value="" />
				<input type="hidden" name="start_date" id="start_date" value="" />
				<input type="hidden" name="end_date" id="end_date" value="" />
				<input type="hidden" name="tenancyid" value="<?php echo $tenancyid; ?>" />
				<input type="hidden" name="lang" value="<?php echo $lang; ?>" />
				<input type="hidden" name="title" value="<?php echo $title; ?>" />
				<input type="hidden" name="disabled" value="<?php echo $disabled; ?>" />
				<input type="hidden" name="inputDisabled" id="inputDisabled" value="" />

				<div class="row-fluid">
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputTitle"><?php echo $tr->translate("thTenantTitle", "default", $lang); ?></label>
							<div class="controls">
								<select id="inputTitle" name="inputTitle" class="input-small">
									<option></option>
									<?php $arrTitle = $tr->translate("thUserformTitles", "default", $lang);
										foreach($arrTitle as $t) { ?>
											<option value="<?php echo $t; ?>" <?php if ($t == $inputTitle) echo " selected"; ?>><?php echo $t; ?></option>
									<?php } ?>
								</select>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputLastname"><?php echo $tr->translate("thTenantLastName", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputLastname" name="inputLastname" value="<?php echo $inputLastname; ?>">
							</div>
						</div> 				
						<div class="control-group">
							<label class="control-label" for="inputName"><?php echo $tr->translate("thTenantName", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputName" name="inputName" value="<?php echo $inputName; ?>">
							</div>
						</div>
						<div class="control-group">
						<label class="control-label" for="inputAddress1"><?php echo $tr->translate("thTenantAddress1", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputAddress1" name="inputAddress1" value="<?php echo $inputAddress1; ?>">
							</div>
						</div>
						<div class="control-group">
						<label class="control-label" for="inputAddress2"><?php echo $tr->translate("thTenantAddress2", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputAddress2" name="inputAddress2" value="<?php echo $inputAddress2; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputZipcode"><?php echo $tr->translate("thTenantZipCode", "default", $lang); ?></label>
							<div class="controls">
								<input class="input-small" type="text" id="inputZipcode" name="inputZipcode" value="<?php echo $inputZipcode; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCity"><?php echo $tr->translate("thTenantCity", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputCity" name="inputCity" value="<?php echo $inputCity; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCountry"><?php echo $tr->translate("thTenantCountry", "default", $lang); ?></label>
							<div class="controls">
								<input type="text" id="inputCountry" name="inputCountry" value="<?php echo $inputCountry; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputPhone"><?php echo $tr->translate("thTenantPhone", "default", $lang); ?>*</label>
							<div class="controls">
								<input type="text" id="inputPhone" name="inputPhone" value="<?php echo $inputPhone; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCellphone"><?php echo $tr->translate("thTenantMobile", "default", $lang); ?>*</label>
							<div class="controls">
								<input type="text" id="inputCellphone" name="inputCellphone" value="<?php echo $inputCellphone; ?>">
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputEmail"><?php echo $tr->translate("thTenantEmail", "default", $lang); ?>*</label>
							<div class="controls">
								<input type="text" id="inputEmail" name="inputEmail" value="<?php echo $inputEmail; ?>">
							</div>
						</div>

					</div>
					<div class="span6">
						<div class="control-group">
							<label class="control-label" for="inputAdults"><?php echo $tr->translate("thReservAdults", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign qtyminus" data-field="inputAdults"></span></a><input type="text" class="input-mini" id="inputAdults" name="inputAdults" value="<?php echo (empty($inputAdults)) ? 0 : $inputAdults; ?>"><a href="#"><span class="add-on icon-plus-sign qtyplus" data-field="inputAdults"></span></a>
								</div>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputChilds"><?php echo $tr->translate("thReservChilds", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign qtyminus" data-field="inputChilds"></span></a><input type="text" class="input-mini" id="inputChilds" name="inputChilds" value="<?php echo (empty($inputChilds)) ? 0 : $inputChilds; ?>"><a href="#"><span class="add-on icon-plus-sign qtyplus" data-field="inputChilds"></span></a>
								</div>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputBaby"><?php echo $tr->translate("thReservBabys", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<a href="#"><span class="add-on icon-minus-sign qtyminus" data-field="inputBaby"></span></a><input type="text" class="input-mini" id="inputBaby" name="inputBaby" value="<?php echo (empty($inputBaby)) ? 0 : $inputBaby; ?>"><a href="#"><span class="add-on icon-plus-sign qtyplus" data-field="inputBaby"></span></a>
								</div>
							</div>
						</div>
						<?php if ($disabled) { ?>
						<div class="control-group">
							<label class="control-label" for="inputDisabled"><?php echo $tr->translate("thReservDisabled", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-prepend">
									<input type="checkbox" id="inputDisabled" name="inputDisabled"<?php if (!empty($inputDisabled)) echo " checked";?>>
								</div>
							</div>
						</div>
						<?php } ?>
						<div class="control-group">
							<label class="control-label" for="startDate"><?php echo $tr->translate("thReservFrom", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-append"><input type="text" class="datepicker input-medium"  name="startDate" id="startDate"
									value="<?php if ($start_date) echo date($config['date_format'], strtotime($start_date)); ?>"><span class="add-on"><i class="icon-calendar"></i></span>
								</div>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="endDate"><?php echo $tr->translate("thReservTo", "default", $lang); ?></label>
							<div class="controls">
								<div class="input-append"><input type="text" class="datepicker input-medium"  name="endDate" id="endDate"
									value="<?php if ($end_date) echo date($config['date_format'], strtotime($end_date)); ?>"><span class="add-on"><i class="icon-calendar"></i></span>
								</div>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCommentReserv"><?php echo $tr->translate("thReservComment", "default", $lang); ?></label>
							<div class="controls">
								<textarea id="inputCommentReserv" name="inputCommentReserv" cols="140" rows="5"><?php echo $inputCommentReserv; ?></textarea>
							</div>
						</div>
						<div class="control-group">
							<label class="control-label"><input class="btn btn-warning btn-mini" type="button" name="actu_captcha" ID="cap" onclick="goAction('RE_CAPTCHA');" value="<?php echo $tr->translate("thUserformNewPicture", "default", $lang); ?>"/></label>
							<div class="controls">
								<img src="<?php echo $captcha->getImgUrl() . $captcha->getId() . ".png"; ?>" width="200" height="80" >
							</div>
						</div>
						<div class="control-group">
							<label class="control-label" for="inputCaptcha"><?php echo $tr->translate("thUserformCaptchaText", "default", $lang); ?> <a name="help" id="help" href="#">(<?php echo $tr->translate("thUserformHelp", "default", $lang); ?>)</a></label>
							<div class="controls">
								<input class="input-mini" id="inputCaptcha" name="inputCaptcha" type="text" /></div>
							</div>
						</div>
					</div>
					<div class="form-actions">
						<button type="btn" name="send" id="send" class="btn btn-primary btn-large span10"><?php echo $tr->translate("thUserformSendUserRequest", "default", $lang); ?></button>
						<div class="clearfix"></div>
						<div><?php echo $tr->translate("thUserformFooter", "default", $lang); ?></div>
					</div>
			</form>
		<?php } ?>
		<?php } ?>

	</div> <!--   fin de div container-->
<?php if (file_exists("help_userform_" . $config['language'] . ".php")) include("help_userform_" . $config['language'] . ".php"); ?>
<?php Logger::info('END User Form rendering'); ?> 
<?php require "../_container/container_bottom.php"; ?>
<script>
	$(document).ready(function() {
		$("body").css("background-color", "#<?php echo $config['color_cal_bgd']; ?>");
		$("#userForm").validate({
			rules: {
				inputName: {required: true},
				inputLastname: {required: true},
				startDate: {required: true},
				endDate: {required: true},
				inputAdults: {required: true, number: true, min:1},
				inputChilds: {required: true, number: true},
				inputBaby: {required: true, number: true},
				inputCaptcha: {required: true},
				inputPhone: {required: function() {
						return (($('#inputPhone').val().length == 0) && ($('#inputCellphone').val().length == 0) && ($('#inputEmail').val().length == 0));
						}},
				inputCellphone: {required: function() {
						return (($('#inputPhone').val().length == 0) && ($('#inputCellphone').val().length == 0) && ($('#inputEmail').val().length == 0));
						}},
				inputEmail: {required: function() {
						return (($('#inputPhone').val().length == 0) && ($('#inputCellphone').val().length == 0) && ($('#inputEmail').val().length == 0));
						}, email: true}
			},
			errorPlacement: function(error, element) {
				error.appendTo($(element).parent());
			},
			messages: {
				inputAdults: {
					min: "<?php echo $tr->translate("msgUserformSelectAdult", "default", $lang); ?>"
				},
				inputPhone: {
					required: "<?php echo $tr->translate("msgUserformEmailMissing", "default", $lang); ?>"
				},
				inputCellphone: {
					required: "<?php echo $tr->translate("msgUserformEmailMissing", "default", $lang); ?>"
				},
				inputEmail: {
					required: "<?php echo $tr->translate("msgUserformEmailMissing", "default", $lang); ?>"
				}
			}
		});
	});

	$("#help").click(function(e){
		$("#helpModal").modal('show');
	});
	
	$("#send").click(function(e){
		if ($('#startDate').val() != '' && $('#endDate').val() != '') {
			if (!(moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>").isValid())){
				alert("<?php echo $tr->translate("msgUserformInvalidStartDate", "default", $lang); ?>");
				return false;
			}
			if (!(moment($('#endDate').val(),"<?php echo $config['date_format_js_moment']; ?>").isValid())){
				alert("<?php echo $tr->translate("msgUserformInvalidEndDate", "default", $lang); ?>");
				return false;
			}
			var start = moment($('#startDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");
			var end = moment($('#endDate').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");

			if (moment(end).isBefore(start)) {
				alert("<?php echo $tr->translate("msgUserformEndBeforeStart", "default", $lang); ?>");
				return false;
			}
			if (moment(end).isSame(start)) {
				alert("<?php echo $tr->translate("msgUserformSameDate", "default", $lang); ?>");
				return false;
			}
			$('#start_date').val(start);
			$('#end_date').val(end);

			// $("#reservationForm").attr("action", "reservation.php");
			$("#action").val($(this).attr("id"));
			// reservationForm.submit();
		}
	});
	function goAction(action){
		if (action == "RE_CAPTCHA"){
			$("#action").val("RE_CAPTCHA");
			userForm.submit();
		}
	}
	$('#startDate').change(function(){
		$('#endDate').datepicker( "option", "minDate", $('#startDate').val());
	});
</script>
