<?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).
 *
 *******************************************************************************
*/

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

	$reservationMgr = new ReservationMgr();
	$tenantMgr = new TenantMgr();
	$paymentMgr = new PaymentMgr();
	$mailMgr = new MailMgr();
	$tagger = new Tagger();

	$query = getPost('query');
	$action = getPost('action');
	$reservationid = getPost('reservationid');

	$filter_year = getPost('filter_year');
	if (empty($filter_year)) {
		$filter_year = date("Y");
	}

	// print_r($_POST);
	include_once ("actionList.php");

	if (!empty($action) && ($action == "UPDATE_RESERV" || $action == "printlease" || $action == "enable" || $action == "ADD_RESERV" || $action == "SEND_LEASE_FILE" || $action == "CREATE_INVOICE")) {
		if ($action == "ADD_RESERV") {
			if ($config['allow_duplicate_reservation']){
				$arrAllReservations = array();
			}else{
				$arrAllReservations = $reservationMgr->isReservationAvailable(getPost('start_date'), getPost('end_date'), getPost('selectTenancy'), ReservationMgr::RESERV_OPTION);
			}

			if (empty($arrAllReservations)){
				if (getPost('radioTenant') != 'yes'){
					$tenant = array();
					$tenant['title'] = getPost('inputTitle');
					$tenant['name'] = getPost('inputName');
					$tenant['lastname'] = getPost('inputLastname');
					$tenant['reference'] = getPost('inputReference');
					$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['fax'] = getPost('inputFax');
					$tenant['email'] = getPost('inputEmail');
					$tenant['newsletter'] = getPost('inputNewsletter');
					$tenant['comment'] = getPost('inputComment');
					$tenant['language'] = getPost('inputLanguage');
					$newTenantId = $tenantMgr->insert($tenant);
					Logger::debug('Add tenant result ID: ' . $newTenantId);
				}else{
					$newTenantId = getPost('selectTenant');
					Logger::debug('tenant ID : ' . $newTenantId);
				}
				if ($newTenantId > 0) {
					$reservation = array();
					$reservation['tenancy_id'] = getPost('selectTenancy');
					$reservation['tenant_id'] = $newTenantId;
					$reservation['arrival_date'] = getPost('start_date');
					$reservation['departure_date'] = getPost('end_date');
					$px = getPost('inputPriceTotal');
					$reservation['price'] = ($px == '') ? 0 : $px;
					$reservation['vat'] = getPost('inputVat');
					$deposit = ($px == '') ? 0 : round($config['lease_deposit_percent'] * $px / 100, 2);
					$reservation['deposit'] = number_format((float)$deposit, 2, '.', '');
					$reservation['adults_nb'] = getPost('inputAdults');
					$reservation['childs_nb'] = getPost('inputChilds');
					$reservation['baby_nb'] = getPost('inputBaby');
					$reservation['disabled'] = getPost('inputDisabled');
					$reservation['comment'] = getPost('inputCommentReserv');
					$reservation['reference'] = getPost('inputReferenceResa');
					$reservation['status'] = ReservationMgr::RESERV_OPTION;
					// print_r($reservation);
					$res = $reservationMgr->insert($reservation);
					Logger::debug('Add reserv: ' . $res);
					if ($res > 0) {
					
					
						$mail = $mailMgr->getMail(10);
						$msgType = "success";
						$msg = $tr->translate("msgSuccess");
						if (isset($mail) && !empty($mail[0]->enable)){
							$tagger->setReservationId($res);
							$mail[0]->from = $config['renter_email'];
							$mail[0]->to = $tagger->tag($mail[0]->to);
							$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);

							include_once ('config/Mailer.php');
							$m = new Mailer($config);
							$r = $m->sendMail($mail);
							if (!$r) {
								$msgType = "error";
								$msg = $tr->translate("msgMailError");
							}
						}
					}else{
						$msgType = "error";
						$msg = $tr->translate("msgError");
						// $msg = "Failed to add Reservation for existing Tenant";
					}
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgAlreadyBooked");
				foreach ($arrAllReservations as $res) {
					$msg .= "<hr>ID: ". $res->reservation_id;
					$msg .= "<br>".  $tr->translate("Name") . ": " . $res->tenant_lastname . " " . $res->tenant_name;
					$msg .= "<br>" . $tr->translate("From") . "/" . $tr->translate("To") . ": " . date($config['date_format'], strtotime($res->arrival_date)) . " / " . date($config['date_format'], strtotime($res->departure_date));
					$msg .= "<br>" . $tr->translate("Status") . ": " . $res->status;
					$msg .= "<br>" . $tr->translate("Price") . ": " . $res->price;
				}
			}
		}

		if ($action == "UPDATE_RESERV") {
			$reservation = array();
			$reservation['reservation_id'] = $reservationid;
			$reservation['tenancy_id'] = getPost('selectTenancy');
			$reservation['tenant_id'] = getPost('selectTenant');
			$reservation['arrival_date'] = getPost('start_date');
			$reservation['departure_date'] = getPost('end_date');
			$reservation['price'] = getPost('inputPriceTotal');
			$reservation['vat'] = getPost('inputVat');
			$reservation['adults_nb'] = getPost('inputAdults');
			$reservation['childs_nb'] = getPost('inputChilds');
			$reservation['baby_nb'] = getPost('inputBaby');
			$reservation['disabled'] = getPost('inputDisabled');
			$reservation['comment'] = getPost('inputCommentReserv');
			$reservation['reference'] = getPost('inputReferenceResa');
			// print_r($reservation);

			$res = $reservationMgr->update($reservation);

			// if ($res == 0) {
				// $msgType = "error";
				// $msg = $tr->translate("msgError");
			// }else{
				// $msgType = "success";
				// $msg = $tr->translate("msgSuccess");
			// }
			$msgType = "success";
			$msg = $tr->translate("msgSuccess");
		}

		if ($action == "SEND_LEASE_FILE") {
			require_once("lib/myUpload.php");
			$upload = new MYUPLOAD('uploadfile_Path');
			$upload->set_directory(ROOT . "data/img/tenancy");
			$tenancyId = getPost('selectTenancy');
			$upload->set_file_name("tenancy_" . $tenancyId . "_" . str_replace(' ', '_', $_FILES['uploadfile_Path']['name']));
			$res = $upload->copy_file();
			if ($res && ($res[0] != 'error')){
				$msgType = $res[0];
				$msg = $res[1];
				$reserv = array();
				$reserv['reservation_id'] = $reservationid;
				$reserv['lease_date'] = date('Y-m-d H:i:s');
				$reserv['status'] = ReservationMgr::RESERV_LEASE_SENT;
				$res = $reservationMgr->update($reserv);
				if ($res == 1) {
					$mail = $mailMgr->getMail(2);
					$msgType = "success";
					$msg = $tr->translate("msgSuccess");
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
				if (isset($mail) && !empty($mail[0]->enable)){
					$tagger->setReservationId($reservationid);

					$mail[0]->file[] = array(ROOT . "data/img/tenancy/" . $upload->user_file_name => $_FILES['uploadfile_Path']['type']);
					$mail[0]->from = $config['renter_email'];
					$mail[0]->to = $tagger->tag($mail[0]->to);
					$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);

					include_once ('config/Mailer.php');
					$m = new Mailer($config);
					$r = $m->sendMail($mail);
					if (!$r) {
						$msgType = "error";
						$msg = $tr->translate("msgMailError");
					}
					unlink(ROOT . "data/img/tenancy/" . $upload->user_file_name);
				}
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
				// $msg = "File upload: general error";
			}
		}

		echo '<div class="alert alert-' . $msgType . '">
			<strong>' . $msg . '</strong>
			</div>';
	}

	$arrAllPayment = $paymentMgr->getPayments();
	$arrBalance = array_reduce($arrAllPayment, function($result, $item) {
		if (!isset($result[$item->reservation_id])) $result[$item->reservation_id] = 0;
		$result[$item->reservation_id] += $item->amount;
		return $result;
	}, array());
	// print_r($arrBalance);

	$arrAllReservations = $reservationMgr->getReservations();

// Get all years where there is a reservation
	$start_years = ( array_map(
		function($item){
			return date("Y",strtotime($item->arrival_date));
		},
		$arrAllReservations));
	$end_years = ( array_map(
		function($item){
			return date("Y",strtotime($item->departure_date));
		},
		$arrAllReservations));

	$arrYears = array_unique(array_merge($start_years,$end_years));
	asort($arrYears);
	if (!in_array($filter_year, $arrYears)) {
		$filter_year = "All";
	}

?>
	<div>
		<ul class="breadcrumb">
			<li><a href="./"><?php echo $tr->translate("menuHome"); ?></a> <span class="divider">/</span></li>
			<li class="active"><?php echo $tr->translate("menuReservations"); ?></li>
		</ul>
	</div>
	<div class="sortable row-fluid">
		<a data-rel="tooltip" title="<?php echo $tr->translate('AddReserv'); ?>" class="well span2 top-block btn-action" href="#" name="newReservation" id="newReservation" _page="reservationDetail.php" _action="Add">
			<i class="icon-red icon-user"></i>
			<div><?php echo $tr->translate("AddReserv"); ?></div>
			<div></div>
		</a>
		<a data-rel="tooltip" title="<?php echo $tr->translate("AddPayment"); ?>" class="well span2 top-block btn-action" href="#" name="newPayment" id="newPayment" _page="paymentDetail.php" _action="Add">
			<i class="icon-cog"></i>
			<div><?php echo $tr->translate("AddPayment"); ?></div>
			<div></div>
		</a>
	</div>
<form class="form-horizontal" method="post" name="trackingForm" id="trackingForm" action="">
<input type="hidden" name="action" id="action" value="" />
<input type="hidden" name="status" id="status" value="" />
<input type="hidden" name="reservprice" id="reservprice" value="" />
<input type="hidden" name="lease_date" id="lease_date" value="" />
<input type="hidden" name="reservationid" id="reservationid" value="<?php echo $reservationid; ?>" />
	<div class="row-fluid sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title>
				<h2><i class="icon-user"></i> <?php echo $tr->translate("Filter"); ?></h2>
			</div>
			<div class="box-content">
				<div class="row-fluid sortable">
					<div class="span4">
								<fieldset>
									<div class="control-group">
										<label class="control-label" for="filter_year"><?php echo $tr->translate("Year"); ?></label>
										<div class="controls">
											<select name="filter_year" id="filter_year" data-rel="chosen" class="filter-action">
											<option value="All" <?php if ($filter_year == "All") echo " selected"; ?>><?php echo $tr->translate("All"); ?></option>
											<?php foreach ($arrYears as $val) { ?>
												<option value="<?php echo $val;?>" <?php if ($filter_year == $val) echo " selected"; ?>><?php echo $val;?></option>
											<?php } ?>
											</select>
										</div>
									</div>
								</fieldset>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="row-fluid sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title>
				<h2><i class="icon-user"></i> <?php echo $tr->translate("Reservations"); ?></h2>
			</div>
			<div class="box-content">
			<div class="table-responsive">
				<table id="tableReservations" name="tableReservations" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
					  		<th><?php echo $tr->translate("ID"); ?></th>
							<th><?php echo $tr->translate("thReservTenancy"); ?></th>
							<th><?php echo $tr->translate("thReservLastName"); ?></th>
							<th><?php echo $tr->translate("thReservName"); ?></th>
							<th><?php echo $tr->translate("thReservFrom"); ?></th>
							<th><?php echo $tr->translate("thReservTo"); ?></th>
							<th><?php echo $tr->translate("Days"); ?></th>
							<th><?php echo $tr->translate("thReservPrice"); ?></th>
							<th><?php echo $tr->translate("thReservBalance"); ?></th>
							<th><?php echo $tr->translate("thReservComment"); ?></th>
							<th><?php echo $tr->translate("thReservStatus"); ?></th>
							<th><?php echo $tr->translate("thReservAction"); ?></th>
						</tr>
				  </thead>   
				  <tbody>
				  <?php
					$firstDay = $filter_year . '-01-01';
					$lastDay = $filter_year . '-12-31';
					foreach ($arrAllReservations as $reservation) {
						if ($filter_year == date("Y",strtotime($reservation->arrival_date)) || $filter_year == date("Y",strtotime($reservation->departure_date)) || $filter_year == "All") {
							$arrPayment = $paymentMgr->getPaymentByReservation($reservation->reservation_id);
							$arr = array();
							$arr[] = $reservation;
				  ?>
					<tr id="<?php echo $reservation->reservation_id; ?>" data-deposit="<?php echo $reservation->deposit; ?>">
						<td><?php echo $reservation->reservation_id; ?></td>
						<td><?php echo $reservation->tenancy_name; ?></td>
						<td>
							<a data-toggle="modal" data-target="#myModal" data-tenantid="<?php echo $reservation->tenant_id; ?>" class="tenant-popup icon-question-sign" href="#"></a>
							<?php echo $reservation->tenant_lastname; ?>
						</td>
						<td><?php echo $reservation->tenant_name; ?></td>
						<td><?php echo date($config['date_format'], strtotime($reservation->arrival_date)); ?></td>
						<td><?php echo date($config['date_format'], strtotime($reservation->departure_date)); ?></td>
						<td><?php echo round((strtotime($reservation->departure_date) - strtotime($reservation->arrival_date))/86400); ?></td>
						<td><?php echo $reservation->price; ?></td>
						<td class="<?php 
							$payment = (isset($arrBalance[$reservation->reservation_id])) ? $arrBalance[$reservation->reservation_id] : 0;
							// $balance = number_format((float)$reservation->price - $payment + $extra, 2, '.', '');
							$balance = number_format((float)getBalance($arr, array(), $arrPayment, $config), 2, '.', '');
							// if ($balance > 0) {echo "td-error";} ?>">
							<?php echo $balance; ?>
						</td>
						
						<td><?php echo getTextSummary($reservation->comment); ?></td>
						<td class="center">
							<span class="tracking" data-search="<?php echo $reservation->status; ?>">
								<a name="<?php echo ReservationMgr::RESERV_OPTION; ?>" title="<?php echo $tr->translate("Tracking1"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($reservation->status >= ReservationMgr::RESERV_OPTION) echo "current"; ?>"><i class="badge icon-question-sign icon-large"></i></a>
								<a name="<?php echo ReservationMgr::RESERV_LEASE_SENT; ?>" title="<?php echo $tr->translate("Tracking2"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($reservation->status >= ReservationMgr::RESERV_LEASE_SENT) echo "current"; ?>"><i class="badge icon-envelope icon-large"></i></a>
								<a name="<?php echo ReservationMgr::RESERV_VALIDATE; ?>" title="<?php echo $tr->translate("Tracking3"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($reservation->status >= ReservationMgr::RESERV_VALIDATE) echo "current"; ?>"><i class="badge icon-ok icon-large"></i></a>
								<a name="<?php echo ReservationMgr::RESERV_CLOSED; ?>" title="<?php echo $tr->translate("Tracking4"); ?>" data-rel="tooltip" data-placement="top" class="tracking-element <?php if ($reservation->status >= ReservationMgr::RESERV_CLOSED) echo "current"; ?>"><i class="badge icon-usd icon-large"></i></a>
							</span>
						</td>
						<td>
							<a class="btn btn-info btn-mini btn-action" title="<?php echo $tr->translate("tipEditReserv"); ?>" data-rel="tooltip" href="#" _id="<?php echo $reservation->reservation_id; ?>" _page="reservationDetail.php" _action="Edit">
								<i class="icon-edit icon-white"></i>
							</a>
							<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipDeleteReserv"); ?>" data-rel="tooltip" href="#" onclick="goAction('DELETE_RESERV', <?php echo $reservation->reservation_id; ?>);">
								<i class="icon-trash icon-white"></i>
							</a>
							<a target="calendar" class="btn btn-success btn-mini" title="<?php echo $tr->translate("tipShowCal"); ?>" data-rel="tooltip" href="calendar.php?id=<?php echo $reservation->tenancy_id; ?>&y=<?php echo $filter_year; ?>">
								<i class="icon-calendar icon-white"></i>
							</a>
						</td>
					</tr>
					<?php }
						} ?>
				  </tbody>
			  </table>
			  </div>
			</div>
		</div><!--/span-->
	
	</div><!--/row-->
</form>
	<div class="row-fluid sortable" id="editReservation">
	</div><!--/row-->

<?php require "../_container/container_bottom.php"; ?>
<script>
// TODO When delte reserv, fileter is set to ALL but no reservation listed.
// Implement in ALLLLL form the same behavior:
// preventdefault for btn form-action
// CAPS LOCK for event in goAction

	function deleteAction() {
		blockUI();
		trackingForm.submit();
	}

	function goAction(action, id) {
		if (action == "DELETE_RESERV") {
			$("#action").val(action);
			$("#reservationid").val(id);
			$("#dialog-confirm").dialog("open");
		}
	}

	$(document).ready(function() {
		if ($('#tableReservations').length) {
			myTable = $('#tableReservations').dataTable();
			var oSettings = myTable.fnSettings();
			oSettings.aoColumns[4].sType = "custom-date";
			oSettings.aoColumns[5].sType = "custom-date";
			oSettings.aoColumns[10].sType = "custom-numeric";
		}
	});

</script>