<?php $_SESSION['redirect'] = $_SERVER['REQUEST_URI'];
	$getUtilityId = $_GET['utility'];
	$getRoomId = $_GET['room'];
	$getUtilityTypeId = $_GET['type'];
	$getPaymentActivityId = $_GET['paymentActivity'];
?>

		
<div class="right_col" role="main">
	<div class="">
		<div class="row">
			<div class="page-title">
				<div class="title_left">
					<h3><?php echo getDetailByTable('utility_type',$getUtilityTypeId)['uty_title']; ?></h3>
				</div>
			</div>
		</div>
		<div class="row">
			<div class="col-md-3 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<table>
							<tr>
								<td class="text-right"><label class="control-label">Owner Name</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('owners',getDetailByTable('rooms',$getRoomId)['o_id'])['o_name']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">No Room</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('rooms',$getRoomId)['r_no'];?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Property</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('properties',getDetailByTable('rooms',$getRoomId)['p_id'])['pty_title']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Rental</label></td>
								<td> : </td>
								<td>RM <?php $getRentalRate = getDetailByTable('rooms',$getRoomId)['r_rental']; echo $getRentalRate; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Rental Start Date</label></td>
								<td> : </td>
								<td><?php $rentalStartDate = getDetailByTable('rooms',$getRoomId)['r_rental_date_start']; if($rentalStartDate == "0000-00-00"){$rentalStartDate = "2017-01-01";} echo $rentalStartDate; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Rental End Date</label></td>
								<td> : </td>
								<td><?php $endDate = getDetailByTable('rooms',$getRoomId)['r_rental_date_end']; if($endDate=="0000-00-00"){echo "currently rent";}else{echo $endDate;} ?></td>
							</tr>
						</table>
						
						<br>
						<p>
							<a href="?pagecontent=room_update&room=<?php echo $getRoomId; ?>"><button class="btn btn-primary">Update Room</button></a>
						</p>
						
					</div>
				</div>
			</div>
			
			<div class="col-md-3 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<table>
							<tr>
								<td class="text-right"><label class="control-label">Total</label></td>
								<td> : </td>
								<td><?php echo " RM ".utilityTotal($getRoomId,$getUtilityTypeId)['total']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Duration</label></td>
								<td> : </td>
								<td><?php echo durationInDays($rentalStartDate,date("Y-m-d")); ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Total Paid</label></td>
								<td> : </td>
								<td><?php echo " RM ".utilityPaidTotal($getRoomId,$getUtilityTypeId)['total']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Total Outstanding</label></td>
								<td> : </td>
								<td><span style="color:red; font-weight: bold;">RM <?php echo utilityTotal($getRoomId,$getUtilityTypeId)['total'] - utilityPaidTotal($getRoomId,$getUtilityTypeId)['total'];?></span></td>
							</tr>
						</table>
						
					</div>
				</div>
			</div>
			
			<div class="col-md-3 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<table>
							<tr>
								<td class="text-right"><label class="control-label">Bank Account</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('rooms',$getRoomId)['r_bank_acc']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Bank Name</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('rooms',$getRoomId)['r_bank_name']; ?></td>
							</tr>
							<tr>
								<td class="text-right"><label class="control-label">Holder</label></td>
								<td> : </td>
								<td><?php echo getDetailByTable('rooms',$getRoomId)['r_bank_holder']; ?></td>
							</tr>
						</table>
						
					</div>
				</div>
			</div>
			
			<?php 
				if($_REQUEST['paymentActivity']){
					if(getDetailByTable('utility_payment',$_GET['paymentActivity'])['utyp_file']){ ?>
			<div class="col-md-6 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<img src="uploads/rental/<?php echo getDetailByTable('utility_payment',$_GET['paymentActivity'])['utyp_file']; ?>" width="100%">
					</div>
					
					<div class="x_content">
						
						<form class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
							<div class="item form-group">
								<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Upload 
								</label>
								<div class="col-md-3 col-sm-3 col-xs-12">
									<input id="night" class="form-control col-md-3 col-xs-12" name="fileToUpload" type="file" >
								</div>
							</div>

							<div class="ln_solid"></div>

							<div class="form-group">
								<div class="col-md-6 col-md-offset-3">
									<button id="send" type="submit" class="btn btn-success" name="uploadBtn">Upload</button>

									<button type="submit" class="btn btn-danger" name="removePhoto">Remove</button>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<?php }else{ ?>
			<div class="col-md-6 col-sm-6 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
					<form class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
						<div class="item form-group">
							<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Upload 
							</label>
							<div class="col-md-3 col-sm-3 col-xs-12">
								<input id="night" class="form-control col-md-3 col-xs-12" name="fileToUpload" type="file" >
							</div>
						</div>

						<div class="ln_solid"></div>

						<div class="form-group">
							<div class="col-md-6 col-md-offset-3">
								<button id="send" type="submit" class="btn btn-success" name="uploadBtn">Upload</button>
							</div>
						</div>
					</form>
					</div>
				</div>
			</div>
			
			<?php }} ?>
			
			<?php if($_GET['paymentActivity']){ ?>
			
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
					<div class="x_title">
						<h2>Utility Payment</h2>
						<div class="clearfix"></div>
					</div>

					<div class="x_content">
						<form class="form-horizontal form-label-left" method="post">
							<div class="item form-group">
								<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Month/Year 
								</label>
								<div class="col-md-3 col-sm-3 col-xs-12">
									<input id="night" class="form-control col-md-3 col-xs-12" name="total" type="currency" value="<?php echo $postMonthYear = date("F / Y",strtotime(getDetailByTable("utilities",getDetailByTable("utility_payment",$_GET['paymentActivity'])['uty_id'])['u_date'])); ?>" readonly>
								</div>
							</div>

							<div class="item form-group">
								<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Date
								</label>
								<div class="col-md-3 col-sm-3 col-xs-12">
									<input id="night" class="form-control col-md-3 col-xs-12" name="date" type="date" value="<?php echo getDetailByTable('utility_payment',$_GET['paymentActivity'])['utyp_date']; ?>">
								</div>
							</div>
							
							<div class="item form-group">
								<label class="control-label col-md-3 col-sm-3 col-xs-12" for="night">Amount 
								</label>
								<div class="col-md-3 col-sm-3 col-xs-12">
									<input id="night" class="form-control col-md-3 col-xs-12" name="amount" type="currency" value="<?php echo getDetailByTable('utility_payment',$_GET['paymentActivity'])['utyp_amount']; ?>">
								</div>
							</div>

							<div class="ln_solid"></div>

							<div class="form-group">
								<div class="col-md-6 col-md-offset-3">
									<button id="send" type="submit" class="btn btn-success" name="submit">Update</button>
									<button id="send" type="submit" class="btn btn-danger" name="remove">Remove</button>
								</div>
							</div>

						</form>
						<?php
							if(isset($_POST['submit'])){
								$postUtilityId = $_GET['paymentActivity'];
								$postDate = $_POST['date'];
								$postAmount = $_POST['amount'];

								mysqli_query($conn,"UPDATE utility_payment SET utyp_amount='$postAmount', utyp_date='$postDate' WHERE utyp_id=$postUtilityId");
								
								utilityLog(0,$getRoomId,$getUtilityTypeId,$_SESSION['admin'][1]." update payment RM".$postAmount." for ".$monthYear." on ".$postDate);

								header("Location: ?pagecontent=utility_view&room=$getRoomId&type=$getUtilityTypeId");
							}
											   
							if(isset($_POST['remove'])){
								$postUtilityId = $_GET['paymentActivity'];
								$fileName = getDetailByTable('utility_payment',$_GET['paymentActivity'])['utyp_file'];

								if(mysqli_query($conn,"DELETE FROM utility_payment WHERE utyp_id=$postUtilityId")){
									unlink('uploads/rental/'.$fileName);
								};
								
								utilityLog(0,$getRoomId,$getUtilityTypeId,$_SESSION['admin'][1]." remove payment for ".$monthYear);

								header("Location: ?pagecontent=utility_view&room=$getRoomId&type=$getUtilityTypeId");
							}
						?>
									
					</div>
                </div>
            </div>
			<?php } ?>
        </div>
		<div class="clearfix"></div>
		<div class="row">
			<div class="col-md-12 col-sm-12 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
						<table id="datatable" class="table table-striped table-bordered">
							<thead>
								<tr>
									<th>NO</th>
									<th>Date</th>
									<th>Amount</th>
									<th>Payment Activity</th>
									<th>Unpaid</th>
									<th>Note</th>
									<th>Action</th>
								</tr>
							</thead>
							<tbody>
								<?php
								foreach(array_reverse(getMonthsInRange($rentalStartDate,date("Y-m-31"))) as $monthYear){
									$date = $monthYear['year']."-".$monthYear['month']."-01";
							  ?>
								<tr>
									<td><?php echo ++$no;?></td>
									<td><?php echo $monthYear['month']."/".$monthYear['year'];?></td>
									<td><?php $rentalRate = utilityRecord($date,$getUtilityTypeId,$getRoomId)['u_amount']; if($rentalRate){echo "RM ".$rentalRate;} ?></td>
									<td><?php 
											foreach(array_reverse(paymentRecord(utilityRecord($date,$getUtilityTypeId,$getRoomId)['u_id'])) as $array2){
												echo "<a href='?pagecontent=utility_view&room=".$getRoomId."&type=".$getUtilityTypeId."&utility=".$array2['uty_id']."&paymentActivity=".$array2['utyp_id']."'>";
												echo "RM ";
												$amount = $array2['utyp_amount']; echo $amount; $total = $total + $amount;
												echo " - ";
												echo date_format(date_create($array2['utyp_date']),"d/m/Y");
												echo "</a>"; echo "<br>";
											};
										?></td>
									<td><?php $amountBalance = $total - $rentalRate; if($amountBalance<0){echo "<span style='color:red;font-weight:bold;'>RM ".$amountBalance."</span>";}else{echo "RM ".$amountBalance;}?></td>
									<td><?php echo utilityRecord($date,$getUtilityTypeId,$getRoomId)['u_note']; ?></td>
									<td>
										
									    <a href="?pagecontent=utility_update&room=<?php echo $getRoomId; ?>&date=<?php echo $date; ?>&type=<?php echo $getUtilityTypeId; ?>"><button type="button" class="btn btn-xs btn-primary">Update</button></a>
										
										<?php if($rentalRate){ ?>
									    <a href="?pagecontent=utility_payment&id=<?php echo utilityRecord($date,$getUtilityTypeId,$getRoomId)['u_id']; ?>&type=<?php echo $getUtilityTypeId; ?>&amount=<?php echo abs($amountBalance); ?>&date=<?php echo $date; ?>&room=<?php echo $getRoomId; ?>"><button type="button" class="btn btn-xs btn-primary">Payment</button></a>
										<?php } ?>
									</td>
								</tr>
								<?php
									//clear
									$total = 0; $amountBalance = 0; } 
								?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
        </div>
		
		
		<div class="clearfix"></div>
		
		  <div class="col-12">
			<div class="x_panel">
			  <div class="x_title">
				<h2>Utility Activity Log</h2>
				<ul class="nav navbar-right panel_toolbox">
				  <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
				  </li>
				  <li class="dropdown">
					<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
					<ul class="dropdown-menu" role="menu">
					  <li><a href="#">Settings 1</a>
					  </li>
					  <li><a href="#">Settings 2</a>
					  </li>
					</ul>
				  </li>
				  <li><a class="close-link"><i class="fa fa-close"></i></a>
				  </li>
				</ul>
				<div class="clearfix"></div>
			  </div>
			  <div class="x_content">
				<table class="table table-hover">
				  <thead>
					<tr>
					  <th>#</th>
					  <th>Log</th>
					  <th>Date/Time</th>
					  <th>Admin</th>
					</tr>
				  </thead>
				  <tbody>
					<?php $no = 0; $result = mysqli_query($conn,"SELECT * FROM utility_log WHERE r_id=$getRoomId AND utyt_id=$getUtilityTypeId ORDER BY utyl_id DESC LIMIT 50");
					while($row = mysqli_fetch_assoc($result)){
					?>
					<tr>
					  <th scope="row"><?php echo ++$no; ?></th>
					  <td><?php echo $row['utyl_report']; ?></td>
					  <td><?php echo $row['timestamp']; ?></td>
					  <td><?php echo getDetailFromTable('admin',$row['a_id'])['a_username']; ?></td>
					</tr>
					  <?php } ?>
				  </tbody>
				</table>

			  </div>
			</div>
		  </div>
    </div>
</div>

<?php

	if(isset($_POST['removePhoto'])){
		
		if(getDetailByTable("utility_payment",$getPaymentActivityId)['utyp_file']){
			$utilityPaymentFile = getDetailByTable("utility_payment",$getPaymentActivityId)['utyp_file'];
			unlink("uploads/rental/".$utilityPaymentFile);
			
			mysqli_query($conn, "UPDATE utility_payment SET utyp_file='' WHERE utyp_id=$getPaymentActivityId");
		}
		
		$postMonthYear = date("F / Y",strtotime(getDetailByTable("utilities",$getUtilityId)['u_date']));
		utilityLog(0,$getRoomId,$getUtilityTypeId,$_SESSION['admin'][1]." remove photo for ".$postMonthYear);
		
		if($_SESSION['redirect']){ $redirectUrl = $_SESSION['redirect'];
			header("Location: $redirectUrl");
		}
	}

	if(isset($_POST['uploadBtn'])){
		
		if(getDetailByTable("utility_payment",$getPaymentActivityId)['utyp_file']){
			$utilityPaymentFile = getDetailByTable("utility_payment",$getPaymentActivityId)['utyp_file'];
			unlink("uploads/rental/".$utilityPaymentFile);
		}
			
		//image resize
		if(is_array($_FILES)) {

			$uploadedFile = $_FILES['fileToUpload']['tmp_name']; 
			$sourceProperties = getimagesize($uploadedFile);
			$imageType = $sourceProperties[2];

			switch ($imageType) {

				case IMAGETYPE_PNG:
					$imageSrc = imagecreatefrompng($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;           

				case IMAGETYPE_JPEG:
					$imageSrc = imagecreatefromjpeg($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;

				case IMAGETYPE_GIF:
					$imageSrc = imagecreatefromgif($uploadedFile); 
					imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
					break;

				default:
					echo "Invalid Image type.";
					exit;
					break;
			}
		}

		  //upload receipt
		  $errors = array();
		  $file_name = $_FILES['fileToUpload']['name'];
		  $file_size =$_FILES['fileToUpload']['size'];
		  $file_tmp = $_FILES['fileToUpload']['tmp_name'];
		  $file_type = $_FILES['fileToUpload']['type'];

		  $file_ext = strtolower(end(explode('.',$_FILES['fileToUpload']['name'])));

		  $extensions = array("jpeg","jpg","png");

		  if(in_array($file_ext,$extensions)=== false){
			 $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
		  }

		  if($file_size > 2097152){
			 $errors[] = 'File size must be excately 2 MB';
		  }

			$file_name = $getPaymentActivityId."_".time().".".$file_ext;
			$filePath = "uploads/rental/".$file_name;

		  if(empty($errors) == true){

			 if(move_uploaded_file($file_tmp,$filePath)){

				 mysqli_query($conn, "UPDATE utility_payment SET utyp_file='$file_name' WHERE utyp_id=$getPaymentActivityId");

				 $adminName = $_SESSION['admin'][1];
				 $roomNo = getDetailByTable("rooms",$getRoomId)['r_no'];
				 $propertyTitle = getDetailByTable("properties",getDetailByTable("rooms",$getRoomId)['p_id'])['pty_title'];

				 sendMessage2(-1001209156913,$adminName." add ".getDetailByTable('utility_type',$getUtilityTypeId)['uty_title']."'s payment for

Property : ".$propertyTitle."
Room : ".$roomNo."
Month/Year : ".$monthYear."
Paid : RM ".$postAmount."
Date : ".$postDate."
");
				 sendPhoto(-1001209156913,"https://admin.homestay.dzvisual.my/production/".$filePath);

				 telegramRoomRentalUpdate($getUtilityTypeId,$getDate);
			 }
		  }
		
		$postMonthYear = date("F / Y",strtotime(getDetailByTable("utilities",$getUtilityId)['u_date']));
		utilityLog(0,$getRoomId,$getUtilityTypeId,$_SESSION['admin'][1]." add photo for ".$postMonthYear);
		
		if($_SESSION['redirect']){ $redirectUrl = $_SESSION['redirect'];
			header("Location: $redirectUrl");
		}
	}
						
	function getMonthsInRange($startDate, $endDate){
		$months = array();
		while (strtotime($startDate) <= strtotime($endDate)) {
			$months[] = array('year' => date('Y', strtotime($startDate)), 'month' => date('m', strtotime($startDate)), );
			$startDate = date('01 M Y', strtotime($startDate.
				'+ 1 month')); // Set date to 1 so that new month is returned as the month changes.
		}

		return $months;
	}

	function paymentRecord($utilityId){
		global $conn; $array = array();
		
		$result = mysqli_query($conn,"SELECT * FROM utility_payment WHERE uty_id=$utilityId");
		while($row = mysqli_fetch_array($result)){
			$array[] = $row;
		}

		return $array;
	}

	function durationInDays($dateStart,$dateEnd){
		$datetime1 = date_create($dateStart);
		$datetime2 = date_create($dateEnd);
		$interval = date_diff($datetime1, $datetime2);
		return $interval->format('%y years %m months %d days');
	}

	function imageResize($imageSrc,$imageWidth,$imageHeight) {

		$newImageWidth =200;
		$newImageHeight =200;

		$newImageLayer=imagecreatetruecolor($newImageWidth,$newImageHeight);
		imagecopyresampled($newImageLayer,$imageSrc,0,0,0,0,$newImageWidth,$newImageHeight,$imageWidth,$imageHeight);

		return $newImageLayer;
	}
?>