<?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";
	include_once ('business/PaymentMgr.php');
	include_once ('business/ReservationMgr.php');
	
	$paymentMgr = new PaymentMgr();
	$reservationMgr = new ReservationMgr();
	
	$action = getPost('action');
	$id = getPost('id');

	if (empty($action)) $action = "Add";
	$add = ($action == "Add") ? true : false;
	$edit = ($action == "Edit") ? true : false;
	
	if ($edit) {
		if (!empty($id)) { 
			$paymentEdit = $paymentMgr->getPaymentOnly($id);
		}
	}
	if (!isset($paymentEdit)) $paymentEdit[] = new PaymentVo();

	$arrReservation = $reservationMgr->getReservations();
	arsort($arrReservation);
	// print_r($arrReservation);
	if (count($arrReservation) == 0) {
	?>
		<div class="alert alert-error">
			<h1><small><?php echo $tr->translate("msgNoReservation"); ?></small></h1>
			<p><?php echo $tr->translate("msgAddReservation"); ?></p>
			<p class="">
				<a href="reservationDetail.php" class="btn btn-large btn-primary"><i class="icon-chevron-left icon-white"></i> <?php echo $tr->translate("AddReserv"); ?></a>
			</p>
			<div class="clearfix"></div>
		</div>
	<?php
	}else{
		$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());

?>
	<div>
		<ul class="breadcrumb">
			<li><a href="./"><?php echo $tr->translate("menuHome"); ?></a> <span class="divider">/</span></li>
			<li><a href="payment.php"><?php echo $tr->translate("menuPayments"); ?></a> <span class="divider">/</span></li>
			<li class="active"><?php echo $tr->translate($action); ?></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>
	</div>

	<div class="row-fluid sortable ui-sortable">
		<div class="box span12">
			<div class="box-header well" data-original-title="">
				<h2><i class="icon-th"></i> <?php echo $tr->translate("Payment"); ?></h2>
			</div>
			<div class="box-content">
				<form class="form-horizontal" method="post" name="paymentForm" id="paymentForm" action="payment.php">
				<input type="hidden" name="action" id="action" value="" />
				<input type="hidden" name="reservid" id="reservid" value="" />
				<input type="hidden" name="paymentid" id="paymentid" value="<?php echo $id; ?>" />
				<input type="hidden" name="paymentdate" id="paymentdate" value="" />

				<?php if ($add) { ?>
				<div class="table-responsive">
				<table id="tablePaymentDetail" name="tablePaymentDetail" class="table table-condensed table-striped table-bordered bootstrap-datatable datatable">
					<thead>
						<tr>
							<th>ID</th>
							<th><?php echo $tr->translate("thPaymentTenancy"); ?></th>
							<th><?php echo $tr->translate("thPaymentTenant"); ?></th>
							<th><?php echo $tr->translate("thPaymentFrom"); ?></th>
							<th><?php echo $tr->translate("thPaymentTo"); ?></th>
							<th><?php echo $tr->translate("thPaymentAmount"); ?></th>
							<th><?php echo $tr->translate("thPaymentTypeBalance"); ?></th>
							<th><?php echo $tr->translate("thPaymentAction"); ?></th>
						</tr>
					</thead>   
					<tbody>
						<?php
							$totalPrice = 0;
							$totalBalance = 0;
							foreach ($arrReservation as $reserv) {
								$payment = (isset($arrBalance[$reserv->reservation_id])) ? $arrBalance[$reserv->reservation_id] : 0;
								$arrPayment = $paymentMgr->getPaymentByReservation($reserv->reservation_id);
								$arr = array();
								$arr[] = $reserv;

								// $balance = number_format((float)$reserv->price - $payment + $extra, 2, '.', '');
								$balance = number_format((float)getBalance($arr, array(), $arrPayment, $config), 2, '.', '');
								if ((!($reserv->paid) && $reserv->status >= $reservationMgr::RESERV_LEASE_SENT)) {
									$totalPrice += $reserv->price;
									$totalBalance += $balance;
						?>
						<tr id="<?php echo $reserv->reservation_id; ?>">
							<td><?php echo $reserv->reservation_id; ?></td>
							<td><?php echo $reserv->tenancy_name; ?></td>
							<td>
								<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 . " " . $reserv->tenant_name; ?></td>
							<td><?php echo date($config['date_format'], strtotime($reserv->arrival_date)); ?></td>
							<td><?php echo date($config['date_format'], strtotime($reserv->departure_date)); ?></td>
							<td><?php echo $reserv->price; ?></td>
							<td><?php echo $balance; ?></td>
							<td>
								<a class="btn btn-success btn-mini paybtn" title="<?php echo $tr->translate("tipReservationPayPart"); ?>" data-rel="tooltip" href="#">
									<i class="icon-plus icon-white"></i>
								</a>
								<a class="btn btn-info btn-mini" title="<?php echo $tr->translate("tipReservationPayAll"); ?>" data-rel="tooltip" href="#" onclick="goAction('PAY_ALL', <?php echo $reserv->reservation_id; ?>);">
									<i class="icon-money icon-white"></i>
								</a>
							</td>
						</tr>
						<?php } ?>
						<?php } ?>
					</tbody>
					<tfoot>
						<tr>
							<th></th>
							<th></th>
							<th></th>
							<th></th>
							<th></th>
							<th><?php echo number_format((float)$totalPrice, 2, '.', '') . " " . $config['currency_symbol']; ?></th>
							<th><?php echo number_format((float)$totalBalance, 2, '.', '') . " " . $config['currency_symbol']; ?></th>
							<th><?php  ?></th>
						</tr>
					</tfoot>
				</table>
				</div>
				<?php } ?>

				<div id="paymentDetail" <?php if (!$edit) echo "style='display:none;'"; ?>>
				<div class="progress">
				  <div class="bar" style="width: 100%"></div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="payment_type"><?php echo $tr->translate("thPaymentType"); ?></label>
							<div class="controls">
								<select id="payment_type" name="payment_type">
									<?php $arrTitle = $tr->translate("thPaymentTypeNames");
										foreach($arrTitle as $title) { ?>
											<option value="<?php echo $title; ?>" <?php if ($paymentEdit[0]->type == $title) echo " selected"; ?>><?php echo $title; ?></option>
									<?php } ?>
								</select>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="payment_montant"><?php echo $tr->translate("thPaymentAmount"); ?></label>
							<div class="controls">
								<div class="input-append"><input class="input-small" id="payment_montant" name="payment_montant" type="text" value="<?php echo $paymentEdit[0]->amount; ?>"><span class="add-on"><?php echo $config['currency_symbol']; ?></span>
								</div>	
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="payment_date"><?php echo $tr->translate("thPaymentDate"); ?></label>
							<div class="controls">
								<div class="input-append"><input type="text" class="datepicker input-small" name="payment_date" id="payment_date" value="<?php
									echo ($paymentEdit[0]->payment_date) ? date($config['date_format'], strtotime($paymentEdit[0]->payment_date)) : date($config['date_format']); ?>" ><span class="add-on"><i class="icon-calendar"></i></span>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="payment_method"><?php echo $tr->translate("thPaymentMethod"); ?></label>
							<div class="controls">
								<select id="payment_method" name="payment_method">
									<?php $arrTitle = $tr->translate("thPaymentMethodNames");
										foreach($arrTitle as $title) { ?>
											<option value="<?php echo $title; ?>" <?php if ($paymentEdit[0]->method == $title) echo " selected"; ?>><?php echo $title; ?></option>
									<?php } ?>
								</select>
							</div>
						</div>
					</div>
				</div>
				<?php if ($add) { ?>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="payment_paye"><?php echo $tr->translate("thPaymentReservClosed"); ?></label>
							<div class="controls">
								<input id="payment_paye" name="payment_paye" type="checkbox">
							</div>
						</div>
					</div>
				</div>
				<?php } ?>
				<div class="row-fluid">
					<div class="span12">
						<div class="control-group">
							<label class="control-label" for="inputComment"><?php echo $tr->translate("thPaymentComment"); ?></label>
							<div class="controls">
							<textarea id="inputComment" name="inputComment" rows="3"></textarea>
							</div>
						</div>
					</div>
				</div>
				<div class="row-fluid">
					<div class="span12">
						<fieldset>
						<div class="control-group">
						<div class="form-actions">
						<?php if ($add) { ?>
							<button type="button" name="add" id="add" class="btn btn-primary" onclick="goAction('PAY_PART');"><?php echo $tr->translate("btnAdd"); ?></button>
						<?php } ?>
						<?php if ($edit) { ?>
							<button type="button" name="save" id="save" class="btn btn-primary" onclick="goAction('EDIT_PAYMENT', <?php echo $paymentEdit[0]->payment_id; ?>);"><?php echo $tr->translate("btnSave"); ?></button>
						<?php } ?>
						</div>
						</div>
					</fieldset>
					</div>
				</div>
			</div>
			</form>
			</div>
		</div><!--/span-->
	</div>
	<?php } ?>
<?php require "../_container/container_bottom.php"; ?>
<script>
	$(document).ready(function() {
		$("#paymentForm").validate({
			rules: {
				payment_type: {required: true},
				payment_montant: {required: true},
				payment_date: {formatDate: true}
			},
			errorPlacement: function(error, element) {
				error.appendTo($(element).parent());
			}
		});
	
		if ($('#tablePaymentDetail').length) {
			myTable = $('#tablePaymentDetail').dataTable();
			var oSettings = myTable.fnSettings();
			oSettings.aoColumns[3].sType = "custom-date";
			oSettings.aoColumns[4].sType = "custom-date";
		}

	});
	$.validator.addMethod(
		"formatDate",
			function(value, element) {
				if (value) {
					return moment(value,"<?php echo $config['date_format_js_moment']; ?>", true).isValid();
				}
			},
		"<?php echo $tr->translate("msgInvalidDate"); ?>"
	);
	function goAction(action, id){
	// prevent the form to be validated and raise an error
	if (action == "PAY_ALL"){
		$('#paymentDetail').hide();
	}
	if (action == "PAY_DD"){
		
		$("#tablePaymentDetail tbody").trigger( "click" );
		return false;
	}

		var isvalidate = $("#paymentForm").valid();
		if(isvalidate){
			// if (!(moment($('#payment_date').val(),"<?php echo $config['date_format_js_moment']; ?>", true).isValid())){
				// alert("<?php echo $tr->translate("msgInvalidDate"); ?>");
				// return false;
			// }
			if ($('#payment_date').val())
				var paymentdate = moment($('#payment_date').val(),"<?php echo $config['date_format_js_moment']; ?>").format("YYYY-MM-DD HH:mm:ss");

			$('#paymentdate').val(paymentdate);
			if (action == "PAY_ALL"){
				$('#action').val(action);
				$('#reservid').val(id);
				paymentForm.submit();
			}
			if (action == "PAY_PART"){
				$('#action').val(action);
				// $('#reservid').val(id);
				blockUI();
				paymentForm.submit();
			}
			if (action == "EDIT_PAYMENT"){
				$('#action').val(action);
				$('#paymentid').val(id);
				blockUI();
				paymentForm.submit();
			}
		}else{
			e.preventDefault();
			return false;
		}
	}

	$("#tablePaymentDetail tbody").delegate("tr", "click", function() {
		var firstCellText = $("td:first", this).text();
		var firstCellText2 = $("td:eq(0)", this).text();
		var fourthCellText = $("td:eq(3)", this).text();
		// alert("First Cell: " + firstCellText + "\nFirst Cell2: " + firstCellText + "\nFourth Cell: " + fourthCellText);
		$('#reservid').val(firstCellText);
	});

	$(".paybtn").click(function(event) {
		$(oTable.fnSettings().aoData).each(function (){
			$(this.nTr).removeClass('row_selected');
		});
		$(this).parents('tr').addClass('row_selected');
		$("#payment_montant").val($(this).parents('tr').find("td").eq(6).text());
		$("#paymentDetail").show();
		
	});
</script>