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


<body class="animsition">
    <div class="page-wrapper">
        <!-- HEADER MOBILE-->
        <?php include "menuSideBar_mobile.php" ;?>
        <!-- END HEADER MOBILE-->
		
        <!-- MENU SIDEBAR-->
        <?php include "menuSideBar.php" ;?>
        <!-- END MENU SIDEBAR-->

        <!-- PAGE CONTAINER-->
        <div class="page-container">
            <!-- HEADER DESKTOP-->
			<?php include "headerPage.php"?>
            <!-- END HEADER DESKTOP-->
			
			
			
			<!-- MAIN CONTENT-->
			<?php
			$location_id = $_SESSION["location_id"];
			//if(isset($_POST['form_generateMonthYear']) && isset($_POST['submit'])) {
			if(isset($_POST['submit'])) {
				$staff_id = $_SESSION["staff_id"];
				$location_id = $_SESSION["location_id"];
				$monthYear = $_POST['monthYear'];
				$_SESSION["monthYear"] = $monthYear;
				//echo " form_generateMonthYear $monthYear ";
				
				$issue_date = date("Y-m-01 00:00:00", strtotime($monthYear));
				$monthYear_view = date("M Y", strtotime($monthYear));
				
				 $sqlListTenant = "select DISTINCT bills.tenant_id,tenant_rental_rate.rental_rate, locations.id as location_id from bills 
										inner JOIN tenants on bills.tenant_id = tenants.id
										inner join tenant_rental_rate on tenants.id = tenant_rental_rate.tenant_id
                                        INNER JOIN properties on tenants.property_id = properties.id
                                        inner join locations on properties.location_id = locations.id
										where  bills.tenant_id not in (
										select bills.tenant_id from bills 
										inner JOIN tenants on bills.tenant_id = tenants.id
										where bills.issue_date = '$issue_date' and tenants.status ='enable'  and bill_type_id = 1) and tenants.status = 'enable' and locations.id = $location_id";
				$runListTenant = mysqli_query($link, $sqlListTenant);
				if($runListTenant === FALSE){
				   die(mysqli_error($link));
				}
				$no=0;
				while($resultListTenant = mysqli_fetch_array($runListTenant)){
					$list_tenantID = $resultListTenant["tenant_id"];
					$list_tenantRentalRate = $resultListTenant["rental_rate"];
					$list_location_id = $resultListTenant["location_id"];
					
					//set running no based on bill_no  start
					$sqlSearchBillNo = "SELECT max(bill_no) as maxBill_no FROM `bills` WHERE `bill_no` LIKE '".$list_location_id."-%' 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 = $list_location_id . "-" . $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($list_tenantRentalRate)."',
						'".number_format($list_tenantRentalRate)."',
						'unpaid',
						'".$issue_date."',
						'1',
						'".$staff_id."',
						'".$list_tenantID."',
						'".date('Y-m-d')."',
						'".date('Y-m-d')."'
						)";
					$runinsert_BillsSql = mysqli_query($link, $insert_BillsSql);
					if($runinsert_BillsSql === FALSE){
						die(mysqli_error($link));
					}
					$no++;
				}
			}
			
			?>
			
            
           <!--main content upper start-->
			<?php include "main-content-upper.php"?>
            <!--main content upper end-->
			<!--main content middle start-->
			<div class="row" >
				
							<div class="card-body">
								<div class="row form-group">
									<div class="col col-md-6">
										<div class="card">
											<div class="card-header py-3">
												<h5 class="m-0 font-weight-bold text-primary">GENERATE MONTHLY BILLING FOR RENTAL</h5>
											</div>
											<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" 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="login" value="<?php echo $_GET["login"]?>">
													
													<!--<input id="inputIsInvalid"  class="<?php echo $invalid_input;?> au-input au-input--xl" type="text" list="projectLocation" name="projectLocation" onChange="javascript: submit();" size="20" disabled value="<?php echo $_SESSION['projectLocation']?>" placeholder="Select Location"/>
													<button class="au-btn--submit" type="submit">
														<i class="zmdi zmdi-search"></i>
														<datalist id="projectLocation">
															
															<?php
															
															//echo "USERNAME: ".$_SESSION["username"] ;
																/* if($_SESSION["username"] != "admin"){
																	  $sqlLocations = "SELECT * FROM ( 
																						(select EL.location_id, locations.location_name, projects.project_name from extra_locations as EL 
																						inner join locations on locations.id = EL.location_id 
																						inner join projects on locations.project_id = projects.id 
																						inner join users on EL.user_id =  users.id
																						where users.id = ". $_SESSION['staff_id'] .") 
																					UNION 
																						(select locations.id, locations.location_name, projects.project_name from locations 
																						inner join users on locations.id = users.location_id 
																						inner join projects on locations.project_id = projects.id
																						where users.id = ". $_SESSION['staff_id'] .") 
																					) results ORDER BY project_name ASC";
																	
																	$runLocations = mysqli_query($link,$sqlLocations);
																	if($runLocations === FALSE){
																		die(mysqli_error($link));//TODO: better error handling
																	}
																}
																else if($_SESSION["username"] == "admin"){
																		 $sqlLocations = "select locations.*,projects.project_name, projects.id as project_id from locations 
																			
																			inner join projects on locations.project_id = projects.id
																			where projects.status = 'enable' and projects.project_name != 'admin'
																			ORDER BY `projects`.`project_name` ASC";
																	$runLocations = mysqli_query($link, $sqlLocations);
																	if($runLocations === FALSE){
																		die(mysqli_error($link));
																	}
																}
																while($resultLocations = mysqli_fetch_array($runLocations)){
																	$location_id = $resultLocations["id"];
																	$location_name = $resultLocations["location_name"];
																	$project_name = $resultLocations["project_name"];
																		?>
																		<option <?php echo (strtoupper($_SESSION["projectLocation"]) ==  strtoupper($project_name . "-" . $location_name))  ? "selected" : "" ?> value="<?php echo strtoupper($project_name . "-" . $location_name); ?>" >
																		
																		<?php
																} */
															?>
														</datalist>
													</button>
													<input type="checkbox" id="checkboxAllLocation" name="checkboxAllLocation" value="yes" class="form-check-input" onclick="checkboxAllLocation(this)"  checked> -->
													<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-12">
															<button class="btn btn-primary" type="submit" name="submit">Submit</button>
														</div>
													</div>
												</div>
											</form>
										</div>												
									</div>
									<div class="col col-md-6" >
										<div class="card-header py-3">
											<h5 class="m-0 font-weight-bold text-primary">Showing Result</h5>
										</div>
										<div class="card-body card-block">
										<?php 
										if($no > 0){
											echo "SUCCESS CREATED $no INVOICE FOR ". strtoupper($monthYear_view) ;
										}
										else if($no == 0){
											echo " NO INVOICE CREATED ";
										}
										?>
									
										</div>
									</div>
								</div>
							</div> 
						</DIV>
            <!--main content middle end-->
			<!--main content bottom start-->
				<?PHP include "main-content-bottom.php";?>
			<!--main content bottom end-->
			
            <!-- END MAIN CONTENT-->
            <!-- END PAGE CONTAINER-->
        </div>
    </div>
    <?PHP include "footerLink.php";?>
</body>

</html>
<!-- end document-->
<script>
/* function checkboxAllLocation(x){
	alert(x);
	
	
} */
const checkboxAllLocation = document.getElementById('checkboxAllLocation')

checkboxAllLocation.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checkboxAllLocation');
    document.getElementById("inputIsInvalid").readOnly = true;

  } else {
    alert('not checked');
	document.getElementById("inputIsInvalid").disabled = false;
	// document.getElementById("sstPercent").disabled = false;
	 
   /*  var twoMonthRental = document.getElementById("twoMonthRental").value = 0.00;
    var utility = document.getElementById("utility").value = 0.00;
    var stampingCharges = document.getElementById("stampingCharges").value;
    var yuranPelbagai = document.getElementById("yuranPelbagai").value;
    var sstCharges = document.getElementById("sstCharges").value;
    var firstMonthRental = document.getElementById("firstMonthRental").value;
    twoMonthRental = twoMonthRental.toFixed(2);
    utility = utility.toFixed(2);
    stampingCharges = Number(stampingCharges);
    yuranPelbagai = Number(yuranPelbagai);
    sstCharges = Number(sstCharges);
    firstMonthRental = Number(firstMonthRental);
   // alert(twoMonthRental);
   // alert(utility);
    updateTotalBilling = parseFloat(twoMonthRental) + parseFloat(utility) +  stampingCharges + yuranPelbagai + sstCharges +  firstMonthRental ;
    updateTotalBilling = updateTotalBilling.toFixed(2);
    document.getElementById("totalBilling").value =  updateTotalBilling;
    document.getElementById("twoMonthRental").value =  twoMonthRental;
    document.getElementById("utility").value =  utility;

    document.getElementById("twoMonthRental").readOnly = true;
    document.getElementById("utility").readOnly = true; */
	}
  }
)
</script>