<? include "top.php"; 
	

?>
<!DOCTYPE html>
<html>
<head>
	<?php include('include/head.php'); ?>
	<title>Generate Customer 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'){
		
		$area_id=$_POST['area_id'];
		
		$mnth=$_POST['mnth'];
		$yrs=$_POST['yrs'];


		if($area_id!=''){



			$chk=f(q("SELECT * FROM tbl_server_bill WHERE m_month='$mnth' AND m_year='$yrs' AND m_area='$area_id'"));

		if($chk['m_month']==''){

			$setbill=mysqli_query($con,"INSERT INTO tbl_server_bill SET m_month='$mnth',m_year='$yrs',m_area='$area_id'");
			$msgb="<small style='color:green;'>Bill generation request received, will be completed in the nxt 15 minutes</small>";
		}else{

			$msgb="<small style='color:red;'>Bill generation request already received. </small>";


		}



		}else{


			$sql=mysqli_query($con,"SELECT * FROM `tbl_area`");
			while($row=mysqli_fetch_array($sql)){


				$chk=f(q("SELECT * FROM tbl_server_bill WHERE m_month='$mnth' AND m_year='$yrs' AND m_area='$row[arid]'"));
				$area_id=$row['arid'];
				

				if($chk['m_month']==''){
		
					$setbill=mysqli_query($con,"INSERT INTO tbl_server_bill SET m_month='$mnth',m_year='$yrs',m_area='$area_id'");

					$msgb="<small style='color:green;'>Bill generation request received, will be completed in the nxt 30 minutes</small>";
				}else{
		
					$msgb="<small style='color:red;'>Bill generation request already received. </small>";
		
		
				}


			}


			




		}

		
        
        

		


	}

	


	?>
	<?php 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);
		}

		$stdates=date("Y-m-d");
		$exppdat=strtotime('+29 days', strtotime($stdates));
		$exppdate=date("Y-m-d",$exppdat);

	?>
	<script type="text/javascript">


		function getMonthName(month){
			//alert(month);
			const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];



  const d = new Date(2022,month,10);
  //d.setMonth(month-1);
  //const monthName = d.toLocaleString("default", {month: "short"});
  const monthName = monthNames[month];
  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;

	var endo=new Date(ssomeFormattedDate);
	var mntho=endo.getMonth();
    //alert(mntho);
    //var formattedDate = someFormattedDate.toISOString().substr(0, 10)
    document.getElementById('enddt').value = someFormattedDate;
    var ddl=document.getElementById('mnth');
    var mname=getMonthName(mntho);
    //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);
			var p=parseFloat(document.getElementById('prevdue').value);
			var oth=parseFloat(document.getElementById('oth_due').value);
			var fp=parseFloat(b)+parseFloat(p)+parseFloat(oth);

			if(a<fp){

				var c=parseFloat(fp)-parseFloat(a);
				document.getElementById('amtpaid').value=Math.round(c);

			}else{

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


		}

		function setcur(){

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

		}

		

	</script>
	<style type="text/css">
		.srch{

			font-size: 16px;
		}
		label{

			font-size: 14px;
			font-weight: 600;
		}
	</style>
	<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 style="margin-bottom:5px;">Generate Customer Bill Lineman Wise</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" id="generatebill">
					
					<div class="clearfix" style="min-height: 30px;"></div>
						<input type="hidden" name="lnarid" id="lnarid" value="1">
						<input type="hidden" name="sendsms" value="0">
						
						<div class="form-group row">
							
							<div class="col-sm-12 col-md-4">
                            <label class="col-sm-12 col-md-2">Area</label>
								<div class="col-sm-12 col-md-10">
									<select name="area_id" class="form-control">
										<option value="">All Lineman</option>
										<?
                                        $sql=mysqli_query($con,"SELECT * FROM tbl_login WHERE l_type=2");
                                        while($row=mysqli_fetch_array($sql)){
											$cmon=date('M');
											$yr=date('Y');
											$chk=f(q("SELECT * FROM tbl_server_bill WHERE m_month='$cmon' AND m_year='$yr' AND m_area='$row[l_id]'"));
											if($chk['m_id']==''){

												$isgen=false;
											}else{

												$isgen=true;
											}
											
                                        ?>
                                        <option value="<?=$row['l_id']?>"><?=$row['l_name']?><?php if($isgen==true){?> <small style="font-size:8px;">(done <?php echo $cmon?>,<?php echo $yr?>) </small><?php } ?></option>
                                        <?}?>
									</select>
								</div>
							</div>
							
							
							<div class="col-sm-12 col-md-3">
								<label class="col-sm-12 col-md-12 col-form-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-2">
								<label class="col-sm-12 col-md-12 col-form-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-12">
								<?php echo $msgb;?>
							</div>
						</div>
						
						
						
						
						
						
						
						

						
						
						<div class="clearfix">
						<div class="pull-left">
							
							
						</div>
						<div class="pull-right">
						
							<button type="submit" id="submt" class="btn btn-success btn-sm"><i class="fa fa-save"></i> Generate</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 type="text/javascript">
			
	function setpaynow(vals){


		if(vals==1){

			document.getElementById('amtpaid').value=0;

		}else{

			document.getElementById('amtpaid').value=document.getElementById('billamt').value;
		}


	}

	function postpaidpush(){


		    var element = document.getElementById('postpaid');
    		element.value = 1;
			setpaynow(1);

		document.getElementById("generatebill").submit();//




	}


	function genGST(amts){

		//var nogst=(parseFloat(amts)*parseFloat(100))/118;
		var gstamt=parseFloat(amts)*parseFloat(0.18);
		//var nogst=parseFloat(amts)-parseFloat(gstamt);
		var nogst=parseFloat(amts);
		var totamt=parseFloat(amts)+parseFloat(gstamt);
		
              
              document.getElementById('billdetails').innerHTML="(Pack amt:"+nogst.toFixed(2)+" and gst amt: "+gstamt.toFixed(2)+" )";
			  document.getElementById('nogstval').value=nogst.toFixed(2);
			  document.getElementById('billamt').value=totamt.toFixed(2);


	}


	function setids(){

		var totlp=[];
var selected = [];
var sum = 0;

    for (var option of document.getElementById('alacarte').options)
    {
        if (option.selected) {
            selected.push(option.value);
            totlp.push(option.getAttribute('data'));
                
                    
    }
   
} 

var count=selected.length;
    //document.getElementById('acc').innerHTML=count;
    for (let i = 0; i < totlp.length; i++) {
        sum += parseFloat(totlp[i]);
    }

    document.getElementById('tbillamt').value=sum;
	document.getElementById('tbillamt').focus();
	document.getElementById('countch').value=count;

document.getElementById('multiprice').value=sum;



	}

	</script>

	<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
    });
	<?php if($_SESSION['lype']=='1'){?>$( "#paydt" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
     $( "#paydt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
	$('#paydt').datepicker('setDate', 'today'); <?php } ?>
    //$( "#enddt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
  } );


  window.setTimeout(setcur, 2000);


  $(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});
  </script>
</body>
</html>