<?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/TenancyMgr.php');
	require_once ('business/PaymentMgr.php');
	require_once ('business/UserMgr.php');
	require_once ('business/MailMgr.php');
	require_once ("config/Tagger.php");

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

	$query = getPost('query');

	include_once ("actionList.php");

	$arrReservation = $reservationMgr->searchReservation($query);
	$arrTenant = $tenantMgr->searchTenant($query);
	$arrTenancy = $tenancyMgr->searchTenancy($query);
	$arrUser = $userMgr->searchUser($query);

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

	if (empty($query) || empty($arrReservation)) $arrReservation = array();
	if (empty($query) || empty($arrTenant)) $arrTenant = array();
	if (empty($query) || empty($arrTenancy)) $arrTenancy = array();
	if (empty($query) || empty($arrUser)) $arrUser = array();
?>
	<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("Search"); if (!empty($query)) echo " [" . $query . "]"; ?></a></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>
	<div class="row-fluid sortable">
		<div class="box span12">
			<form class="form-horizontal" method="post" name="trackingForm" id="trackingForm" action="search.php">
				<input type="hidden" name="action" id="action" value="" />
				<input type="hidden" name="status" id="status" value="" />
				<input type="hidden" name="query" id="query" value="<?php echo $query; ?>" />
				<input type="hidden" name="tenantid" id="tenantid" value="" />
				<input type="hidden" name="tenancyid" id="tenancyid" value="" />
				<input type="hidden" name="userid" id="userid" value="" />
				<input type="hidden" name="lease_date" id="lease_date" value="" />
				<input type="hidden" name="reservationid" id="reservationid" value="" />
			<div class="box-header well" data-original-title>
				<h2><i class="icon-picture"></i> <?php echo $tr->translate("searchReserv"); ?></h2>
			</div>
			<div class="box-content">
			<?php if (!empty($arrReservation)) { ?>
				<div class="table-responsive">
				<table id="tableSearchReserv" name="tableSearchReserv" 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("LeaseDate"); ?></th>
							<th><?php echo $tr->translate("Status"); ?></th>
							<th><?php echo $tr->translate("thReservAction"); ?></th>
						</tr>
					</thead>   
					<tbody>
						<?php foreach ($arrReservation as $reserv) {
							$leaseDays =  round((time() - strtotime($reserv->lease_date))/86400);
							$arrPayment = $paymentMgr->getPaymentByReservation($reserv->reservation_id);
							$arr = array();
							$arr[] = $reserv;

						?>
						<tr id="<?php echo $reserv->reservation_id; ?>" data-deposit="<?php echo $reserv->deposit; ?>">
							<td><?php echo $reserv->reservation_id; ?></td>
							<td class="<?php if (stristr($reserv->tenancy_name, $query)) echo "alert"; ?>"><?php echo $reserv->tenancy_name; ?></td>
							<td class="<?php if (stristr($reserv->tenant_lastname, $query)) echo "alert"; ?>">
								<a data-toggle="modal" data-target="#myModal" data-tenantid="<?php echo $reserv->tenant_id; ?>" class="tenant-popup icon-question-sign" href="#"></a>
							<?php echo $reserv->tenant_lastname; ?></td>
							<td class="<?php if (stristr($reserv->tenant_name, $query)) echo "alert"; ?>"><?php echo $reserv->tenant_name; ?></td>
							<td class="<?php if (stristr(date($config['date_format'], strtotime($reserv->arrival_date)), $query)) echo "alert"; ?>"><?php echo date($config['date_format'], strtotime($reserv->arrival_date)); ?></td>
							<td class="<?php if (stristr(date($config['date_format'], strtotime($reserv->departure_date)), $query)) echo "alert"; ?>"><?php echo date($config['date_format'], strtotime($reserv->departure_date)); ?></td>
							<td><?php echo round((strtotime($reserv->departure_date) - strtotime($reserv->arrival_date))/86400); ?></td>
							<td class="<?php if (stristr($reserv->price, $query)) echo "alert"; ?>"><?php echo $reserv->price; ?></td>
							<td class="<?php 
								$payment = (isset($arrBalance[$reserv->reservation_id])) ? $arrBalance[$reserv->reservation_id] : 0;
								// $balance = number_format((float)$reserv->price - $payment + $extra, 2, '.', '');
								$balance = number_format((float)getBalance($arr, array(), $arrPayment, $config), 2, '.', '');
								// if (($payment == 0) || ($balance < 0)) {echo "td-error";} ?>">
								<?php echo $balance; ?>
							</td>
							<td>
								<div class="row-fuild">
									<span><?php
											if (isset($reserv->lease_date)) {
												echo date($config['date_format'], strtotime($reserv->lease_date));
											if ($reserv->status < ReservationMgr::RESERV_VALIDATE) {
											?>
											<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipClearLeaseDate"); ?>" data-rel="tooltip" href="#" onclick="goAction('CLEAR_LEASE_DATE', <?php echo $reserv->reservation_id; ?>);">
												<i class="icon-trash"></i>
											</a>

											<?php } ?>
											<?php }else{ ?>

										<div class="input-append"><input type="text" class="datepicker input-small" name="leaseDate<?php echo $reserv->reservation_id; ?>" id="leaseDate<?php echo $reserv->reservation_id; ?>" value="<?php
											echo date($config['date_format']);
											?>"><span class="add-on"><i class="icon-calendar"></i></span>

										</div>
											<a class="btn btn-primary btn-mini" title="<?php echo $tr->translate("tipSetLeaseDate"); ?>" data-rel="tooltip" href="#" onclick="goAction('SET_LEASE_DATE', <?php echo $reserv->reservation_id; ?>);">
												<i class="icon-ok"></i>
											</a>

											<?php } ?>
									</span>
								</div>
							</td>
							<td>
								<span class="tracking" data-search="<?php echo $reserv->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 ($reserv->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 ($reserv->status >= ReservationMgr::RESERV_LEASE_SENT) echo "current"; if ($reserv->status == ReservationMgr::RESERV_LEASE_SENT && $reserv->lease_date && ($leaseDays >= $config['lease_reminder_delay'])) echo " error"; ?>"><i class="badge icon-envelope icon-large"></i><small><?php if ($reserv->status == ReservationMgr::RESERV_LEASE_SENT && $reserv->lease_date && ($leaseDays >= $config['lease_reminder_delay'])) echo $leaseDays; ?></small></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 ($reserv->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 ($reserv->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 $reserv->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 $reserv->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 $reserv->tenancy_id; ?>&y=<?php echo date("Y"); ?>">
									<i class="icon-calendar icon-white"></i>
								</a>
							</td>
						</tr>
						<?php } ?>
					</tbody>
				</table>
				</div>
				<?php }else{ ?>
					<div class="alert"><?php echo $tr->translate("searchNoResult"); ?></div>
				<?php } ?>
			</div><!--/box-content-->
		</form>

		</div><!--/span-->
	</div><!--/row-->
	<div class="row-fluid sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title>
				<h2><i class="icon-picture"></i> <?php echo $tr->translate("searchTenant"); ?></h2>
			</div>
			<div class="box-content">
			<?php if (!empty($arrTenant)) { ?>
				<div class="table-responsive">
				<table id="tableSearchTenant" name="tableSearchTenant" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
							<th><?php echo $tr->translate("thTenantLastName"); ?></th>
							<th><?php echo $tr->translate("thTenantName"); ?></th>
							<th><?php echo $tr->translate("thTenantAddress1"); ?></th>
							<th><?php echo $tr->translate("thTenantZipCode"); ?></th>
							<th><?php echo $tr->translate("thTenantCity"); ?></th>
							<th><?php echo $tr->translate("thTenantCountry"); ?></th>
							<th><?php echo $tr->translate("thTenantPhone"); ?></th>
							<th><?php echo $tr->translate("thTenantMobile"); ?></th>
							<th><?php echo $tr->translate("thTenantEmail"); ?></th>
							<th><?php echo $tr->translate("thTenantComment"); ?></th>
							<th><?php echo $tr->translate("thTenantAction"); ?></th>
						</tr>
					</thead>   
					<tbody>
						<?php foreach ($arrTenant as $tenant) { ?>
						<tr>
							<td class="<?php if (stristr($tenant->lastname, $query)) echo "alert"; ?>"><?php echo $tenant->lastname; ?></td>
							<td class="<?php if (stristr($tenant->name, $query)) echo "alert"; ?>"><?php echo $tenant->name; ?></td>
							<td class="<?php if (stristr($tenant->address1, $query)) echo "alert"; ?>"><?php echo $tenant->address1; ?></td>
							<td class="<?php if (stristr($tenant->zipcode, $query)) echo "alert"; ?>"><?php echo $tenant->zipcode; ?></td>
							<td class="<?php if (stristr($tenant->city, $query)) echo "alert"; ?>"><?php echo $tenant->city; ?></td>
							<td class="<?php if (stristr($tenant->country, $query)) echo "alert"; ?>"><?php echo $tenant->country; ?></td>
							<td class="<?php if (stristr($tenant->phone, $query)) echo "alert"; ?>"><?php echo $tenant->phone; ?></td>
							<td class="<?php if (stristr($tenant->cellphone, $query)) echo "alert"; ?>"><?php echo $tenant->cellphone; ?></td>
							<td class="<?php if (stristr($tenant->email, $query)) echo "alert"; ?>">
							<?php if ($tenant->email) { ?>
								<a class="icon-envelope" href="mailto:<?php echo $tenant->email; ?>"></a>
							<?php } ?>
							<?php echo $tenant->email; ?></td>
							<td class="<?php if (stristr($tenant->comment, $query)) echo "alert"; ?>"><?php echo getTextSummary($tenant->comment); ?></td>
							<td>
								<a class="btn btn-info btn-mini btn-action" title="<?php echo $tr->translate("tipTenantEdit"); ?>" data-rel="tooltip" href="#" _id="<?php echo $tenant->tenant_id; ?>" _page="tenantDetail.php" _caption="<?php echo $tr->translate("EditTenynt"); ?>" _action="<?php echo $tr->translate("actionEdit"); ?>">
									<i class="icon-edit icon-white"></i>
								</a>
								<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipTenantDelete"); ?>" data-rel="tooltip" href="#" onclick="goAction('DELETE_TENANT', <?php echo $tenant->tenant_id; ?>);">
									<i class="icon-trash icon-white"></i>
								</a>
							</td>
						</tr>
						<?php } ?>
					</tbody>
				</table>
				</div
				<?php }else{ ?>
					<div class="alert"><?php echo $tr->translate("searchNoResult"); ?></div>
				<?php } ?>
			</div><!--/box-content-->
		</div><!--/span-->
	</div><!--/row-->
	<div class="row-fluid sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title>
				<h2><i class="icon-picture"></i> <?php echo $tr->translate("searchTenancy"); ?></h2>
			</div>
			<div class="box-content">
			<?php if (!empty($arrTenancy)) { ?>
				<div class="table-responsive">
				<table id="tableSearchTenancy" name="tableSearchTenancy" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
							<th><?php echo $tr->translate("thTenancyName"); ?></th>
							<th><?php echo $tr->translate("thTenancyAddress1"); ?></th>
							<th><?php echo $tr->translate("thTenancyAddress2"); ?></th>
							<th><?php echo $tr->translate("thTenancyZipCode"); ?></th>
							<th><?php echo $tr->translate("thTenancyCity"); ?></th>
							<th><?php echo $tr->translate("thTenancyCountry"); ?></th>
							<th><?php echo $tr->translate("thTenancyComment"); ?></th>
							<th><?php echo $tr->translate("thTenancyAction"); ?></th>
						</tr>
					</thead>   
					<tbody>
						<?php foreach ($arrTenancy as $tenancy) { ?>
						<tr>
							<td class="<?php if (stristr($tenancy->name, $query)) echo "alert"; ?>"><?php echo $tenancy->name; ?></td>
							<td class="<?php if (stristr($tenancy->address1, $query)) echo "alert"; ?>"><?php echo $tenancy->address1; ?></td>
							<td class="<?php if (stristr($tenancy->address2, $query)) echo "alert"; ?>"><?php echo $tenancy->address2; ?></td>
							<td class="<?php if (stristr($tenancy->zipcode, $query)) echo "alert"; ?>"><?php echo $tenancy->zipcode; ?></td>
							<td class="<?php if (stristr($tenancy->city, $query)) echo "alert"; ?>"><?php echo $tenancy->city; ?></td>
							<td class="<?php if (stristr($tenancy->country, $query)) echo "alert"; ?>"><?php echo $tenancy->country; ?></td>
							<td class="<?php if (stristr($tenancy->comment, $query)) echo "alert"; ?>"><?php echo getTextSummary($tenancy->comment); ?></td>
							<td>
								<a class="btn btn-info btn-mini btn-action" title="<?php echo $tr->translate("tipTenancyEdit"); ?>" data-rel="tooltip" href="#" _id="<?php echo $tenancy->tenancy_id; ?>" _page="tenancyDetail.php" _caption="<?php echo $tr->translate("EditTenancy"); ?>" _action="<?php echo $tr->translate("actionEdit"); ?>">
									<i class="icon-edit icon-white"></i>
								</a>
								<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipTenancyDelete"); ?>" data-rel="tooltip" href="#" onclick="goAction('DELETE_TENANCY', <?php echo $tenancy->tenancy_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 $tenancy->tenancy_id; ?>&y=<?php echo date("Y"); ?>">
									<i class="icon-calendar icon-white"></i>
								</a>
							</td>
						</tr>
						<?php } ?>
					</tbody>
				</table>
				</div>
				<?php }else{ ?>
					<div class="alert"><?php echo $tr->translate("searchNoResult"); ?></div>
				<?php } ?>
			</div><!--/box-content-->
		</div><!--/span-->
	</div><!--/row-->
	
	<div class="row-fluid sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title>
				<h2><i class="icon-picture"></i> <?php echo $tr->translate("searchUser"); ?></h2>
			</div>
			<div class="box-content">
			<?php if (!empty($arrUser)) { ?>
				<div class="table-responsive">
				<table id="tableSearchUser" name="tableSearchUser" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
							<th><?php echo $tr->translate("thUserName"); ?></th>
							<th><?php echo $tr->translate("thUserEmail"); ?></th>
							<th><?php echo $tr->translate("thUserComment"); ?></th>
							<th><?php echo $tr->translate("thUserEnabled"); ?></th>
							<th><?php echo $tr->translate("thUserAction"); ?></th>
						</tr>
					</thead>   
					<tbody>
						<?php foreach ($arrUser as $user) { ?>
						<tr>
							<td class="<?php if (stristr($user->username, $query)) echo "alert"; ?>"><?php echo $user->username; ?></td>
							<td class="<?php if (stristr($user->email, $query)) echo "alert"; ?>">
							<?php if ($user->email) { ?>
								<a class="icon-envelope" href="mailto:<?php echo $user->email; ?>"></a>
							<?php } ?>
							<?php echo $user->email; ?></td>
							<td class="<?php if (stristr($user->comment, $query)) echo "alert"; ?>"><?php echo getTextSummary($user->comment); ?></td>
							<td>
								<span class="label label-<?php if ($user->enable) { echo "success";}else{ echo "important"; }?>"><?php echo $user->enable; ?></span>
							</td>
							<td>
								<a class="btn btn-info btn-mini btn-action" title="<?php echo $tr->translate("tipUserEdit"); ?>" data-rel="tooltip" href="#" _id="<?php echo $user->user_id; ?>" _page="userDetail.php" _action="<?php echo $tr->translate("Edit"); ?>">
									<i class="icon-edit icon-white"></i>
								</a>
								<a class="btn btn-danger btn-mini" title="<?php echo $tr->translate("tipUserDelete"); ?>" data-rel="tooltip" href="#" onclick="goAction('DELETE_USER', <?php echo $user->user_id; ?>);">
									<i class="icon-trash icon-white"></i>
								</a>
							</td>
						</tr>
						<?php } ?>
					</tbody>
				</table>
				</div>
				<?php }else{ ?>
					<div class="alert"><?php echo $tr->translate("searchNoResult"); ?></div>
				<?php } ?>
			</div><!--/box-content-->
		</div><!--/span-->
	</div><!--/row-->

<?php require "../_container/container_bottom.php"; ?>
<script>
	function deleteAction() {
		blockUI();
		trackingForm.submit();
	}

	function goAction(action, id) {
		if (action == "SET_LEASE_DATE") {
			$("#action").val(action);
			$("#reservationid").val(id);

			var lease_date = moment($("#leaseDate"+id).val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");
			if (!(moment($("#leaseDate"+id).val(),"<?php echo $config['date_format_js_moment']; ?>").isValid())){
				alert("<?php echo $tr->translate("msgInvalidDate"); ?>");
				return false;
			}
			$("#lease_date").val(lease_date);
			// $('#content').slideUp("slow");
			blockUI();
			trackingForm.submit();
		}
		if (action == "CLEAR_LEASE_DATE") {
			$("#action").val(action);
			$("#reservationid").val(id);
			$("#dialog-confirm").dialog("open");
		}
		if (action == "DELETE_TENANT") {
			$('#trackingForm').attr('action','tenant.php');
			$("#action").val(action);
			$("#tenantid").val(id);
			$("#dialog-confirm").dialog("open");
		}
		if (action == "DELETE_TENANCY") {
			$('#trackingForm').attr('action','tenancy.php');
			$("#action").val(action);
			$("#tenancyid").val(id);
			$("#dialog-confirm").dialog("open");
		}
		if (action == "DELETE_USER"){
			$('#trackingForm').attr('action','user.php');
			$("#action").val(action);
			$("#userid").val(id);
			$("#dialog-confirm").dialog("open");
		}
		if (action == "DELETE_RESERV"){
			$('#trackingForm').attr('action','reservation.php');
			$("#action").val(action);
			$("#reservationid").val(id);
			$("#dialog-confirm").dialog("open");
		}
	}

</script>