<?php 
//error_reporting(0); 
date_default_timezone_set("Asia/Kuala_Lumpur");			
			session_start();
			require_once "config.php";
			 $tenant_id = $_GET["tenant_id"];
			 "::rental_amount_paid::" . $rental_amount_paid = $_GET["rental_amount_paid"];
			$monthYear_water = $_GET['monthYear_water'];
			$water_amount_paid = $_GET['water_amount_paid'];
			$monthYear_others = $_GET['monthYear_others'];
			$others_amount_paid = $_GET['others_amount_paid'];
			$bill_type_id_others = $_GET['bill_type_id_others'];
			$location_id = $_SESSION["location_id"];
			$project_id = $_SESSION["project_id"];
			$type="";
			$location_code = $_SESSION["location_code"];
			$project_code = $_SESSION["project_code"];
			$rental_payment_type = $_GET['rental_payment_type'];
			$water_payment_type = $_GET['water_payment_type'];
			$others_payment_type = $_GET['others_payment_type'];
			$refNo_rental = $_GET['refNo_rental'];
			$refNo_water = $_GET['refNo_water'];
			$refNo_other = $_GET['refNo_other'];
			
			
		if($rental_amount_paid > 0){ //rental part
			 // "RENTAL START"
			$bill_type_id = 1;
			  $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));
			}

			$balance = 0.00;
			$amount_paid = 0.00;
			
			$countData = 1;
			$paidBalance = $rental_amount_paid;
			$arrayData_rentalBills = array();
			$totalAmountPaid = 0.00;
			
			//rental type description
			if($rental_payment_type !="" && $rental_payment_type != null){
				$sqlPaymentType = "select id, payment_type_desc from payment_type where id = $rental_payment_type";
				$runPaymentType = mysqli_query($link, $sqlPaymentType);
				if($runPaymentType === FALSE){
					die(mysqli_error($link));
				}
				$resultPaymentType = mysqli_fetch_assoc($runPaymentType);
				$payment_type_id = $resultPaymentType["id"];
				$payment_type_desc = $resultPaymentType["payment_type_desc"];
			}
			//rental type description
			
			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_id = $resultBills["id"];
				$tenant_id = $resultBills["tenant_id"];
				$bill_no = $resultBills["bill_no"];
				
				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";
				}
				if($totalAmountPaid < $rental_amount_paid && $totalAmountPaid >= 0){
					$paidBalance = $paidBalance - $amount_due;
					if($paidBalance >= 0){
						$amount_due = 0.00;
						$amount_paid = $resultBills["amount_due"];
					}
					else if($paidBalance < 0){
						$amount_due =   abs($paidBalance);
						$amount_paid = $resultBills["amount_due"] - abs($paidBalance);
					}
					if($rental_payment_type > 1 )	{
						$arrayData_rentalBills[] = $bill_id . "," . $countData . "," . $monthYear_issuedate . "," . $type . "," . number_format($amount_paid,2) . "," . $payment_type_desc . ",". $refNo_rental . "," . number_format($amount_due,2);
					}	
					else{
						$arrayData_rentalBills[] = $bill_id . "," . $countData . "," . $monthYear_issuedate . "," . $type . "," . number_format($amount_paid,2) . "," . $payment_type_desc . "," . number_format($amount_due,2);
					}
				}
				
				
				$totalAmountPaid += $amount_paid;
				$countData++;
				
			}
			$arrayLength = count($arrayData_rentalBills);
			$listOut = "";
			$payment_status = "";
			for($y=0;$y<$arrayLength;$y++){
				$payment_status = "unpaid";
				$listOut = explode(',',$arrayData_rentalBills[$y]);
				$list_BillId = $listOut[0];
				$list_monthYear_issuedate = $listOut[2];
				$list_type = $listOut[3];
				$list_amount_paid = $listOut[4];
				$list_payment_type_desc = $listOut[5];
				if($rental_payment_type > 1 )	{
					$list_refNo_rental = $listOut[6];
					$list_amount_due = $listOut[7];
					}	
				else{
					$list_amount_due = $listOut[6];
					}
				
				if($list_amount_due > 0){
					$payment_status = "partial";
				}
				else if($list_amount_due == 0){
					$payment_status = "paid";
				}
				//pull out latest receipt no 
				//IMPORTANT INFO START
				// LOCATION CODE:
				// HCM - PPR HICOM
				// KD - PPR KD
				// CH - COUNCIL HOMES
				// SR - PPR SERENDAH
				// PAYMENT TYPE:
				// SS - BAYARAN SEWA SEMASA
				// ST - BAYARAN SEWA TUNGGAKAN 
				// AS - BAYAR BILL AIR SEMASA
				// AT - BAYAR BILL AIR TUNGGAKAN
				// BILL TYPE ID: 
				// 1 - RENTAL
				// 2 - WATER
				// 3 - MBPJ
				// 4 - LPHS
				// 5 - MBI
				//IMPORTANT INFO END
				
				$payment_type = "";
				if($list_type == "Current" || $list_type == "Advance"){
					// " :: RENTAL - Current :: Advance :: ";
					// " :: BILL TYPE ID - $bill_type_id ::";
					if($bill_type_id == 1)
						$payment_type = "SS";
					else if($bill_type_id == 2)
						$payment_type = "AS";
				}
				else if($list_type == "Outstanding"){
					// " :: RENTAL - OUTSTANDING :: ";
					// " :: BILL TYPE ID - $bill_type_id ::";
					if($bill_type_id != 2){
						// "RENTAL - OUTSTANDING";
						$payment_type = "ST";
					}
					else if($bill_type_id == 2){
							$payment_type = "AT";
					}
				}
				
		
				//Check running number from receipt_number table based on location_id, bill_type_id, and payment_type - start
				$serialNo = "";
				 $sqlRunningNo = "select running_no from receipt_number where location_code = '" . $location_code . "' and  bill_type_id = " . $bill_type_id . " and payment_type = '" . $payment_type . "' order by running_no DESC limit 1";
				$runRunningNo = mysqli_query($link, $sqlRunningNo);
				if($runRunningNo === FALSE){
					die(mysqli_error($link));
				}

				//$running_no = $resultRunningNo["running_no"];
				if(mysqli_num_rows($runRunningNo) == 1){
					$resultRunningNo = mysqli_fetch_assoc($runRunningNo);
					$running_no = $resultRunningNo["running_no"];
			   
					$running_no++;
					$strlenRunningNo = strlen($running_no);
					
					if($strlenRunningNo == 1){
						$serialNo = '0'. $running_no;
					}
					ELSE
						$serialNo = $running_no;
				}
				else if(mysqli_num_rows($runRunningNo) == 0){
					$serialNo = '01';
					$running_no = 1;
				
				}
				//Check running number from receipt_number table based on location_id, bill_type_id, and payment_type - end

			    $receiptNoPayment_rental =  $location_code . '/'.$payment_type . '/' . $serialNo;
				
				
				//INSERT INTO receipt_number table
				//$sqlInsertReceiptNo = "insert into receipt_number value ('','".$_SESSION["location_code"]."',$bill_type_id,'$payment_type',".$running_no.",'".$receiptNoPayment_rental."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertReceiptNo = "insert into receipt_number (location_code,bill_type_id,payment_type,running_no, serial_no, updated_at, created_at) 
															values ('".$_SESSION["location_code"]."',$bill_type_id,'$payment_type',".$running_no.",'".$receiptNoPayment_rental."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertReceiptNo = mysqli_query($link, $sqlInsertReceiptNo);
				if($runInsertReceiptNo === FALSE){
					die(mysqli_error($link));
				}
				//insert into payments table
				//$new_serialNo = $payment_type . "-" . $new_serialNo;
				//$sqlInsertPayments = "insert into payments value ('','".$receiptNoPayment_rental."',".$list_amount_paid.",".$_SESSION["staff_id"] .",".$list_BillId.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				 $sqlInsertPayments = "insert into payments (receipt_no, amount_paid, created_by, bill_id, created_at, updated_at, optional_bill_date)
													values ('".$receiptNoPayment_rental."',".$list_amount_paid.",".$_SESSION["staff_id"] .",".$bill_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayments = mysqli_query($link, $sqlInsertPayments);
				if($runInsertPayments === FALSE){
					die(mysqli_error($link));
				}
				//get latest id insert in payments
				$payment_last_id = mysqli_insert_id($link);
				//insert into payments_paymenttype_bridge (link for payments table with payment_type table)
				$sqlInsertPayment_spaymenttype_bridge = "insert into payments_paymenttype_bridge value (".$payment_last_id.",".$payment_type_id.",'".$refNo_rental."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayment_spaymenttype_bridge = mysqli_query($link, $sqlInsertPayment_spaymenttype_bridge);
				if($runInsertPayment_spaymenttype_bridge === FALSE){
					die(mysqli_error($link));
				}
				
				
				//update bills table
				echo $sqlUpdateBills = "update bills set payment_status = '$payment_status', amount_due = $list_amount_due, updated_at = '".date("Y-m-d H:i:s")."' where id = $list_BillId";
				$runUpdateBills  = mysqli_query($link, $sqlUpdateBills);
				if($runUpdateBills === FALSE){
					die(mysqli_error($link));
				}
				
				
				//include("printReceipt_rental.php");
				include("printPayment3.php");
				
			}
			//  "RENTAL END"
		}
		if($monthYear_water != "" && $water_amount_paid > 0 ){
			// "WATER START"
			$bill_type_id = 2;
			if($monthYear_water == date("Y-m")){
				$type = "Current";
			}
			else if($monthYear_water < date("Y-m")){
				$type = "Outstanding";
			}
			else if($monthYear_water > date("Y-m")){
				$type = "Advance";
			}
			//pull out latest receipt no 
				//IMPORTANT INFO START
				// LOCATION CODE:
				// HCM - PPR HICOM
				// KD - PPR KD
				// CH - COUNCIL HOMES
				// SR - PPR SERENDAH
				// PAYMENT TYPE:
				// SS - BAYARAN SEWA SEMASA
				// ST - BAYARAN SEWA TUNGGAKAN 
				// AS - BAYAR BILL AIR SEMASA
				// AT - BAYAR BILL AIR TUNGGAKAN
				// BILL TYPE ID: 
				// 1 - RENTAL
				// 2 - WATER
				// 3 - MBPJ
				// 4 - LPHS
				// 5 - MBI
				//IMPORTANT INFO END
				
				$payment_type = "";
				if($type == "Current" || $type == "Advance"){
					if($bill_type_id == 1)
						$payment_type = "SS";
					else if($bill_type_id == 2)
						$payment_type = "AS";
				}
				else if($type == "Outstanding"){
					if($bill_type_id != 2)
						$payment_type = "ST";
					else if($bill_type_id == 2)
						$payment_type = "AT";
				}
				
				
				$serialNo = "";
				 $sqlRunningNo = "select running_no from receipt_number where location_code = '" . $location_code . "' and  bill_type_id = " . $bill_type_id . " and payment_type = '" . $payment_type . "' order by running_no DESC limit 1";
				$runRunningNo = mysqli_query($link, $sqlRunningNo);
				if($runRunningNo === FALSE){
					die(mysqli_error($link));
				}

				//$running_no = $resultRunningNo["running_no"];
				if(mysqli_num_rows($runRunningNo) == 1){
					$resultRunningNo = mysqli_fetch_assoc($runRunningNo);
					$running_no = $resultRunningNo["running_no"];
			   
					$running_no++;
					$strlenRunningNo = strlen($running_no);
					
					if($strlenRunningNo == 1){
						$serialNo = '0'. $running_no;
					}
					ELSE
						$serialNo = $running_no;
				}
				else if(mysqli_num_rows($runRunningNo) == 0){
					$serialNo = '01';
					$running_no = 1;
				
				}
				//Check running number from receipt_number table based on location_id, bill_type_id, and payment_type - end

			    $receiptNoPayment_water =  $location_code . '/'.$payment_type . '/' . $serialNo;
				
				
				//INSERT INTO receipt_number table
				//$sqlInsertReceiptNo = "insert into receipt_number value ('', '".$_SESSION["location_code"]."',$bill_type_id,'$payment_type',".$running_no.",'".$receiptNoPayment_water."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertReceiptNo = "insert into receipt_number (location_code,bill_type_id,payment_type,running_no, serial_no, updated_at, created_at) 
															values ('".$_SESSION["location_code"]."',$bill_type_id,'$payment_type',".$running_no.",'".$receiptNoPayment_water."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertReceiptNo = mysqli_query($link, $sqlInsertReceiptNo);
				if($runInsertReceiptNo === FALSE){
					die(mysqli_error($link));
				}
				
				
				//set running no based on bill_no  start
				$sqlSearchBillNo = "SELECT max(bill_no) as maxBill_no FROM `bills` WHERE `bill_no` LIKE '%".$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 = $location_id . "-" . $maxBill_no;
				
				
				
				
				$issue_date_water = "0000-00-00 00:00:00";
				if($monthYear_water != "" ){
					$issue_date_water = date("Y-m-01 H:i:s",strtotime($monthYear_water));
				}
				//2. insert bills table
				//$sqlInsertBills = "insert into bills value ('',".$bill_no.",".$water_amount_paid.",".$water_amount_paid.",'paid','".$issue_date_water."',".$bill_type_id.",".$_SESSION["staff_id"].",".$tenant_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertBills = "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.",".$water_amount_paid.",".$water_amount_paid.",'paid','".$issue_date_water."',".$bill_type_id.",".$_SESSION["staff_id"].",".$tenant_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertBills = mysqli_query($link, $sqlInsertBills);
				$newBill_id = 0;
				if($runInsertBills === FALSE){
					die(mysqli_error($link));
				}
				
				$newBill_id = mysqli_insert_id($link);
				
				
				//rental type description
				if($water_payment_type !="" && $water_payment_type != null){
					$sqlPaymentType = "select id, payment_type_desc from payment_type where id = $water_payment_type";
					$runPaymentType = mysqli_query($link, $sqlPaymentType);
					if($runPaymentType === FALSE){
						die(mysqli_error($link));
					}
					$resultPaymentType = mysqli_fetch_assoc($runPaymentType);
					$payment_type_id = $resultPaymentType["id"];
					$payment_type_desc = $resultPaymentType["payment_type_desc"];
				}
				//rental type description
				
				//insert into payments table
				//echo " receiptNoDeposit:: ". $receiptNoPayment_water =  $location_code . '/'.$bill_code . '/' . $serialNo;
				//$sqlInsertPayments = "insert into payments value ('','".$receiptNoPayment_water."',".$water_amount_paid.",".$_SESSION["staff_id"] .",".$newBill_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertPayments = "insert into payments (receipt_no,amount_paid,created_by,bill_id, created_at, updated_at, optional_bill_date)
													values ('".$receiptNoPayment_water."',".$water_amount_paid.",".$_SESSION["staff_id"] .",".$bill_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayments = mysqli_query($link, $sqlInsertPayments);
				if($runInsertPayments === FALSE){
					die(mysqli_error($link));
				}
				//get latest id insert in payments
				$payment_last_water_id = mysqli_insert_id($link);
				//insert into payments_paymenttype_bridge (link for payments table with payment_type table)
				$sqlInsertPayment_spaymenttype_bridge = "insert into payments_paymenttype_bridge value (".$payment_last_water_id.",".$payment_type_id.",'".$refNo_water."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayment_spaymenttype_bridge = mysqli_query($link, $sqlInsertPayment_spaymenttype_bridge);
				if($runInsertPayment_spaymenttype_bridge === FALSE){
					die(mysqli_error($link));
				}
				
			
			include("printPayment3.php");
			 //"WATER END"
		}
		if($others_amount_paid > 0){
				// "OUTSTANDING START"
				 $type="Outstanding";
				$payment_type = "";
				$payment_status = "";
				$bill_type_id = $bill_type_id_others;
				if($type == "Outstanding"){
					if($bill_type_id != 2)
						$payment_type = "ST";
				}
				$monthYear_others = date("Y-m-01 00:00:00");
				
				 $sqlBills_outstanding = "SELECT * FROM bills 
										WHERE tenant_id = $tenant_id and (payment_status = 'unpaid' or payment_status = 'partial' )  and bill_type_id = ".$bill_type_id_others." AND amount_due > 0 limit 1
										";
				$runBills_outstanding = mysqli_query($link, $sqlBills_outstanding);
				if($runBills_outstanding === FALSE){
					die(mysqli_error($link));
				}
				$balance_outstanding = 0.00;
				$amount_paid_outstanding = 0.00;
				$paid_outstanding = $others_amount_paid;
				$amount_due_balance = 0.00;
				$bill_id = "";
				while($resultBills_outstanding=mysqli_fetch_array($runBills_outstanding)){
					$amount_due = $resultBills_outstanding["amount_due"];
					$bill_id = $resultBills_outstanding["id"];
				}
				$amount_due_balance = $amount_due - $others_amount_paid;						
				if($amount_due_balance > 0){
					$payment_status = "partial";
				}
				else if($amount_due_balance == 0){
					$payment_status = "paid";
				}						
										
			
				
				
				$serialNo = "";
				 $sqlRunningNo = "select running_no from receipt_number where location_code = '" . $location_code . "' and  bill_type_id = " . $bill_type_id . " and payment_type = '" . $payment_type . "' order by running_no DESC limit 1";
				$runRunningNo = mysqli_query($link, $sqlRunningNo);
				if($runRunningNo === FALSE){
					die(mysqli_error($link));
				}

				//$running_no = $resultRunningNo["running_no"];
				if(mysqli_num_rows($runRunningNo) == 1){
					$resultRunningNo = mysqli_fetch_assoc($runRunningNo);
					$running_no = $resultRunningNo["running_no"];
			   
					$running_no++;
					$strlenRunningNo = strlen($running_no);
					
					if($strlenRunningNo == 1){
						$serialNo = '0'. $running_no;
					}
					ELSE
						$serialNo = $running_no;
				}
				else if(mysqli_num_rows($runRunningNo) == 0){
					$serialNo = '01';
					$running_no = 1;
				
				}
				//Check running number from receipt_number table based on location_id, bill_type_id, and payment_type - end

			    $receiptNoPayment_other =  $location_code . '/'.$payment_type . '/' . $serialNo;
				
				
				//INSERT INTO receipt_number table
			    //$sqlInsertReceiptNo = "insert into receipt_number value ('', '".$_SESSION["location_code"]."',$bill_type_id_others,'$payment_type',".$running_no.",'".$receiptNoPayment_other."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertReceiptNo = "insert into receipt_number (location_code,bill_type_id,payment_type,running_no, serial_no, updated_at, created_at) 
															values ('".$_SESSION["location_code"]."',$bill_type_id,'$payment_type',".$running_no.",'".$receiptNoPayment_other."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertReceiptNo = mysqli_query($link, $sqlInsertReceiptNo);
				if($runInsertReceiptNo === FALSE){
					die(mysqli_error($link));
				}
				//rental type description
				$others_payment_type;
				if($others_payment_type !="" && $others_payment_type != null){
					$sqlPaymentType = "select id, payment_type_desc from payment_type where id = $others_payment_type";
					$runPaymentType = mysqli_query($link, $sqlPaymentType);
					if($runPaymentType === FALSE){
						die(mysqli_error($link));
					}
					$resultPaymentType = mysqli_fetch_assoc($runPaymentType);
					$payment_type_id = $resultPaymentType["id"];
					$payment_type_desc = $resultPaymentType["payment_type_desc"];
				}
				//rental type description
				//insert into payments table
				//$new_serialNo = $payment_type . "-" . $new_serialNo;
				//$sqlInsertPayments = "insert into payments value ('','".$receiptNoPayment_other."',".$others_amount_paid.",".$_SESSION["staff_id"] .",".$bill_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$sqlInsertPayments = "insert into payments (receipt_no,amount_paid,created_by,bill_id, created_at, updated_at, optional_bill_date)
													values ('".$receiptNoPayment_other."',".$others_amount_paid.",".$_SESSION["staff_id"] .",".$bill_id.",'".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayments = mysqli_query($link, $sqlInsertPayments);
				if($runInsertPayments === FALSE){
					die(mysqli_error($link));
				}
				//get latest id insert in payments
				$payment_last_other_id = mysqli_insert_id($link);
				//insert into payments_paymenttype_bridge (link for payments table with payment_type table)
				$sqlInsertPayment_spaymenttype_bridge = "insert into payments_paymenttype_bridge value (".$payment_last_other_id.",".$payment_type_id.",'".$refNo_other."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
				$runInsertPayment_spaymenttype_bridge = mysqli_query($link, $sqlInsertPayment_spaymenttype_bridge);
				if($runInsertPayment_spaymenttype_bridge === FALSE){
					die(mysqli_error($link));
				}
				
				
				//update bills table
				$sqlUpdateBills = "update bills set  payment_status = '$payment_status', amount_due = $amount_due_balance, updated_at = '".date("Y-m-d H:i:s")."' where id = $bill_id";
				$runUpdateBills  = mysqli_query($link, $sqlUpdateBills);
				if($runUpdateBills === FALSE){
					die(mysqli_error($link));
				}
				
				include("printPayment3.php");
				// "OUTSTANDING END"
		}	
		