<? include "top.php"; 
	

?>
<!DOCTYPE html>
<html>
<head>
	<?php include('include/head.php'); ?>
	<title>Pay Cable Bill</title>
	<link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/jquery.dataTables.css">
	<link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/dataTables.bootstrap4.css">
	<link rel="stylesheet" type="text/css" href="https://sarmac.b-cdn.net/plugins/datatables/media/css/responsive.dataTables.css">
	<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
	<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
	<?php include('include/header.php'); ?>
	<?php include('include/sidebar.php'); 

	$action=$_REQUEST['action'];
	$gcustid=$_REQUEST['custid'];

	if($gcustid!=''){


			$getgc=f(q("SELECT * FROM adduser WHERE id='$gcustid'"));
	}

	if($action=='save'){
		
		$lnarid=$_POST['lnarid'];
		$strtdt=$_POST['strtdt'];
		$enddt=$_POST['enddt'];
		$mnth=$_POST['mnth'];
		$yrs=$_POST['yrs'];
		$custid=$_POST['custid'];	
		$csadded=$_SESSION['murgibhai'];	
		$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
		$postpaid=$_POST['postpaid'];
		$amtpaid=$_POST['amtpaid'];
		$billamt=$_POST['billamt'];
		$discamt=$_POST['discamt'];
		$sendsms=$_POST['sendsms'];
		$paymodes=$_POST['paymodes'];
		$paydt=$_POST['paydt'];

		$priceamt=(floatval($billamt)/118)*100;
		$bgstamt=floatval($billamt)-floatval($priceamt);
		// if(floatval($discamt)>0){

		// 	$priceamt=floatval($priceamt)-floatval($discamt);

		// }
		//$priceamt=floatval($billamt)-floatval($bgstamt);
		$gstamt=round(floatval($bgstamt),2);
		

		$checkexpiry=f(q("SELECT * FROM adduser WHERE id='$custid'"));

		if($checkexpiry['is_cable']=='1'){

			$bl_tp='1';
		}else{

			$bl_tp='0';
		}

		if($checkexpiry['name']!=''){

			$getmax=f(q("SELECT MAX(blid) as maxid FROM cbill"));
			

			$maxid=$getmax['maxid'];
			$maxid=floatval($maxid)+1;

			$sumdue=f(q("SELECT bl_amt FROM cbill WHERE bl_cid='$custid'  ORDER BY blid DESC LIMIT 1"));
			$tdue=$sumdue['bl_amt'];

			$getdues=f(q("SELECT bl_payamt FROM cbill WHERE bl_cid='$custid'  ORDER BY blid DESC LIMIT 1"));
			$totpay=$getdues['bl_payamt'];


			$tdue=floatval($tdue)-floatval($totpay);

			if($tdue==''){
				$tdue=0;
			}
			$currentb=floatval($billamt);
			$dueamt=$currentb;

			$dues=(floatval($dueamt)-floatval($discamt))-floatval($amtpaid);


			// echo "Outstanding: ".$tdue."<br>";
			// echo "Current Bill: ".$currentb."<br>";
			// echo "Current Dues: ".$dues."<br>";

			//die();

			$dates = $checkexpiry['pexpiry'];
			if($dates=='2020-09-01'){
			$expdate=$strtdt;
			}else{

					// $curdate=new DateTime($dates);
					// $newstdate=new DateTime($strtdt);


					// if($curdate>$newstdate){

					// 	$expdate=$dates;
					// }elseif($curdate==$newstdate){

					// 	$expdate=strtotime('+1 days', strtotime($dates));
					// 	$expdate=date("Y-m-d",$expdate);
					// }elseif($curdate<$newstdate){

						$expdate=$strtdt;
					//}


			}

			

			//echo "Expiry".$expdate; die();

			$thirtyDaysUnix = date('Y-m-d', strtotime($expdate. ' + 29 days')); 
			//echo "EXPIRY".$thirtyDaysUnix; die();
			$expirydate=$thirtyDaysUnix;
			$pkid=$checkexpiry['packid'];
			if($pkid==''){

				$pkid='0';
			}
		

				if($postpaid=='0'){

					$sqls="INSERT INTO cbill SET bl_cid='$custid',bl_dt=CURDATE(),bl_pid='$pkid',bl_no='$maxid',bl_cname='$checkexpiry[name]',bl_address='$checkexpiry[address]',bl_phone='$checkexpiry[phone]',bl_paych='$checkexpiry[pay_ch]',bl_amt='$currentb',bl_payamt='$amtpaid',bl_stat='1',bl_paydt='$paydt',bl_paymd='$paymodes',bl_trn='$txnid',bl_payuid='NA',bl_due='$dues',bl_prevdue='$tdue',bl_user='$csadded',bl_expiry='$expirydate',bl_tp='$bl_tp',bl_month='$mnth',bl_year='$yrs',bl_stdt='$strtdt',bl_disc='$discamt',bl_gst='$gstamt',bl_pak='$priceamt'";

						

				}else{

					$sqls="INSERT INTO cbill SET bl_cid='$custid',bl_dt=CURDATE(),bl_pid='$pkid',bl_no='$maxid',bl_cname='$checkexpiry[name]',bl_address='$checkexpiry[address]',bl_phone='$checkexpiry[phone]',bl_paych='$checkexpiry[pay_ch]',bl_amt='$currentb',bl_payamt='0',bl_stat='0',bl_paydt='$paydt',bl_paymd='NA',bl_trn='$txnid',bl_payuid='NA',bl_due='$currentb',bl_prevdue='$tdue',bl_user='$csadded',bl_expiry='$expirydate',bl_tp='$bl_tp',bl_month='$mnth',bl_year='$yrs',bl_stdt='$strtdt',bl_disc='$discamt',bl_gst='$gstamt',bl_pak='$priceamt'";
				}

			$res=mysqli_query($con,$sqls);
			$blid=mysqli_insert_id($con);

			if($res){

					if($postpaid=='0'){

						$gstval='18';
						$gstamt=floatval($amtpaid)*(18/118);

						$instrn=mysqli_query($con,"INSERT INTO tbl_trans SET trn_ac='$custid',trn_name='$checkexpiry[name]',trn_amt='$amtpaid',trn_date=CURDATE(),trn_type='DEPOSIT AC',trn_gst=1,trn_grate='18',trn_gamt='$gstamt',trn_memo='Bill Amount received for $checkexpiry[name]'");

					}

			}

			//echo "INSERT INTO cbill SET bl_cid='$custid',bl_dt=CURDATE(),bl_pid=0,bl_no='$maxid',bl_cname='$checkexpiry[name]',bl_address='$checkexpiry[address]',bl_phone='$checkexpiry[phone]',bl_paych='$checkexpiry[pay_ch]',bl_amt='$currentb',bl_payamt='0',bl_stat='0',bl_paydt=CURDATE(),bl_paymd='NA',bl_trn='$txnid',bl_payuid='NA',bl_due='$currentb',bl_prevdue='$tdue',bl_user='$csadded',bl_expiry='$expirydate'";
			if($res){


				$res1=mysqli_query($con,"UPDATE adduser SET mnth='$mnth',yrs='$yrs',pexpiry='$expirydate',actv=1,price='$priceamt' WHERE id='$custid'");


                 









				if($postpaid=='0'){


					if($sendsms=='1'){

						$checksms=f(q("SELECT COUNT(*) as total FROM tbl_sms" ));
						if(floatval($checksms['total'])<=5000){
										$mobno=$checkexpiry['phone'];
										if($mobno!=''){
											$msgg="Dear user your bill has been generated amount is $currentb. Paid amount is: $amtpaid";
											require("lib/sender.php");

											$obj = new Sender("8013928783","39678","PATSMS",$msgg, $mobno);
											$obj->Submit ();

											

												

						                        $insms=mysqli_query($con,"INSERT INTO tbl_sms SET cnt=1");
						                       // echo $result;

										}
						}				
					}

				?>

				 <script type="text/javascript">
	            Swal.fire('Bill Generated','','success').then(function() {
    window.open('payonline.php?blid=<?=$txnid?>','_blank');
     //window.open('generatebill.php','_parent');
});
	             </script>
		<?	}else{


				if($sendsms=='1'){
							$mobno=$checkexpiry['phone'];
						$checksms=f(q("SELECT COUNT(*) as total FROM tbl_sms" ));
						if(floatval($checksms['total'])<=5000){
								if($mobno!=''){

									$msgg="Dear user your bill has been generated amount is $currentb. Due amount is: $dues";

										require("lib/sender.php");

											$obj = new Sender("8013928783","39678","PATSMS",$msgg, $mobno);
											$obj->Submit ();
				                        $count=floatval($count)+1;
				                        $insms=mysqli_query($con,"INSERT INTO tbl_sms SET cnt=1");

								}

						}		
				} 				

			?>  

				<script type="text/javascript">
	           Swal.fire('Bill Generated','','success').then(function() {
    			window.open('payonline.php?blid=<?=$txnid?>','_blank');
     			// window.open('generatebill.php','_parent');
});
	             </script>


	<? } }

		}else{?>


			 <script type="text/javascript">
            Swal.fire('Bill already generated for this customer','','error')
             </script>


	<?	}

			
				// $res=mysqli_query($con,"INSERT INTO tbl_lane SET lnname='$lnname',lnarid='$lnarid'");

			



	}

	


	?>
	<? include "ajax.php"; 


		if($gcustid==''){

			$currentdt=date("Y-m-d");
		$thirtyDaysUnix = strtotime('+29 days', strtotime($currentdt));
		$fetdt=date("Y-m-d",$thirtyDaysUnix);
		//echo "HELLO";

		}else{


			$currentdt=strtotime('+1 days', strtotime($getgc['pexpiry']));
			$currentdt=date("Y-m-d",$currentdt);
			$thirtyDaysUnix = strtotime('+29 days', strtotime($currentdt));
			$fetdt=date("Y-m-d",$thirtyDaysUnix);
		}

		

	?>
	<script type="text/javascript">
		function getMonthName(month){
			//alert(month);
  const d = new Date();
  d.setMonth(month-1);
  const monthName = d.toLocaleString("default", {month: "short"});
  return monthName;
}
		function setdt(oldDate){

			//var nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+30);
			 var tt = oldDate;

    var date = new Date(tt);
    var ddd = date.getDate();
    var mmm = date.getMonth()+1;
    var yyy = date.getFullYear();

    var ssomeFormattedDate = yyy + '-' + mmm + '-' + ddd;
    document.getElementById('strdt').value = ssomeFormattedDate;


    var newdate = new Date(date);

    newdate.setDate(newdate.getDate() + 29);
    
    var dd = newdate.getDate();
    var mm = newdate.getMonth() + 1;
    var y = newdate.getFullYear();

    var someFormattedDate = y + '-' + mm + '-' + dd;
    //alert(someFormattedDate);
    //var formattedDate = someFormattedDate.toISOString().substr(0, 10)
    document.getElementById('enddt').value = someFormattedDate;
    var ddl=document.getElementById('mnth');
    var mname=getMonthName(mmm);
    //alert(mname);

    var opts = ddl.options.length;
			for (var i=0; i<opts; i++){
			    if (ddl.options[i].value == mname){
			        ddl.options[i].selected = true;
			        break;
			    }
			}


		}


		function setpayamt(){


			var a=parseFloat(document.getElementById('discamt').value);
			var b=parseFloat(document.getElementById('billamt').value);

			if(a<b){

				var c=parseFloat(b)-parseFloat(a);
				document.getElementById('amtpaid').value=c;

			}else{

				//alert("Discount amount cannot be greater than the bill amount");
				document.getElementById('discamt').value='0';
				document.getElementById('amtpaid').value=b;
				
			}
			


		}

		function setcur(){

			document.getElementById('srch').focus();

		}

		

	</script>
	<div class="main-container">
		<div class="pd-ltr-20 customscroll customscroll-10-p height-100-p xs-pd-20-10">
			<div class="min-height-200px">
				<div class="page-header">

					<div class="row">
						<div class="col-md-6 col-sm-12">
							<div class="title">
								<h4>Generate Customer Bill</h4>
							</div>
							<nav aria-label="breadcrumb" role="navigation">
								<ol class="breadcrumb">
									<li class="breadcrumb-item"><a href="index.php">Home</a></li>
									<li class="breadcrumb-item active" aria-current="page">Generate Customer Bill</li>
								</ol>
							</nav>
						</div>
						<div class="col-md-6 col-sm-12 text-right">
							<!-- <div class="dropdown">
								<a class="btn btn-secondary dropdown-toggle" href="#" role="button" data-toggle="dropdown">
									January 2018
								</a>
								<div class="dropdown-menu dropdown-menu-right">
									<a class="dropdown-item" href="#">Export List</a>
									<a class="dropdown-item" href="#">Policies</a>
									<a class="dropdown-item" href="#">View Assets</a>
								</div>
							</div> -->
						</div>
					</div>
				</div>
				<!-- Default Basic Forms Start -->
				<div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
					<small style="color: red;"><?=$msg?></small>
					<form action="<?=$_SERVER['PHP_SELF']?>?action=<? if($action=='edit'){?>update&cid=<?=$cid?><? }else{?>save<?} ?>" method="POST">
					<input type="hidden" name="lnarid" id="lnarid" value="1">
					<div class="clearfix" style="min-height: 30px;"></div>

						<div class="form-group row">
							
							<!-- <label class="col-sm-12 col-md-2 col-form-label">Search Customer</label> -->
							<div class="col-sm-12 col-md-3">
								<label>Customer ID</label>
								<input class="form-control" type="text" name="serch" id="srch" placeholder="Acno / VC / STB / Phone Number" value="<? if($gcustid!=''){ echo $getgc['custid']; }?>" readonly required onblur="getcust()">
							</div>
						
					
						
						<?php
							if($gcustid!=''){ ?>

								<script type="text/javascript">
									getcust();

								</script>

						<?php	}

						?>

						<div class="col-sm-12 col-md-3">
								<label>Start</label>
								<input class="form-control" type="text" placeholder="yyyy-mm-dd" id="strdt" name="strtdt"  value="<?=$currentdt?>" onchange="setdt(this.value)" readonly>
						</div>
						<div class="col-sm-12 col-md-3">
							<label>End</label>
								<input class="form-control" type="text" placeholder="yyyy-mm-dd"  id="enddt" name="enddt"  value="<?=$fetdt?>" readonly>
						</div>
						<div class="col-sm-12 col-md-3">
							<label>Bill Amount</label>
								<input class="form-control" type="text" name="billamt" id="billamt"  value="" readonly>
							</div>




						</div>
						
						<div class="form-group row">
							
							<div class="col-sm-12 col-md-3">
								<label>Month</label>
								<select class="form-control" name="mnth" id="mnth">
									<option value="Jan" <? if(date('m')=='1'){?> selected <? } ?>>Jan</option>	
									<option value="Feb" <? if(date('m')=='2'){?> selected <? } ?>>Feb</option>	
									<option value="Mar" <? if(date('m')=='3'){?> selected <? } ?>>Mar</option>	
									<option value="Apr" <? if(date('m')=='4'){?> selected <? } ?>>Apr</option>	
									<option value="May" <? if(date('m')=='5'){?> selected <? } ?>>May</option>	
									<option value="Jun" <? if(date('m')=='6'){?> selected <? } ?>>Jun</option>	
									<option value="Jul" <? if(date('m')=='7'){?> selected <? } ?>>Jul</option>	
									<option value="Aug" <? if(date('m')=='8'){?> selected <? } ?>>Aug</option>	
									<option value="Sep" <? if(date('m')=='9'){?> selected <? } ?>>Sep</option>	
									<option value="Oct" <? if(date('m')=='10'){?> selected <? } ?>>Oct</option>	
									<option value="Nov" <? if(date('m')=='11'){?> selected <? } ?>>Nov</option>	
									<option value="Dec" <? if(date('m')=='12'){?> selected <? } ?>>Dec</option>	
									

								</select>
							</div>
							
							<div class="col-sm-12 col-md-3">
								<label>Year</label>
								<select class="form-control" name="yrs" id="yrs">
									<?
										for($i=2020;$i<=2030;$i++){
									?>
									<option value="<?=$i?>" <? if(date('Y')==$i){?> selected <? } ?>><?=$i?></option>	
									<? } ?>	
									

								</select>
							</div>
							<div class="col-md-3" style="padding-top:30px;">

								<button type="button" class="btn btn-primary btn-sm" onclick="getcust()"><i class="fa fa-search"></i></button>

							</div>

						</div>
						<div class="form-group row">
							<input type="hidden" name="postpaid" value="1">
							<input type="hidden" name="discamt" id="discamt" value="0">
							<input type="hidden" name="amtpaid" id="amtpaid" value="0">
							<script type="text/javascript">
									getcust();
									setpayamt();

							</script>
							<input type="hidden" name="sendsms" id="sendsms" value="0">
							<input type="hidden" name="paymodes" id="paymodes" value="ONLINE">
							<input type="hidden" name="paydt" id="paydt" value="<?php echo date('Y-m-d')?>">
							<input type="hidden" name="remarks" id="remarks" value="Paid by Customer">

							<!-- <label class="col-sm-12 col-md-2 col-form-label">Bill Amount</label>
							
							<div class="col-md-2"></div>
							<label class="col-sm-12 col-md-2 col-form-label  pull-right">Postpaid Bill</label>
							<div class="col-sm-12 col-md-3">
								<select class="form-control" name="postpaid">
								<option value="0">No</option>
								<option value="1">Yes</option>
							</select>
							</div> -->
						</div>
						<!-- <div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Discount Amount</label>
							<div class="col-sm-12 col-md-3">
								<input class="form-control" type="text" name="discamt" id="discamt"  value="" onblur="setpayamt()">
							</div>
							<div class="col-md-2"></div>
							<label class="col-sm-12 col-md-2 col-form-label">Amount Paid</label>
							<div class="col-sm-12 col-md-3">
								<input class="form-control" type="text" name="amtpaid" id="amtpaid"  value="">
							</div>
							<div class="col-md-2"></div>
							
						</div>
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label  pull-right">Send SMS</label>
							<div class="col-sm-12 col-md-3">
								<select class="form-control" name="sendsms">
								
								<option value="1">Yes</option>
								<option value="0">No</option>
							</select>
							</div>
							<div class="col-md-2"></div>

							<label class="col-sm-12 col-md-2 col-form-label  pull-right">Payment Mode</label>
							<div class="col-sm-12 col-md-3">
								<select class="form-control" name="paymodes">
								
								<option value="CASH">Cash</option>
								<option value="UPI">UPI</option>
								<option value="CHEQUE">Cheque</option>
								<option value="BANK_TRANSFER">Bank Transfer</option>
								<option value="CREDIT_CARD">Credit Card</option>
								<option value="DEBIT_CARD">Debit Card</option>
								<option value="ONLINE">Online Payment</option>
							</select>
							</div>
						</div>
						<div class="form-group row">
							<label class="col-sm-12 col-md-2 col-form-label">Pay Date</label>
							<div class="col-sm-12 col-md-3">
								<input class="form-control" type="date" placeholder="yyyy-mm-dd"  id="paydt" name="paydt"  value="<?php echo date('Y-m-d')?>">
							</div>
							<div class="col-md-2"></div>
							
							
						</div>
						
						<div class="form-group row">
							
							<div class="col-md-8">
								<label class="col-sm-12 col-md-12 col-form-label  pull-right">Remarks</label>
								<textarea class="form-control" name="remarks"></textarea>


							</div>
							
							
						</div> -->

						<div class="form-group row">
							<input type="hidden" name="custid" id="custid">
							<div class="col-md-12"><span id="cname"></span><br></div>
							<div class="col-md-12"><span id="caddr"></span><br></div>
							<div class="col-md-12"><span id="cphone"></span><br></div>
							<div class="col-md-12"><span id="cacno"></span><br></div>
							<div class="col-md-12"><span id="cvc"></span><br></div>
							<div class="col-md-12"><span id="cstb"></span><br></div>
							<div class="col-md-12"><span id="cprice"></span><br></div>
							<div class="col-md-12"><span id="cexpiry"></span><br></div>
							<div class="col-md-12"><span id="cpack"></span><br></div>




						</div>

						
						
						<div class="clearfix">
						<div class="pull-left">
							<!-- <h4 class="text-blue">Default Basic Forms</h4>
							<p class="mb-30 font-14">All bootstrap element classies</p> -->
							<!-- <button type="button" class="btn btn-primary btn-sm" onclick="getcust()"><i class="fa fa-save"></i> Search</button> -->
						</div>
						<div class="pull-right">
													
							<!-- <a href="#basic-form1" class="btn btn-primary btn-sm scroll-click" rel="content-y"  data-toggle="collapse" role="button"><i class="fa fa-code"></i> Source Code</a> -->
							<button type="submit" id="submt" class="btn btn-primary btn-sm" disabled="true"><i class="fa fa-save"></i> Pay Now</button>
						</div>
					</div>
					</form>
					<div class="collapse collapse-box" id="basic-form1" >
						
					</div>
				</div>
				

			</div>
			<?php include('include/footer.php'); ?>
		</div>
	</div>
	<?php include('include/script.php'); ?>

	<script src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
	<script src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
	<!-- buttons for Export datatable -->
	<script src="src/plugins/datatables/media/js/button/dataTables.buttons.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.print.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.html5.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.flash.js"></script>
	<script src="src/plugins/datatables/media/js/button/pdfmake.min.js"></script>
	<script src="src/plugins/datatables/media/js/button/vfs_fonts.js"></script>
	<script>
		$('document').ready(function(){
			$('.data-table').DataTable({
				scrollCollapse: true,
				autoWidth: false,
				responsive: true,
				columnDefs: [{
					targets: "datatable-nosort",
					orderable: false,
				}],
				"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
				"language": {
					"info": "_START_-_END_ of _TOTAL_ entries",
					searchPlaceholder: "Search"
				},
			});
			$('.data-table-export').DataTable({
				scrollCollapse: true,
				autoWidth: false,
				responsive: true,
				columnDefs: [{
					targets: "datatable-nosort",
					orderable: false,
				}],
				"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
				"language": {
					"info": "_START_-_END_ of _TOTAL_ entries",
					searchPlaceholder: "Search"
				},
				dom: 'Bfrtip',
				buttons: [
				'copy', 'csv', 'pdf', 'print'
				]
			});
			var table = $('.select-row').DataTable();
			$('.select-row tbody').on('click', 'tr', function () {
				if ($(this).hasClass('selected')) {
					$(this).removeClass('selected');
				}
				else {
					table.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			});
			var multipletable = $('.multiple-select-row').DataTable();
			$('.multiple-select-row tbody').on('click', 'tr', function () {
				$(this).toggleClass('selected');
			});

			setcur();
		});

	</script>
	
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#strdt" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
    //$( "#strdt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

    $( "#enddt" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
    //$( "#enddt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
  } );


  window.setTimeout(setcur, 2000);
  </script>
</body>
</html>