<?php 

include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdme_Purchase_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 Supplier<span class="text-danger">*</span></label>							
									<select onchange="get_supplier_details(this.value);"  name="sel_supplier" id="sel_supplier" class="form-control select2 jsrequired" <?php echo $disabled ; ?>>
										<option value="">Select</option>
										<?php 
										$rslt_list = $db->get_rsltset("select m_supplier.*, sup_id AS Id,sup_name AS Name from m_supplier where IsActive = '1' order by sup_name asc");
										foreach($rslt_list as $r){
											$sel='';
											if($res_ed['sup_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="supplier_gst_no" style="color:green; font-size:12px;"><?php echo $supplier_details['sup_gstno'];   ?></span></label>
									</div>
									<div class="col-sm-8">
									<label>Address: <span id="supplier_address" style="color:green; font-size:12px;"><?php echo $supplier_details['sup_address'];   ?></span></label>
									</div>
									<div class="col-sm-4">
									<label>City: <span id="supplier_city" style="color:green; font-size:12px;"><?php echo $supplier_details['sup_city'];   ?></span></label>
									</div>
									<div class="col-sm-4">
									<label>State: <span id="supplier_state" style="color:green; font-size:12px;"><?php echo $supplier_details['sup_state'];   ?></span></label>
									</div>
									<div class="col-sm-3">
									<label>Pincode:<span id="supplier_postcode" style="color:green; font-size:12px;"><?php echo $supplier_details['sup_postcode'];   ?></span></label>
									<span id="supplier_product" style="color:green; font-size:12px; display:;"><?php echo $supplier_details['sup_product'];   ?></span>
								    </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  <span id="bill_type" style=" font-size:18px; display:none;"></span></h5>
<!-- ----------------------------------------------raw Product --------------------------------------------->
<!-- ----------------------------------------------raw Product --------------------------------------------->
					<div class="card-box "  id ="raw_product" style= "display:;">		
						<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_1">
										<thead>
									<tr>
                                    
                                    <th>
                                    <?php if ($operation !== "Edit"): ?>
                            <input type="checkbox" class="form-check-input chk_select_bill" id="chk_select_all_1" onclick="checkall();"  />
                                    <?php endif; ?>
                                    </th>
										<!-- <th>S.No</th> -->
                                        <th>Bill No</th>
                                        <th style="width:150px;">Bill Date</th>
                                        <th>Supplier 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>
    <!-- ----------------------------------------------finished Product --------------------------------------------->
    <!-- ----------------------------------------------finished Product --------------------------------------------->
                    <div class="card-box"  id ="finished_product" style= "display:;">		
                    <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_2">
                        <thead>
									<tr>
										<th>
                                            <input type="checkbox" class="form-check-input chk_select_bill" id="chk_select_all" onclick="checkall_2();"  />
                                        </th>
                                        <!-- <th>Bill No</th> -->
                                        <!-- <th style="width:150px;">Bill Date</th> -->
                                        <th>Financial Year</th>
                                        <th>Company Name</th>
                                        <th>Supplier Name</th>
                                        <th>Total Amount</th>	
                                        <th>After Discount</th>
                                        <!-- <th>After Discount </th>	 -->
                                        <th>GST / IGST</th>	
                                        <th>Return Amount</th>	
                                        <th>Final Amount</th>	
                                    
									</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>
                                
<!-- ----------------------------------------------end finished Product --------------------------------------------->

<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','purchase_payment_actions.php','jvalidate','payment','purchase_payment_mng.php');" ><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','purchase_payment_mng.php');" >Cancel</button>													 
										
                                        <input type="" id="overall_bill_id" name="overall_bill_id[]" >
											<input type="" id="overall_bill_amt" name="overall_bill_amt[]" >
											<input type="" id="overall_bill_date" name="overall_bill_date[]" >
                                            <input type="" id="overall_bill_company" name="overall_bill_company[]" >
                                            <input type="" id="overall_bill_supplier" name="overall_bill_supplier[]" >
                                            <input type="" id="overall_bill_fin_year" name="overall_bill_fin_year[]" >
                                            <input type="" id="overall_bill_totalamt" name="overall_bill_totalamt[]" >
                                            <input type="" id="overall_bill_aftDiscount" name="overall_bill_aftDiscount[]" >
                                            <input type="" id="overall_bill_gst" name="overall_bill_gst[]" >
                                            <input type="" id="overall_bill_finalamt" name="overall_bill_finalamt[]" >
                                            <input type="" 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%',
    });
    $("#raw_product").hide();
        // $("#finished_product").hide();
});

$(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_supplier = "";
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,
                        supplier : event.target.dataset.supplier,
                        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_supplier = checklist.map(e => e.supplier).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_supplier').value = bill_supplier;
    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_supplier_details(sup_id) {   
    if(sup_id != '') {   
        $.ajax({
            url: 'ajax_actions.php',
            type: 'POST',
            dataType: 'json',
            data: 'action=get_supplier_det_by_sup_id&supplier_id=' + sup_id,
            beforeSend: loading(),
            success: function(response) {               
                if(response.rslt == "1") {       
                    var supplier_gst_no = response.supplier_gst;         
                    var sup_address = response.sup_address;
                    var sup_city = response.sup_city;
                    var sup_state = response.sup_state;
                    var sup_postcode = response.sup_postcode;
                    var sup_product = response.sup_product;

                    $("#supplier_gst_no").text(supplier_gst_no);   
                    $("#supplier_address").text(sup_address);   
                    $("#supplier_city").text(sup_city);   
                    $("#supplier_state").text(sup_state);   
                    $("#supplier_postcode").text(sup_postcode);   
                    $("#supplier_product").text(sup_product);   
                    $(".row").show();

                    // Call the bill_details function passing sup_product value
                    bill_details(sup_product);
                }           
                unloading();
            }
        });    
    }
    $('#chk_select_all').off('click');

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

function bill_details(sup_product) {
    if(sup_product == 2) {
        $("#finished_product").show();
        $("#raw_product").hide();
        $("#bill_type").text("Finished Product").show();
    } 
    else if(sup_product == 1) {
        $("#raw_product").show();
        $("#finished_product").hide();
        $("#bill_type").text("Raw Materials").show();
    }
    else {
        $("#raw_product").hide();
        $("#finished_product").hide();
    }
    
}


function get_bill_status(selectedValue) {

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

    // Get the selected Company and supplier values
    var financial_id = $('#financial_id').val();
    var selectedsupplier = $('#sel_supplier').val();


console.log(financial_id,selectedsupplier);
    $.ajax({
        url: 'ajax_actions.php',
        type: 'POST',
        data: {
            action: 'get_purchase_payment',
            supplier_id: selectedsupplier,
            financial_id: financial_id

        },
        dataType: 'json',
        success: function (responseData) {
            if (responseData.length === 0) {
        if ($.fn.DataTable.isDataTable('#tbl_payment_det_1')) {
            $('#tbl_payment_det_1').DataTable().clear().draw(); 
        }
        if ($.fn.DataTable.isDataTable('#tbl_payment_det_2')) {
            $('#tbl_payment_det_2').DataTable().clear().draw(); 
        }
    }
            var product_type = responseData[0].product_type;
            console.log(product_type);
            

    if (product_type === '1') {
            var table_1 = $('#tbl_payment_det_1').DataTable({
                "width" : '100%',
                "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: 'ss_silks_purchase_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) {
                                
                                return `<input type="checkbox" class="form-check-input" 
                                ${(document.getElementById("chk_select_all_1").checked)?'checked':''}
                                 name="chk_select_bill[]" id ="chk_select_bill" class="chk_select_bill" singlecheckbox data-id="${row.p_invoice_no }" data-amount="${row.bill_amount}"
                                 data-date="${row.billDate}" 
                               
                                 data-fin_year="${row.financial_year}" 
                                 data-totalamt="${row.tot_pur_amt}" 
                                 data-discount="${row.discount}" 
                                 data-gst="${row.tot_tax_amt}" 
                                 data-finalamt="${row.final_pur_amt}" 
                                 data-returnamt="${row.return_amt}"
                                 style="width: 20px; height: 20px;"
                                 
                                  />`;
                            }
                    },
                    { "data": "p_invoice_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": "supplierName" },
                    { "data": "financial_year" },
                    { "data": "tot_pur_amt" },
                    { "data": "discount" },
                    { "data": "tot_tax_amt" },
                    { "data": "final_pur_amt" },
                   
                ]
            });
            checkall();
        
} 
else if (product_type === '2') {
            var table_2 = $('#tbl_payment_det_2').DataTable({
                "width" : '100%',
                "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: 'ss_silks_purchase_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) {
                                
                                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.company_id }" 
                                 data-amount="${row.final_pur_amt}"
                                
                               
                                 data-fin_year="${row.financial_year}" 
                                 data-totalamt="${row.tot_pur_amt}" 
                                 data-discount="${row.discount}" 
                                 data-gst="${row.tot_tax_amt}" 
                                 data-finalamt="${row.final_pur_amt}" 
                                 data-returnamt="${row.return_amt}"
                                 style="width: 20px; height: 20px;"
                                 
                                  />`;
                            }
                    },
                    { "data": "financial_year" },
                    { "data": "company_name" },
                    { "data": "supplierName" },
                    { "data": "tot_pur_amt" },
                    { "data": "discount" },
                    { "data": "tot_tax_amt" },
                    { "data": "return_amt" },
                    { "data": "final_pur_amt" },
                   
                ]
            });
            checkall();

            
}


$('#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_1.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_1').prop('checked');
    $('#tbl_payment_det_1').DataTable().rows().every(function() {
        var data = this.data();
        console.log(this.data());
        var id = data.p_invoice_no;
        var amount = data.bill_amount;
        var date = data.billDate;
        var company = data.company_name;
        var supplier = data.supplierName;
        var fin_year = data.financial_year;
        var totalamt = data.tot_pur_amt;
        var aftDiscount = data.discount;
        var gst = data.tot_tax_amt;
        var finalamt = data.final_pur_amt;
        var returnamt = data.return_amt;
        console.log(id, amount, date, company,supplier, fin_year, totalamt, aftDiscount, gst, finalamt, returnamt);

        if (isChecked) {
            checklist.push({
                id: id,
                amount: amount,
                date: date,
                company: company,
                supplier: supplier,
                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_supplier = checklist.map(function(e) {
        return e.supplier;
    }).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_supplier').val(bill_supplier);
    $('#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);

   
}


</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>
	  