<? include "top.php"; ?>
<!DOCTYPE html>
<html>
<head>
	<?php include('include/head.php'); ?>
	<title>Generate Customer Bill</title>
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/jquery.dataTables.css">
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/dataTables.bootstrap4.css">
	<link rel="stylesheet" type="text/css" href="src/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'];
	$custpayid=$_REQUEST['custpayid'];
	if($action=='save'){
		if($psave==1){
		$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'];
		$lineman=$_POST['lineman'];
		$getlog=f(q("SELECT * FROM tbl_login WHERE l_id='$lineman'"));
		$ltype=$getlog['l_type'];
		$paymodes=$_POST['paymodes'];
		$disc=$_POST['disc'];
		$bl_remarks=$_POST['bl_remarks'];
		$linemanuid=$getlog['l_uid'];

		
		

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

		$care=$checkexpiry['area_id'];

		if($ltype=='2'){

			if($care!=$getlog['user_id']){ ?>

				<script type="text/javascript">
            Swal.fire('Lineman doesnt have access to this area','','error').then(function() {
    window.open('customer-payments.php','_parent');
    });


             </script>

		<?   	}


		}

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

			$getmax=f(q("SELECT MAX(blid) as maxid FROM cbill WHERE bl_cid='$custid' AND bl_due>0"));
			

			$maxid=$getmax['maxid'];
			$blid=$maxid;
			$getbilld=f(q("SELECT * FROM cbill WHERE blid='$blid'"));
			$prepay=$getbilld['bl_payamt'];
			$totpay=floatval($prepay)+floatval($amtpaid);
			$totpayment=floatval($totpay)+floatval($disc);
			$dues=floatval(floatval($getbilld['bl_amt'])+floatval($getbilld['bl_prevdue']))-floatval($totpayment);


			if(floatval($blid)>0){
						$getbils=f(q("SELECT * FROM cbill WHERE blid='$blid'"));
						$txnid=$getbils['bl_trn'];
						$res=mysqli_query($con,"UPDATE cbill SET bl_payamt='$totpay',bl_stat=1,bl_due='$dues',bl_paymd='$paymodes',bl_paydt='$strtdt',bl_disc='$disc',bl_remarks='$bl_remarks' WHERE blid='$blid'");

			
			if($res){

				$gstval='18';
						$gstamt=floatval($amtpaid)*(18/118);
				$inspay=mysqli_query($con,"INSERT INTO tbl_billpay SET pay_date='$strtdt',pay_amt='$amtpaid',pay_bill='$blid',pay_by='$paymodes',pay_user='$linemanuid',pay_rmrk='$bl_remarks'");
				$instrn=mysqli_query($con,"INSERT INTO tbl_trans SET trn_ac='$custid',trn_name='$checkexpiry[name]',trn_amt='$amtpaid',trn_date='$strtdt',trn_type='MONTHLY BILL',trn_gst=1,trn_grate='18',trn_gamt='$gstamt',trn_memo='Bill Amount received for $checkexpiry[name]',trn_billid='$blid'");

				?>
				 <script type="text/javascript">
			          Swal.fire('Payment Updated','','success').then(function() {
						// Send SMS automatically after successful payment
						
					});
			           </script>
		<? $issentsms='1';	}

		}else{?>


			<script type="text/javascript">
            Swal.fire('No unpaid bill for this customer','','error')
            </script>


	<?	}

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

	}else{

		?>
		 <script type="text/javascript">
			Swal.fire('You dont have permission ','','error')
			 </script>

		<?
	}

	}

	


	?>
	<? include "ajax.php"; 
		$currentdt=date("Y-m-d");
		$thirtyDaysUnix = strtotime('+30 days', strtotime($currentdt));
		$fetdt=date("Y-m-d",$thirtyDaysUnix);

	?>
	<script type="text/javascript">
		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() + 30);
    
    // 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;

		}

	</script>
	<script type="text/javascript">
			
			function disco(vals){

						var billamt=document.getElementById('totaldues').value;

						if(vals==''){

							document.getElementById('disc').value='0';
							vals=0;
						}
						var payamt=parseFloat(billamt)-parseFloat(vals);
						document.getElementById('amtpaid').value=payamt;

			}

	</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>Customer Payment Entry</h4>
							</div>
							
						</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" onkeydown="if(event.keyCode === 13) {
    alert('You have pressed Enter key, use submit button instead'); 
    return false;
}">
					
					<div class="clearfix" style="min-height: 30px;"></div>
						<input type="hidden" name="lnarid" id="lnarid" value="1">

						<div class="form-group row">
							<label class="col-sm-12 col-md-1 col-form-label">Search</label>
							<div class="col-sm-12 col-md-2">
								
								<input class="form-control" type="text" name="serch" id="srch" placeholder="Acno / VC / STB / Phone Number / Username / IP Address" value="<?php echo $custpayid;?>" required onblur="getcustp()">
								
							</div>
							<div class="col-md-1"><button type="button" class="btn btn-primary"  onclick="getcustp()"><i class="fa fa-search"></i></button></div>
							<?php 

								if($custpayid!=''){

									echo "<script>getcustp();</script>";

								}
							
							?>
							<label class="col-sm-12 col-md-2 col-form-label text-right">Pay Type</label>
							<div class="col-sm-12 col-md-2">
								<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>
							<label class="col-sm-12 col-md-2 col-form-label text-right">Pay Date</label>
							<div class="col-sm-12 col-md-2">
								<input class="form-control" type="text" placeholder="yyyy-mm-dd" id="strdt" name="strtdt"  value="<?=$currentdt?>" onchange="setdt(this.value)" <?php if($_SESSION['lype']!='1'){?> readonly <?php } ?>>
							</div>
							
						</div>
						<div class="form-group row">
						
								<label class="col-sm-12 col-md-1 col-form-label">Lineman</label>
								<div class="col-sm-12 col-md-3">
								<select name="lineman" class="form-control" id="lineman" required>
								<option></option>
											<?php 

													$ql=mysqli_query($con,"SELECT * FROM tbl_login WHERE l_type=2 ORDER BY l_name");
													while($arrcl=mysqli_fetch_array($ql)){
											
											?>
													<option value="<?php echo $arrcl['l_id']?>" ><?php echo $arrcl['l_name']?></option>

								<?php } ?>
								</select>
													</div>
								


							
						</div>
						<div class="form-group row" style="border:1px solid gray; border-radius: 10px;padding:10px;">
							<input type="hidden" name="custid" id="custid">
							<div class="col-md-3"><span id="cname">Name: </span><br></div>
							<div class="col-md-3"><span id="cadd">Address: </span><br></div>
							
							<div class="col-md-3"><span id="cphone">Phone: </span><br></div>
							<div class="col-md-3"><span id="cacno">Ac NO: </span><br></div>
							<div class="col-md-3"><span id="cvc">VC No: </span><br></div>
							<div class="col-md-3"><span id="cstb">STB No:</span><br></div>
							<div class="col-md-3"><span id="cprice">Price</span><br></div>
							<div class="col-md-3"><span id="cpack">MSO: </span><br></div>
							<div class="col-md-3"><span id="cexpiry">Last Payment: </span><br></div>
							
							<div class="col-md-3"><span id="caddr">Last Paydate: </span><br></div>
							<div class="col-md-3"><span id="cdue">Due: </span><br></div>




						</div>
					
						
						<div class="form-group row">
							<input type="hidden" name="billamt" id="billamt" value="0">
							<input type="hidden" name="totaldues" id="totaldues" value="0">
							
							<label class="col-sm-12 col-md-1 col-form-label">Discount</label>
							<div class="col-sm-12 col-md-2">
								<input class="form-control" type="text" name="disc" id="disc"  value="0" onblur="disco(this.value)">
							</div>
							<!-- <label class="col-sm-12 col-md-2 col-form-label text-right">Sub Total</label>
							<div class="col-sm-12 col-md-2">
								<input class="form-control" type="text" name="subt" id="subt"  value="0">
							</div> -->
							<label class="col-sm-12 col-md-2 col-form-label text-right">Pay Amount</label>
							<div class="col-sm-12 col-md-2">
								<input class="form-control" type="number" required min="0" step=".01" oninput="validity.valid||(value='');" name="amtpaid" id="amtpaid"  value="0">
							</div>
							<label class="col-sm-12 col-md-2 col-form-label text-right">Remarks</label>
							<div class="col-md-3">
								
								<input type="text" class="form-control" name="bl_remarks">
								


							</div>
						</div>
						
						<div class="form-group row">
							<!-- <label class="col-sm-12 col-md-2 col-form-label">Month</label>
							<div class="col-sm-12 col-md-3">
								<select class="form-control" name="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-md-2"></div>
							<label class="col-sm-12 col-md-2 col-form-label  pull-right">Year</label>
							<div class="col-sm-12 col-md-3">
								<select class="form-control" name="yrs">
									<?
										for($i=2020;$i<=2030;$i++){
									?>
									<option value="<?=$i?>" <? if(date('Y')==$i){?> selected <? } ?>><?=$i?></option>	
									<? } ?>	
									

								</select>
							</div> -->
						</div>
						<div class="form-group row">
							
							<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="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="getcustp()"><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" ><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');
			});
		});
	</script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<?php if($_SESSION['lype']=='1'){?> <script>
  $( function() {
    $( "#strdt" ).datepicker({
      changeMonth: true,
      changeYear: true
    });
    //$( "#strdt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

   
  } );
  </script><?php } ?>

  <script>
		function sendAutoSMS(phone, message) {
			console.log('sendAutoSMS called with phone:', phone, 'and message:', message);
			if (phone && message) {
				// Encode the message for URL safety
				var encodedMsg = btoa(unescape(encodeURIComponent(message)));

				// Make AJAX call to send-sms.php
				$.ajax({
					url: 'send-sms.php',
					type: 'POST',
					data: {
						action: 'sendsms',
						cphone: phone,
						msgs: encodedMsg
					},
					dataType: 'json',
					success: function (response) {
						console.log('SMS sent successfully to', phone);
						if (!response.success) {
							console.error('SMS sending failed:', response.error || 'Unknown error');
						}
					},
					error: function (xhr, status, error) {
						console.error('SMS sending failed:', error);
					}
				});
			} else {
				console.log('sendAutoSMS called but phone or message is missing');
			}
		}
	</script>
	<?php 

		if($issentsms=='1'){
			?>

			<script>
				var phone = '<?=$checkexpiry["phone"]?>';
						var msg = '<?php echo SITE_NAME?>\n\nDear <?=$checkexpiry["name"]?>, your payment of Rs.<?=$amtpaid?> has been received. Thank you for your payment.';
						sendAutoSMS(phone, msg);
						window.open('customer-payments.php','_parent');
			</script>

	<?php	}
	
	?>
</body>
</html>