<?php include "headerLink.php"?>
<!DOCTYPE html>
<html lang="en">


<body class="animsition">
    <div class="page-wrapper">
       

        <!-- PAGE CONTAINER-->
        <!--<div class="page-container">-->
            <!-- HEADER DESKTOP-->
			
            <!-- END HEADER DESKTOP-->
			
			
			
			<!-- MAIN CONTENT-->
			<?php 
			$tenant_id = $_GET["tenant_id"];
			$bill_type_id_others = $_GET["bill_type_id_others"];
			$display = "display:none";

			
			
			include("queryTenant.php");
			$resultTenant = mysqli_fetch_assoc($runTenant);
			$tenant_name = $resultTenant["tenant_name"];
			$unit_no = $resultTenant["unit_no"];
			$location_name = $resultTenant["location_name"];
			$tenant_status = $resultTenant["status"];
			
			include("tenantRentalRate.php");
			
			
			
			$location_id = $_SESSION["location_id"];
			$location_code = $_SESSION["location_code"];
			
			if (isset($_GET['submit'])) {
				$staff_id = $_SESSION["staff_id"];
				//$location_id = $_SESSION["location_id"];
				$location_code = $_SESSION["location_code"];
				$monthYear = $_GET['monthYear'];
				$_SESSION["monthYear"] = $monthYear;
				//echo " form_generateMonthYear $monthYear ";
				$no=0;
				$issue_date = date("Y-m-01 00:00:00", strtotime($monthYear));
				 "monthYear_view: " . $monthYear_view = date("M Y", strtotime($monthYear));
				
				  
				
				//check issue date for selected month year exist or not.
				  $sqlCheckBills = "select * from bills where issue_date = '$issue_date' and tenant_id = $tenant_id and bill_type_id = 1";
				
				
				
				$runCheckBills = mysqli_query($link, $sqlCheckBills);
				if($runCheckBills === FALSE){
				   die(mysqli_error($link));
				}
				 " countExistBills : ".$countExistBills = mysqli_num_rows($runCheckBills);
				if($countExistBills == 0){
					//set running no based on bill_no  start
					//$sqlSearchBillNo = "SELECT max(bill_no) as maxBill_no FROM `bills` WHERE `bill_no` LIKE '".$location_code."-%' and bill_type_id = 1 ORDER BY `bills`.`bill_no` ASC";
					 $sqlSearchBillNo = "SELECT bill_no FROM `bills` 
										inner join tenants on bills.tenant_id = tenants.id
										inner join properties on tenants.property_id = properties.id
										inner join locations on properties.location_id = locations.id 
										inner join projects on locations.project_id = projects.id 
										where locations.id = $location_id AND bill_type_id = 1  order by bills.id DESC limit 1";
					$runSearchBillNo = mysqli_query($link, $sqlSearchBillNo);
					if($runSearchBillNo === FALSE){
						die(mysqli_error($link));
					}
					$resultBillNo = mysqli_fetch_assoc($runSearchBillNo);
					
					
					//set running no based on bill_no end
					
					$bill_no = $resultBillNo["bill_no"];
					$bill_no_split = explode('/',$bill_no); 
					 " bill_no_split: START";
						//print_r($bill_no_split);
					 " bill_no_split: END";
						
					//susunan baru bill_no = [project_code]/[location_code]/[bill_code]/[running_no]
					//0->[INV]
					//1->[location_code]
					//2->[bill_code]
					//3->[running_no]
					 " countBillNoSplit: " .$countBillNoSplit = count($bill_no_split);
					if($countBillNoSplit > 0){
						 " countBillNoSplit > 0" ;
						 " BILL NO :: " . $bill_no = $bill_no_split[3];
						$bill_no++;
						$strlenRunningNo = strlen($bill_no);
						
						 
						 
						 IF($strlenRunningNo == 1)
							  $bill_no = '0'. $bill_no;
						 
					}
					else if($countBillNoSplit == 0){
						 " countBillNoSplit = 0" ;
						$bill_no = "01";
					}
					
					IF(date("Y-m",strtotime($monthYear)) == date("Y-m") || date("Y-m",strtotime($monthYear)) > date("Y-m")){
						$bill_name = "SEWA SEMASA";
					}
					ELSE IF(date("Y-m",strtotime($monthYear)) < date("Y-m")){
						$bill_name = "SEWA TUNGGAKAN";
					}
					
					
					include('bill_code.php');
					
					$bill_no = "INV/". $location_code . '/'.$bill_code . '/' . $bill_no;
					
					 $insert_BillsSql = "insert into bills (bill_no, amount_due, bill_amount, payment_status, issue_date, bill_type_id, created_by, tenant_id, created_at, updated_at)
										 values (
											'".$bill_no."',
											'".number_format($rental_rate,2)."',
											'".number_format($rental_rate,2)."',
											'unpaid',
											'".$issue_date."',
											'1',
											'".$staff_id."',
											'".$tenant_id."',
											'".date('Y-m-d H:i:s')."',
											'".date('Y-m-d H:i:s')."'
											)";
					$runinsert_BillsSql = mysqli_query($link, $insert_BillsSql);
					if($runinsert_BillsSql === FALSE){
						die(mysqli_error($link));
					}
					$no++;
					$display = "display:block";
				}
			else if($countExistBills > 0){
				$no=0;
				$totalBillAmount = 0.00;
				$amountDue = 0.00;
				while($resultCheckBills = mysqli_fetch_array($runCheckBills)){
					$tenant_id = $resultCheckBills["tenant_id"];
					$tenantRentalRate = $resultCheckBills["rental_rate"];
					$location_id = $resultCheckBills["location_id"];
					$bill_amount = $resultCheckBills["bill_amount"];
					
					$totalBillAmount += $bill_amount;
				}
				if($totalBillAmount < $rental_rate){
					$amountDue = $rental_rate - $totalBillAmount;
					//set running no based on bill_no  start
					$sqlSearchBillNo = "SELECT max(bill_no) as maxBill_no FROM `bills` WHERE `bill_no` LIKE '".$location_code."-%' ORDER BY `bills`.`bill_no` ASC";
					$runSearchBillNo = mysqli_query($link, $sqlSearchBillNo);
					if($runSearchBillNo === FALSE){
						die(mysqli_error($link));
					}
					$resultBillNo = mysqli_fetch_assoc($runSearchBillNo);
					$maxBill_no = $resultBillNo["maxBill_no"];
					$maxBill_no_split = explode('-',$maxBill_no);   
					$maxBill_no = $maxBill_no_split[1];
					$maxBill_no++;
					
					$bill_no = $location_code . "-" . $maxBill_no;
					//set running no based on bill_no end
					
					
					$insert_BillsSql = "insert into bills (bill_no, amount_due, bill_amount, payment_status, issue_date, bill_type_id, created_by, tenant_id, created_at, updated_at)
										values (
											'".$bill_no."',
											'".number_format($amountDue,2)."',
											'".number_format($amountDue,2)."',
											'unpaid',
											'".$issue_date."',
											'1',
											'".$staff_id."',
											'".$tenant_id."',
											'".date('Y-m-d H:i:s')."',
											'".date('Y-m-d H:i:s')."'
											)";
					$runinsert_BillsSql = mysqli_query($link, $insert_BillsSql);
					if($runinsert_BillsSql === FALSE){
						die(mysqli_error($link));
					}
					$no++;
				}
				$display = "display:block";
			}
				
			}
			
			
			?>
 <div class="main-content"  >
	<div class="section__content section__content--p30" >
		<div class="container-fluid" >
			<div class="row" >
				<div class="col col-md-12" >
					<div class="card">
						
						<div class="card-body">
							<div class="col col-md-12">
										<div class="card">
											<div class="card-header py-3">
												<h5 class="m-0 font-weight-bold text-primary">GENERATE MONTHLY BILLING FOR RENTAL [<?php echo $tenant_name . " : " . $unit_no .", ". $location_name?>]</h5>
											</div>
											<?php if($tenant_status == "enable"){?>
											<form action="<?php $_SERVER['PHP_SELF']; ?>" method="get" enctype="multipart/form data" name="form_generateMonthYear">
												<!--<input type="hidden" name="projectLocation" value="<?php echo $_GET["projectLocation"]?>">-->
												<div class="card-body card-block">
													<input type="hidden" name="tenant_id" value="<?php echo $_GET["tenant_id"]?>">
													<input type="hidden" name="bill_type_id_others" value="<?php echo $_GET["bill_type_id_others"]?>">
													
													<div >
														<label class=" form-control-label"><b>Please choose Month/Year</b></label>
													</div>
													<div class="form-check" >
														<input class="form-control" type="month" name="monthYear" id="monthYear" value="<?php echo $_SESSION["monthYear"]?>">
													</div>
														
												</div>	
												<div class="card-footer">		
													<div class="row form-group" >
														<div class="col col-sm-3">
															<button class="btn btn-primary" type="submit" name="submit">Submit</button>
														</div>
														<div class="col col-sm-9" style="<?php echo $display?>">
															<label class=" form-control-label"><center><b>
														<?php 
														if($no > 0){
															echo "SUCCESS CREATED $no INVOICE FOR ". strtoupper($monthYear_view) ;
														}
														else if($no == 0){
															echo " NO INVOICE CREATED ";
														}
														?>
															</b></center></label>
														</div>
													</div>
												</div>
											</form>
											<?php } else if($tenant_status == "disable"){?>
												<div class="card-body card-block">
													<div >
														<label class=" form-control-label"><b>Cannot create new invoice - tenant deactive</b></label>
													</div>
														
												</div>	
											
											<?PHP } ?>
										</div>												
									</div>
						</div>
					</div>
				</div>
			</div>
			<div class="row" >
				<div class="col col-md-12" >
					<div class="card">
						<div class="card-header">
							<h6 class="m-0 font-weight-bold text-primary">Invoice for Rental [<?php echo $tenant_name . " : " . $unit_no .", ". $location_name?>]</h6>
						</div>
						<div class="card-body">
							<div class="table-responsive">
								<!--<table class="table table-bordered" id="dataTable" widtd="70%" cellspacing="0" style="font-size: 12px">-->
								<table class="table table-bordered table-hover table-sm" id="dataTable" widtd="70%" cellspacing="0" style="font-size: 12px">
									<tr>
										<td valign="top" align="center" ><b>BIL</b></td>
										<td ><b>INVOICE NO</b></td>
										<td ><b>MONTH/YEAR</b></td>
										<td ><b>TYPE</b></td>
										<td align = "center" ><b>BILL AMOUNT (RM)</b></td>
										<td align = "center" ><b>OUTSTANDING AMOUNT (RM)</b></td>
										<td align = "center" ><b>PAYMENT STATUS</b></td>
									</tr>


								<?php
								/* $sqlBills = "SELECT * FROM bills 
								WHERE tenant_id = $tenant_id and (payment_status = 'unpaid' or payment_status = 'partial' and bill_type_id = 1)  
								order by
								CASE WHEN MONTH(issue_date) = MONTH(CURDATE()) AND YEAR(issue_date) = YEAR(CURDATE()) THEN 0 ELSE 1 END,
								CASE WHEN YEAR(issue_date) = YEAR(CURDATE()) AND  MONTH(issue_date) < MONTH(CURDATE()) THEN 0 ELSE 1 END,
								issue_date asc"; */
								$sqlBills = "SELECT * FROM bills 
												WHERE tenant_id = $tenant_id and (payment_status = 'unpaid' or payment_status = 'partial' and bill_type_id = 1)  
												order by
												CASE WHEN MONTH(issue_date) = MONTH(CURDATE()) AND YEAR(issue_date) = YEAR(CURDATE()) THEN 0 ELSE 1 END,
												issue_date asc";
								$runBills = mysqli_query($link, $sqlBills);
								if($runBills === FALSE){
									die(mysqli_error($link));
								}
								$no=1;
								while($resultBills = mysqli_fetch_array($runBills)){
									$issue_date = $resultBills["issue_date"];
									$monthYear_issuedate = date("Y-m",strtotime($issue_date));
									$amount_due = $resultBills["amount_due"];
									$bill_amount = $resultBills["bill_amount"];
									$payment_status = $resultBills["payment_status"];
									$bill_id = $resultBills["id"];
									$tenant_id = $resultBills["tenant_id"];
									$bill_no = $resultBills["bill_no"];
									$monthYear_issuedate_view = date("M Y", strtotime($monthYear_issuedate));
									if($monthYear_issuedate == date("Y-m")){
										$type = "Current";
									}
									else if($monthYear_issuedate < date("Y-m")){
										$type = "Outstanding";
									}
									else if($monthYear_issuedate > date("Y-m")){
										$type = "Advance";
									}
									?>
									<tr>
										<td valign="top" align="center" ><b><?php echo $no?></b></td>
										<td ><b><?php echo $bill_no?></b></td>
										<td ><b><?php echo $monthYear_issuedate_view?></b></td>
										<td ><b><?php echo $type?></b></td>
										<td align = "center" ><b><?php echo number_format($bill_amount,2,".",",")?></b></td>
										<td align = "center" ><b><?php echo number_format($amount_due,2,".",",")?></b></td>
										<td align = "center" ><b><?php echo $payment_status?></b></td>
									</tr>
									<?php
									$no++;
								}

								?>
								</table>
							</div>
						</div>
					</div>
				</div>
			</div>




                        
                        <?PHP include "footer.php";?>
                        
                    </div>
                </div>
            </div>
            <!-- END MAIN CONTENT-->
            <!-- END PAGE CONTAINER-->
        </div>
		
   <!-- </div>-->
    <?PHP include "footerLink.php";?>
</body>

</html>