<?php 

include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdme_Payment_Details($db,'');
include_once "includes/pagepermission.php";



//check permission - START
if(!($res_modm_prm)){
	header("Location:".admin_public_url."error.php");
}
//check permission - END

$id=$_REQUEST['id'];
if($id!="")
{
	
//check edit permission - START	
if(trim($res_modm_prm['EditPrm'])=="0") {
?>
<script>
  window.location="error.php";
</script>
<?php	
}
//check edit permission - END	

$operation="Edit";
$act="update";
$btn='Update';

$str_ed = "select * from t_payment_main where IsActive != '2' and id = '".base64_decode($id)."' ";
$pdt_ed = "select * from t_payment_details where IsActive != '2' and payment_id = '".base64_decode($id)."' ";
// $sale_ed = "SELECT * FROM t_sales_payment WHERE actu_bill_no = '".base64_decode($id)."' ";



$res_ed = $db->get_a_line($str_ed);
$payment_ed = $db->get_results($pdt_ed);
// $sale_ed = $db->get_a_line($sale_ed);
$customer_details = $db->get_a_line("SELECT * from m_customer where cus_id = '".$res_ed['cus_id']."' ");


$edit_id = $res_ed['id'];
$company_id = $res_ed['company_id'];
$cus_id = $res_ed['cus_id'];
$notes = $res_ed['notes'];
$pay_id = $payment_ed['payment_id'];


$rslt_pdt_list = $db->get_rsltset("SELECT * FROM `t_payment_details` WHERE `payment_id` = '".$edit_id."'   ");


$pdt_sv_cnt = count($rslt_pdt_list);

$disp_pdt_cnt=1;
if($pdt_sv_cnt >0){
	$disp_pdt_cnt =$pdt_sv_cnt;
}


$chk='';
if($res_ed['IsActive']=='1')
{
	$chk='checked';
}

}
else
{
	
//check edit permission - START	
if(trim($res_modm_prm['AddPrm'])=="0") {
?>
<script>
  window.location="error.php";
</script>
<?php	
}
//check edit permission - END
	$operation="Add";
	$act="insert";
	$btn='Save';
	
$disp_pdt_cnt=1;

//$disp_over_all_tot=0;
//$edit_id=0;
}

?>    
<style>
    .custom-padding {
        padding-bottom: 10px; 
    }
	.green-color {
        color:green;
		font-size: 18px;
    }
</style>

<div class="wrapper">
    <div class="container">        
		<!-- Page-Title - START -->
        <div class="row">
            <div class="col-sm-5">										
                <h4 class="page-title"><?php echo $operation; ?> Payment Entry</h4>						
            </div>
        </div>
		<!-- Page-Title - END -->	
                                <?php
										$readonly = ($operation === "Edit") ? 'readonly' : ''; 
										$disabled = ($operation === "Edit") ? 'disabled' : ''; 
										$display = ($operation === "Edit") ? '' : 'none'; 
										?>		
		<div class="row">
			<div class="col-sm-12">
				<form id="jvalidate" name="frmpayment" role="form" class="form-horizontal" action="payment_actions.php" method="post" enctype="multipart/form-data" >
				<input type="hidden" name="action" value="<?php echo $act; ?>" />
				<input type="hidden" name="edit_id" id="edit_id" value="<?php echo $edit_id; ?>"  />
				<input type="hidden" name="hdn_pdt_sno" id="hdn_pdt_sno" value="<?php echo $disp_pdt_cnt; ?>" />
				
					<div class="card-box ">				
					<div class="row">
                    <div class="col-sm-2">
							<div class="form-group">
									<label>Financial Year<span class="text-danger">*</span></label>							
									<select onchange="get_bill_status()" name="financial_id" id="financial_id" class="form-control select2 jsrequired">
										<option value="">Select</option>
										<?php 
										$rslt_fy_list = $db->get_rsltset("select financial_id,f_start_date,f_end_date from m_financial_year order by f_start_date asc");
										$current_fy_id = '';
										if($act=='insert') {
											$current_fy_details = end($rslt_fy_list);
											$current_fy_id = $current_fy_details[0]['financial_id'];
										}
										foreach($rslt_fy_list as $r){
											$financial_year_label = date('Y',strtotime($r['f_start_date'])).'-'.date('Y',strtotime($r['f_end_date']));
											if($act=='update')
												$sel= ($res_ed['financial_id']==$r['financial_id'])?' selected="selected" ':'';
											else
												$sel= ($current_fy_id==$r['financial_id'])?' selected="selected" ':'';
										?>
										<option value="<?php echo $r['financial_id']; ?>" <?php echo $sel; ?>><?php echo $financial_year_label; ?></option>
										<?php	
										}
										?>
									</select>
								</div>
							</div>
							<div class="col-sm-4">
							<div class="form-group">
									<label>Select Company<span class="text-danger">*</span></label>							
									<select onchange="get_bill_status()" name="sel_company" id="sel_company" class="form-control select2 jsrequired" <?php echo $disabled ; ?>>
										<option value="">Select</option>
										<?php 
										$rslt_list = $db->get_rsltset("select company_id AS Id,company_name AS Name from m_company where IsActive = '1' order by company_name asc");
										foreach($rslt_list as $r){
											$sel='';
											if($res_ed['company_id']==$r['Id'])
												$sel=' selected="selected" ';
										?>
										<option value="<?php echo $r['Id']; ?>" <?php echo $sel; ?>><?php echo $r['Name']; ?></option>
										<?php	
										}
										?>
									</select>
								
								</div>	
								</div>	

                                <div class="col-sm-4">
                                <div class="form-group">
									<label>Select Customer<span class="text-danger">*</span></label>							
									<select onchange="get_customer_details(this.value);"  name="sel_customer" id="sel_customer" class="form-control select2 jsrequired" <?php echo $disabled ; ?>>
										<option value="">Select</option>
										<?php 
										$rslt_list = $db->get_rsltset("select m_customer.*, cus_id AS Id,cus_name AS Name from m_customer where IsActive = '1' order by cus_name asc");
										foreach($rslt_list as $r){
											$sel='';
											if($res_ed['cus_id']==$r['Id'])
												$sel=' selected="selected" ';
										?>
										<option value="<?php echo $r['Id']; ?>" <?php echo $sel; ?>><?php echo $r['Name']; ?></option>
										<?php	
										}
										?>
									</select>
									&nbsp;
								<div class="row" style="display:<?php echo $display; ?> ;">
									<div class="col-sm-4">
									<label>Gst: <span id="customer_gst_no" style="color:green; font-size:12px;"><?php echo $customer_details['cus_gstno'];   ?></span></label>
									</div>
									<div class="col-sm-8">
									<label>Address: <span id="customer_address" style="color:green; font-size:12px;"><?php echo $customer_details['cus_address'];   ?></span></label>
									</div>
									<div class="col-sm-4">
									<label>City: <span id="customer_city" style="color:green; font-size:12px;"><?php echo $customer_details['cus_city'];   ?></span></label>
									</div>
									<div class="col-sm-4">
									<label>State: <span id="customer_state" style="color:green; font-size:12px;"><?php echo $customer_details['cus_state'];   ?></span></label>
									</div>
									<div class="col-sm-3">
									<label>Pincode:<span id="customer_postcode" style="color:green; font-size:12px;"><?php echo $customer_details['cus_postcode'];   ?></span></label>
								    </div>
								    
								</div>
								</div>	
							</div>
                            <div class="col-sm-2">
                                <div class="form-group">
                                <label>Bill Status<span class="text-danger">*</span></label>		
                                <select onchange="get_bill_status(this.value);" name="bill_status" id="bill_status" class="form-control select2 jsrequired"<?php echo $disabled ; ?>>
										<option value="">Select</option>
										<option value="1">Pending</option>
										<option value="2" >Cleared</option>
                                        <option value="3">All</option>
										
									</select>
                                    &nbsp;
									<div class=" count" style="display:none ;">
									<div class="col-sm-4">
									<label>Pending: <span id="pendingCount" style="color:green; font-size:12px;"></span></label>
									</div>
									<div class="col-sm-4">
									<label>Cleared: <span id="clearedCount" style="color:green; font-size:12px;"></span></label>
									</div>
									</div>

                                </div>
                                </div>
							</div>
						</div>

<h5> Bill Details</h5>
					<div class="card-box ">		
						<div class="row">
							<div class="col-md-12">
								<div class="table-responsive challan-table">
									<table class="table table-bordered table-hover" id="tbl_payment_det">
										<thead>
									<tr>
                                    
                                    <th>
                                    <?php if ($operation !== "Edit"): ?>
                            <input type="checkbox" class="form-check-input chk_select_bill" id="chk_select_all" onclick="checkall();"  />
                                    <?php endif; ?>
                                    </th>
										<!-- <th>S.No</th> -->
                                        <th>Bill No</th>
                                        <th style="width:150px;">Bill Date</th>
                                        <th>Company Name</th>
                                        <th>Financial Year</th>
                                        <th>Total Amount</th>	
                                        <th>After Discount </th>	
                                        <th>GST / IGST</th>	
                                        <th>Bill Total</th>	
                                    <?php if ($operation !== "Edit"): ?>
                                        <th>Returned Total</th>	
                                    <?php endif; ?>
                                        <th>Paid Amount</th>
                                    <?php if ($operation !== "Edit"): ?>
                                        <th>Receivable Amount</th>	
                                        <th>Status</th>	
                                    <?php endif; ?>
									</tr>								
								</thead>	
								<tbody id="tbl_body_payment_det">	
                                    <?php 
                                    if($pdt_sv_cnt >0){
                                        $ai=0;
                                        foreach($rslt_pdt_list as $r){
                                            $ai = $ai+1;
                                            
                                        ?>	
                                    <input type="hidden" name="hdn_pay_cnt[]" value="<?php echo $ai; ?>" />

                                    <tr>
                                        
                                        <td></td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control " style="width:80px;"  value="<?php echo $r['s_bill_no']; ?>" readonly />
										</td>
                                        <td>
                                    <?php $formattedDate = date('d-m-Y', strtotime($r['s_bill_date']));  ?>
                                    <input type="text" style="border: 0px ;" class="form-control" style="width:100px;" value="<?php echo $formattedDate; ?>" readonly />
                                        </td>
                                        <td>
                                        <input type="" style="border: 0px ;" class="form-control "  value="<?php echo $r['company']; ?>"  />
										</td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['financial']; ?>" readonly />
										</td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['total_amount']; ?>" readonly />
                                        </td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['after_discount']; ?>" readonly />
                                        </td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['gst_amt']; ?>" readonly />
                                        </td>
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['bill_amount']; ?>" readonly />
                                        </td>
                                        <!-- <td>
                                        <input type="text" class="form-control "  value="<?php echo $r['return_amount']; ?>" readonly />
                                        </td> -->
                                        <td>
                                        <input type="text" style="border: 0px ;" class="form-control "  value="<?php echo $r['paid_amt']; ?>" readonly />
                                        </td>
                                        <!-- <td>
                                        <input type="text" class="form-control "  value="<?php echo $r['final_amount']; ?>" readonly />
                                        </td> -->
                                        
                                        <!-- <td><input type="" class="form-control badger bg-success"   style="width:90px; pointer-events:none; " value="Cleared" readonly /></td> -->
                                        

                                    <?php			
										}		
									}	
									else{	
									?>		
										<tr>
											<td colspan="10">No products found for this bill.</td>
										</tr>
									<?php		
									}
										?>	
								</tbody>				
								
							</table>
						</div>
								
					</div>
					</div>
					</div>
                        
<h5> Payment Details</h5>
                        <div class="card-box ">		
							<div class="row">
								<div class="col-sm-4">
								<div class="form-group">
									<label >Payment Type<span class="text-danger">*</span></label>
                                    <select  name="payment_type" id="payment_type" class="form-control select2 jsrequired">
										<option value="">Select</option>
                                        <?php
                                        $rslt_list =  $db->get_rsltset("SELECT payment_type_id AS Id, payment_type AS payment_type FROM status_payment_type");
                                    
										foreach($rslt_list as $r){
											$sel='';
											if($res_ed['payment_type']==$r['Id'])
												$sel=' selected="selected" ';
										?>
										<option value="<?php echo $r['Id']; ?>" <?php echo $sel; ?>><?php echo $r['payment_type']; ?></option>
										<?php	
										}
										?>
                                        
									</select>
								</div>	
								</div>	
                                <div class="col-sm-4">
                                <div class="form-group">
                                    <label >Txn Reference No<span class="text-danger">*</span></label>
                                    <input type="text" name="ref_no" id="ref_no" class="form-control jsrequired" value="<?php echo $res_ed['ref_no']; ?>">
                                </div>
                                </div>
                                <div class="col-sm-4">
                                <div class="form-group">
                                    <label >Payment Date<span class="text-danger">*</span></label>
                                    <input type="text" name="payment_date" id="payment_date" class="form-control jsrequired" value="<?php echo date('d-m-Y', strtotime($res_ed['payment_date'])); ?>">
                                </div>
                                </div>

							</div>	
                            <div class="row">
								<div class="col-sm-4">
                                <div class="form-group">
                                    <label >Bill Amount<span class="text-danger">*</span></label>
                                    <input type="number" name="bill_amount" id="bill_amount" min="0" class="form-control jsrequired" value="<?php echo $res_ed['bill_amount']; ?>" <?php echo $readonly ; ?>>
                                </div>
                                </div>
								<div class="col-sm-4">
                                <div class="form-group">
                                    <label >Received Amount<span class="text-danger">*</span></label>
                                    <input onchange="get_received_amount()" type="number" name="received_amount" id="received_amount" min="0" class="form-control jsrequired" value="<?php echo $res_ed['received_amount']; ?>" >
                                </div>
                                </div>
                                <div class="col-sm-4">
                                <div class="form-group">
                                    <label >Commission/Less<span class="text-danger">*</span></label>
                                    <input type="number" name="less_amount" id="less_amount" class="form-control jsrequired" value="<?php echo $res_ed['less_amount']; ?>" >
                                </div>
                                </div>
                            </div>
                            <div class="row">
                            <div class="col-sm-4">
                                <div class="form-group">
                                <label>Payment Status<span class="text-danger">*</span></label>		
                                <select name="payment_status" id="payment_status" class="form-control select2 jsrequired">
                                    <option value="">Select</option>
                                    <option value="1" <?php echo ($res_ed['payment_status'] == '1') ? 'selected' : ''; ?>>Pending</option>
                                    <option value="2" <?php echo ($res_ed['payment_status'] == '2') ? 'selected' : ''; ?>>Cleared</option>
                                </select>
                                </div>
                                </div>

								<div class="col-sm-8">
                                <div class="form-group">
                                    <label> Notes </label>
                                    <textarea name="notes" id="notes" class="form-control"><?php echo $res_ed['notes']; ?></textarea>
                                </div>
                                </div>
                            </div>
                            <div class="row">
							<div class="col-sm-8">&nbsp;</div>
					
							<div class="col-sm-4">						
								<div class="form-group">
									<div class="btn-group pull-right m-t-15">
										
										<button <?php if($act =='update') echo 'style="display:;"'; ?>  class="btn btn-primary waves-effect waves-light" type="submit" onClick="javascript:funSave_payment('frmPayment','payment_actions.php','jvalidate','payment','payment_mng.php');" ><span id="spSubmit"><?php echo $btn; ?> Details</span></button>

										

 										<!-- <button <?php if($act =='update') echo 'style="display:;"'; ?>  class="btn btn-primary waves-effect waves-light" type="submit"  ><span id="spSubmit"><?php echo $btn; ?> Details</span></button> -->
										
										<button class="btn btn-secondary waves-effect m-l-5" type="button" onClick="javascript:funCancel('frmReturn','jvalidate','payment','payment_mng.php');" >Cancel</button>													 
										
                                        <input type="hidden" id="overall_bill_id" name="overall_bill_id[]" >
											<input type="hidden" id="overall_bill_amt" name="overall_bill_amt[]" >
											<input type="hidden" id="overall_bill_date" name="overall_bill_date[]" >
                                            <input type="hidden" id="overall_bill_company" name="overall_bill_company[]" >
                                            <input type="hidden" id="overall_bill_fin_year" name="overall_bill_fin_year[]" >
                                            <input type="hidden" id="overall_bill_totalamt" name="overall_bill_totalamt[]" >
                                            <input type="hidden" id="overall_bill_aftDiscount" name="overall_bill_aftDiscount[]" >
                                            <input type="hidden" id="overall_bill_gst" name="overall_bill_gst[]" >
                                            <input type="hidden" id="overall_bill_finalamt" name="overall_bill_finalamt[]" >
                                            <input type="hidden" id="overall_bill_returnamt" name="overall_bill_returnamt[]" >
                                           

									</div>
								</div>						
							</div>
							
						</div>
						</div>	

					
                </div>
            </div> <!-- end row -->	
        </form>
			

<?php include "includes/footer.php";  ?> 
	 </div> <!-- container -->
</div> <!-- End wrapper -->

<?php include "includes/footer_script.php";  ?> 

<!-- Autocomplete -->
<script type="text/javascript" src="assets/plugins/autocomplete/jquery.autocomplete.min.js"></script>


<script type="text/javascript"> 

$(document).ready(function(){
    $(".select2").select2({
        width:'100%',
    });
    
});

$(function () {	
	var date = new Date();
	var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());		
	$('#payment_date').datepicker({	
		format: 'dd-mm-yyyy',
		startDate: '-100y',
		endDate: '+0d',
		autoclose: true,	
		assumeNearbyYear:20,	
		todayHighlight: true
		
	});	
	
	<?php if($act=="insert"){ ?> 
	$('#payment_date').datepicker('setDate', today);
	<?php } ?>
	
	// auto_complete_intialize(1);
	
	
		
});

var checklist = [];
var bill_no = "";
var bill_amt = "";
var bill_date = "";
var bill_company = "";
var bill_fin_year = "";
var bill_totalamt = "";
var bill_aftDiscount = "";
var bill_gst = "";
var bill_finalamt = "";
var bill_returnamt = "";

$('body').on('change','[singlecheckbox]',function(){
    if(event.target.checked){
        checklist.push({id : event.target.dataset.id, 
                        amount : event.target.dataset.amount,
                        date : event.target.dataset.date,
                        company : event.target.dataset.company,
                        fin_year : event.target.dataset.fin_year,
                        totalamt : event.target.dataset.totalamt,
                        aftDiscount : event.target.dataset.discount,
                        gst : event.target.dataset.gst,
                        finalamt : event.target.dataset.finalamt,
                        returnamt : event.target.dataset.returnamt

                    });
    }else{
        const index = checklist.findIndex(e => e.id === event.target.dataset.id);
        if(index !== -1){            
            checklist.splice(index, 1);
        }
    }
    let total = 0;
    checklist.forEach(e => total += parseFloat(e.amount));
    document.getElementById('bill_amount').value = total.toFixed(2);

    bill_no = checklist.map(e => e.id).join(",");
    bill_amt = checklist.map(e => e.amount).join(",");
    bill_date = checklist.map(e => e.date).join(",");
    bill_company = checklist.map(e => e.company).join(",");
    bill_fin_year = checklist.map(e => e.fin_year).join(",");
    bill_totalamt = checklist.map(e => e.totalamt).join(",");
    bill_aftDiscount = checklist.map(e => e.aftDiscount).join(",");
    bill_gst = checklist.map(e => e.gst).join(",");
    bill_finalamt = checklist.map(e => e.finalamt).join(",");
    bill_returnamt = checklist.map(e => e.returnamt).join(",");

    document.getElementById('overall_bill_id').value = bill_no;
    document.getElementById('overall_bill_amt').value = bill_amt;
    document.getElementById('overall_bill_date').value = bill_date;
    document.getElementById('overall_bill_company').value = bill_company;
    document.getElementById('overall_bill_fin_year').value = bill_fin_year;
    document.getElementById('overall_bill_totalamt').value = bill_totalamt;
    document.getElementById('overall_bill_aftDiscount').value = bill_aftDiscount;
    document.getElementById('overall_bill_gst').value = bill_gst;
    document.getElementById('overall_bill_finalamt').value = bill_finalamt;
    document.getElementById('overall_bill_returnamt').value = bill_returnamt;

    
});
function funSave_payment($frm,$urll,$acts,$stats,$lodlnk)
{
	if ($('#'+$acts).valid()) {
		if($('#txt_final_sale_amt').val() == '0'){
			swal("Warning!", "Your total amount should not be zero", "warning");	
			return false;
		}
		//check validate
		var chk_validate = check_validate();
		if(chk_validate == true){
			
			$("button").attr('disabled',true);
			
			var m_data = new FormData();
			var formdatas = $("#"+$acts).serializeArray();
			$.each( formdatas, function( key, value ) {
				 m_data.append( value.name, value.value);							 
			});
						

			$.ajax({
				url        : $urll,
				type	   : 'POST',
				dataType   : 'json',
				processData: false,
				contentType: false,
				data       : m_data,
				beforeSend: function() { loading(); },
				success: function(response){
					if(response.rslt == "1"){
						swal("Success!", "Sales details save successfully", "success");										
						$("#"+$acts)[0].reset();
						$(location).attr('href', $lodlnk);
						unloading();
					}
					else if(response.rslt == "2"){
						swal("Success!", "Sales details update successfully", "success");										
						$("#"+$acts)[0].reset();
						$(location).attr('href', $lodlnk);
						unloading();
					}
					else{
						swal("Failure!", "somehing missing try some time", "warning");
						unloading();
					}
					unloading();
					
					$("button").attr('disabled',false);
				}
			});	
			
		}
	}
}

function check_validate(){
	var rslt = true;
		
	return rslt;
}

function get_customer_details(cus_id){	
   
	if(cus_id !=''){	
		$.ajax({
			url: 'ajax_actions.php',
			type: 'POST',
			dataType : 'json',
			data: 'action=get_customer_det_by_cus_id&customer_id='+cus_id,
			beforeSend: loading(),
			success: function(response) {				
				if(response.rslt == "1"){		
					var customer_gst_no = response.customer_gst;			
					var cus_address = response.cus_address;
					var cus_city = response.cus_city;
					var cus_state = response.cus_state;
					var cus_postcode = response.cus_postcode;

					$("#customer_gst_no").text(customer_gst_no);	
					$("#customer_address").text(cus_address);	
					$("#customer_city").text(cus_city);	
					$("#customer_state").text(cus_state);	
					$("#customer_postcode").text(cus_postcode);	
					$(".row").show();
                }			
				unloading();
			}
		});   	
	}
    $('#chk_select_all').off('click');

    get_bill_status(1);
    $("#bill_status").val("1").trigger("change"); 

}



function get_bill_status(selectedValue) {

    document.getElementById('bill_amount').value = '0.00';
    checklist = [];

    // Get the selected Company and Customer values
    var financial_id = $('#financial_id').val();
    var selectedCompany = $('#sel_company').val();
    var selectedCustomer = $('#sel_customer').val();
    var selectedBillStatus = $('#bill_status').val();

    $.ajax({
        url: 'ajax_actions.php',
        type: 'POST',
        data: {
            action: 'get_bill_no_by_company_id_payment',
            company_id: selectedCompany,
            bill_status: selectedBillStatus,
            customer_id: selectedCustomer,
            financial_id: financial_id

        },
        dataType: 'json',
        success: function (responseData) {
            // Initialize or retrieve the DataTable
            var pendingCount = '0';
            var clearedCount = '0';

            responseData.forEach(function (row) {
                    var statusValue = parseInt(row.bill_status);
                    switch (statusValue) {
                        case 1:
                            pendingCount++;
                            break;
                        case 2:
                            clearedCount++;
                            break;
                        default:
                            unknownCount++;
                            break;
                    }
                });
                $("#pendingCount").text(pendingCount);
                $("#clearedCount").text(clearedCount);
                $(".count").show();

            var table = $('#tbl_payment_det').DataTable({
                "width" : '100%',
                // "drawCallback": function( settings ) {
                //     document.querySelectorAll('[name="chk_select_bill[]"]').forEach(e => { e.checked = document.getElementById("chk_select_all").checked })
                //     },
                "destroy": true, // Destroy existing DataTable if it exists
                "paging": true,   // Enable pagination
                "lengthChange": true, // Show 'Show entries' dropdown
                "searching": true,   // Enable searching
                "ordering": false,    // Enable sorting
                "info": true,        // Show information
                "autoWidth": true,   // Adjust column width automatically
                "data": responseData, // Provide the data
                "order" : [[2, 'desc']],
                "dom": '<"pull-right custom-padding"B><"pull-left custom-padding"f>rtip',
                    serverMethod: 'post',
                    buttons: 
                    [
                        {
                            extend: 'excel', 
                            filename: 'payment_listing' + new Date().toISOString().slice(0, 10),
                            text:      'Download <i class="fa fa-file-excel-o green-color"></i>',
                            exportOptions: {
                                                columns: [1,2,3,4,5,6,7,8,9,10,11,12] ,
                                                modifier: {
                                                    page: 'all',
                                                    },
                                            },
                                            
                            
                        },
                        
                    ],
                "columns": [
                    
                    // Define your table columns here
                    {
                        "data": null,
                        "render": function (data, type, row) {
                                // debugger
                            var isDisabled = row.bill_status === '2' ? 'disabled' : '';
                                // debugger
                                return `<input type="checkbox" class="form-check-input" 
                                ${(document.getElementById("chk_select_all").checked)?'checked':''}
                                 name="chk_select_bill[]" id ="chk_select_bill" class="chk_select_bill" singlecheckbox data-id="${row.s_bill_no }" data-amount="${row.bill_amount}"
                                 data-date="${row.billDate}" 
                                 data-company="${row.companyName}" 
                                 data-fin_year="${row.financial_year}" 
                                 data-totalamt="${row.tot_sale_amt}" 
                                 data-discount="${row.discount}" 
                                 data-gst="${row.tot_tax_amt}" 
                                 data-finalamt="${row.final_sale_amt}" 
                                 data-returnamt="${row.return_amt}"
                                 style="width: 20px; height: 20px;"
                                 
                                 value="${data.s_payment_id }" ${isDisabled } />`;
                            }
                    },
                    { "data": "s_bill_no" },
                    { "data": "billDate",
                        "render": function (data, type, row) {               
                            var dateParts = data.split('-');
                            if (dateParts.length === 3) {
                                var formattedDate = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
                                return '<span data-sort="' + dateParts[0] + '-' + dateParts[1] + '-' + dateParts[2] + '">' + formattedDate + '</span>';
                            } else {
                                return 'Invalid Date';
                            }
                        },
                        "type": "date-uk",
                    },
                    { "data": "companyName" },
                    { "data": "financial_year" },
                    // { "data": "customerName" },
                    // { "data": null }, 
                    { "data": "tot_sale_amt" },
                    { "data": "discount" },
                    { "data": "tot_tax_amt" },
                    { "data": "final_sale_amt" },
                    { "data": "return_amt" },
                    { "data": "paid_amt" },
                    { "data": "bill_amount" },
                    {
                        "data": "bill_status",
                        "render": function (data, type, row) {
                            var statusValue = parseInt(data);

                            // console.log('Status Data:', statusValue);
                         
                            switch (statusValue) {
                                case 1:
                                    return '<button class="btn btn-warning rounded-pill " style="pointer-events: none; background-color: #f0ad4e; border-color: #eea236; color: black;">Pending</button>';
                                case 2:
                                    return '<button class="btn btn-success rounded-pill" style="pointer-events: none; background-color: #5bc0de; border-color: #46b8da; color: black;">Cleared</button>';
                                default:
                                    return 'Unknown';
                            }
                        }
                       
                    }
                ]
            });
            checkall();
            

		// 	$(document).ready(function() {
			
        //     let table = $('#tbl_payment_det').DataTable( {
        //         columnDefs: [ {
        //             orderable: false,
        //             className: 'select-checkbox',
        //             targets:   0
        //         } ],
        //         select: {
        //             style:    'multi',
        //             selector: 'td:first-child'
        //         },
        //         order: [[ 1, 'asc' ]]
        //     });
            
        //     $('#tbl_payment_det').on('click', '#chk_select_all', function () {
        //         if ($('#chk_select_all:checked').val() === 'on')
        //             table.rows().select();
        //         else
        //             table.rows().deselect();
        //     });							
        // });

// $('#chk_select_all').on('change', function () {

//     $(".chk_select_bill").prop('checked', $(this).prop("checked"));

//     console.log('hi');
//         var isChecked = $(this).prop('checked');
//         // Select or deselect all checkboxes in the DataTable
//         table.rows().every(function () {
//             var row = this.node();
//             $(row).find('input[name="chk_select_bill[]"]').prop('checked', isChecked);
//         });
//         // calculateTotalBillAmount(); 
//     });
// $(document).ready(function () {
//    $('body').on('click', '#chk_select_all', function () {
//       if ($(this).hasClass('allChecked')) {
//          $('input[name="chk_select_bill[]"]', '#tbl_payment_det').prop('checked', false);
//       } else {
//        $('input[name="chk_select_bill[]"]', '#tbl_payment_det').prop('checked', true);
//        }
//        $(this).toggleClass('allChecked');
//      })
// });

// $('#received_amount').on('change', function() {
//         calculateTotalBillAmount();
//     });

// $('#tbl_payment_det').on('change', function () {
//     var selectedBillIds = [];
// 		var selectedBillAmt = [];
// 		var selectedBillDates = [];
//         var selectedBillCompany = [];
//         var selectedBillFinancialYear = [];
//         var selectedBilltotSaleAmt = [];
//         var selectedBilldiscountAmt = [];
//         var selectedBilltotTaxAmt = [];
//         var selectedBillfinalSaleAmt = [];
//         var selectedBillreturnAmt = [];
//         var selectedBillAmount = [];

//         $('#tbl_payment_det input[name="chk_select_bill[]"]:checked').each(function() {
//             var row = $(this).closest('tr');
//             var billAmount = parseFloat(row.find('td:eq(11)').text()); 
// 			var bill_id = row.find('td:eq(1)').text();
// 			var bill_date = row.find('td:eq(2)').text();
//             var billCompany = row.find('td:eq(3)').text();
//             var billFinancialYear = row.find('td:eq(4)').text();
//             var billtotAmt = row.find('td:eq(5)').text();
//             var billdiscountAmt = row.find('td:eq(6)').text();
//             var billtotTaxAmt = row.find('td:eq(7)').text();
//             var billfinalAmt = row.find('td:eq(8)').text();
//             var billreturnAmt = row.find('td:eq(9)').text();
           

//             selectedBillIds.push(bill_id);
//             selectedBillDates.push(bill_date);
//             selectedBillAmt.push(billAmount);
//             selectedBillCompany.push(billCompany);
//             selectedBillFinancialYear.push(billFinancialYear);
//             selectedBilltotSaleAmt.push(billtotAmt);
//             selectedBilldiscountAmt.push(billdiscountAmt);
//             selectedBilltotTaxAmt.push(billtotTaxAmt);
//             selectedBillfinalSaleAmt.push(billfinalAmt);
//             selectedBillreturnAmt.push(billreturnAmt);
            

//         });

        
//             if (selectedBillIds.length > 0) {
//         $('#overall_bill_id').val(selectedBillIds.join(','));
//         $('#overall_bill_date').val(selectedBillDates.join(','));
//         $('#overall_bill_amt').val(selectedBillAmt.join(','));
//         $('#overall_bill_company').val(selectedBillCompany.join(','));
//         $('#overall_bill_fin_year').val(selectedBillFinancialYear.join(','));
//         $('#overall_bill_totalamt').val(selectedBilltotSaleAmt.join(','));
//         $('#overall_bill_aftDiscount').val(selectedBilldiscountAmt.join(','));
//         $('#overall_bill_gst').val(selectedBilltotTaxAmt.join(','));
//         $('#overall_bill_finalamt').val(selectedBillfinalSaleAmt.join(','));
//         $('#overall_bill_returnamt').val(selectedBillreturnAmt.join(','));
//     } else {
       
//         $('#overall_bill_id').val('');
//         $('#overall_bill_date').val('');
//         $('#overall_bill_amt').val('');
//     }

//     // calculateTotalBillAmount(); 
// });


// function calculateTotalBillAmount() {
//     var totalAmount = 0;

//     // Iterate through checked checkboxes
//     $('input[name="chk_select_bill[]"]:checked').each(function () {

//         var row = table.row($(this).closest('tr')).data();
//         totalAmount += parseFloat(row.bill_amount);
        
//     });

//     // Update the total amount input field
//     $('#bill_amount').val(totalAmount.toFixed(2)); // Format the total amount as needed
// }
// Add an event listener to the "received amount" input field
$('#received_amount').on('input', function () {
    var receivedAmount = parseFloat($(this).val());
    var billAmount = parseFloat($('#bill_amount').val());

    if (!isNaN(receivedAmount) && !isNaN(billAmount)) {
        var FinalAmount =  receivedAmount - billAmount ;
       var lessAmount = Math.abs(FinalAmount, 0);

        $('#less_amount').val(lessAmount.toFixed(2)); // Format the less amount as needed
    }
});

            // Handle the case where no data is returned.
            if (responseData.length === 0) {
                table.clear().draw(); // Clear the existing data
                // $('#tbl_payment_det').append('<tr><td colspan="10">No data found.</td></tr>');
            }

        },
        error: function (error) {
            console.error(error);
            // Handle error
        }
    });
}

function checkall() {
    // console.log('asdsad');
    // console.log(this.data());
    var isChecked = $('#chk_select_all').prop('checked');
    $('#tbl_payment_det').DataTable().rows().every(function() {
        var data = this.data();
        console.log(this.data());
        var id = data.s_bill_no;
        var amount = data.bill_amount;
        var date = data.billDate;
        var company = data.companyName;
        var fin_year = data.financial_year;
        var totalamt = data.tot_sale_amt;
        var aftDiscount = data.discount;
        var gst = data.tot_tax_amt;
        var finalamt = data.final_sale_amt;
        var returnamt = data.return_amt;
        console.log(id, amount, date, company, fin_year, totalamt, aftDiscount, gst, finalamt, returnamt);

        if (isChecked) {
            checklist.push({
                id: id,
                amount: amount,
                date: date,
                company: company,
                fin_year: fin_year,
                totalamt: totalamt,
                aftDiscount: aftDiscount,
                gst: gst,
                finalamt: finalamt,
                returnamt: returnamt
            });
        } else {
            var index = checklist.findIndex(function(e) {
                return e.id === id;
            });
            if (index !== -1) {
                checklist.splice(index, 1);
            }
        }
    });

    var total = 0;
    checklist.forEach(function(e) {
        total += parseFloat(e.amount);
    });
    $('#bill_amount').val(total.toFixed(2));

    bill_no = checklist.map(function(e) {
        return e.id;
    }).join(",");
    bill_amt = checklist.map(function(e) {
        return e.amount;
    }).join(",");
    bill_date = checklist.map(function(e) {
        return e.date;
    }).join(",");
    bill_company = checklist.map(function(e) {
        return e.company;
    }).join(",");
    bill_fin_year = checklist.map(function(e) {
        return e.fin_year;
    }).join(",");
    bill_totalamt = checklist.map(function(e) {
        return e.totalamt;
    }).join(",");
    bill_aftDiscount = checklist.map(function(e) {
        return e.aftDiscount;
    }).join(",");
    bill_gst = checklist.map(function(e) {
        return e.gst;
    }).join(",");
    bill_finalamt = checklist.map(function(e) {
        return e.finalamt;
    }).join(",");
    bill_returnamt = checklist.map(function(e) {
        return e.returnamt;
    }).join(",");

    $('#overall_bill_id').val(bill_no);
    $('#overall_bill_amt').val(bill_amt);
    $('#overall_bill_date').val(bill_date);
    $('#overall_bill_company').val(bill_company);
    $('#overall_bill_fin_year').val(bill_fin_year);
    $('#overall_bill_totalamt').val(bill_totalamt);
    $('#overall_bill_aftDiscount').val(bill_aftDiscount);
    $('#overall_bill_gst').val(bill_gst);
    $('#overall_bill_finalamt').val(bill_finalamt);
    $('#overall_bill_returnamt').val(bill_returnamt);

    
}
console.log(date);



</script>
<script>
function get_received_amount() {
    var receivedAmount = parseFloat($('#received_amount').val());
    var billAmount = parseFloat($('#bill_amount').val());
    if (!isNaN(receivedAmount) && !isNaN(billAmount)) {
        var FinalAmount =  receivedAmount - billAmount ;
       var lessAmount = Math.abs(FinalAmount, 0);
        $('#less_amount').val(lessAmount.toFixed(2)); 
    }
}
</script>


</body>
</html>
	  