<?php 

include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdme_purchasereturn($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_pur_return_entry_main where IsActive != '2' and r_bill_no = '".base64_decode($id)."' ";
$pdt_ed = "select * from t_pur_return_entry_details where IsActive != '2' and r_bill_no = '".base64_decode($id)."' ";

$res_ed = $db->get_a_line($str_ed);
$return_ed = $db->get_results($pdt_ed);

$edit_id = $res_ed['r_bill_no'];
$disp_inv_no = $res_ed['actu_pur_bill_no'];
$financial_id = $res_ed['financial_id'];
$company_id = $res_ed['company_id'];
$notes = $res_ed['notes'];
$rtn_id = $return_ed['r_bill_no'];

// $purchase_ed = "select * from t_purchase_entry_main where IsActive != '2' and actu_bill_no = '".$disp_inv_no."' and financial_id ='".$financial_id."' and company_id = '".$company_id."' ";
// $sal_ed = $db->get_a_line($purchase_ed);
// $purchase_ed_id = $sal_ed['s_bill_no'];

// $purchase_det_ed = "select * from t_purchase_entry_details where IsActive != '2' and s_bill_no = '".$purchase_ed_id."' ";
// $sal_det_ed = $db->get_a_line($purchase_det_ed);
// $purchase_detail_id = $sal_det_ed['s_bill_no'];

/*
$rslt_pdt_list = $db->get_rsltset("select t1.*,t2.upload_img from t_purchase_entry_details t1 inner join t_purchase_entry_details t2 on t1.pdt_sku=t2.pdt_sku where 1=1 and t1.IsActive=1 and t1.s_bill_no='".$res_ed['s_bill_no']."' "); */

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

$purchase_checked = $rslt_pdt_list['pdt_sku'];

$rslt_pdt_list_selected = $db->get_rsltset("select t1.*,'' as upload_img from t_return_entry_details t1 where 1=1 and t1.IsActive=1 and t1.s_bill_no='".$res_ed['actu_bill_no']."'    ");


$pdt_sv_cnt = count($rslt_pdt_list);

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

$pdt_sv_cnt_selected = count($rslt_pdt_list_selected);
$disp_pdt_cnt_selected=1;
if($pdt_sv_cnt_selected >0){
	$disp_pdt_cnt_selected =$pdt_sv_cnt_selected;
}

$disp_over_all_tot=0;
if(isset($res_ed['total_amount']) && !empty($res_ed['total_amount'])){
	$disp_over_all_tot=$res_ed['total_amount'];
}



$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;
}

$discount_type_html='<option value="">Select</option> <option value="1">%</option> <option value="2">Flat</option>';
?>  

<div class="wrapper">
    <div class="container">        
		<!-- Page-Title - START -->
        <div class="row">
            <div class="col-sm-5">										
                <h4 class="page-title"><?php echo $operation; ?> Purchase Return Entry</h4>						
            </div>
        </div>
		<!-- Page-Title - END -->	
									<?php
										$readonly = ($operation === "Edit") ? 'readonly' : ''; 
										?>	
		<div class="row">
			<div class="col-sm-12">
				<form id="jvalidate" name="frmReturn" role="form" class="form-horizontal" action="purchase_return_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; ?>" />
				<input type="hidden" name="hdn_pdt_sno_selected" id="hdn_pdt_sno_selected" value="<?php echo $disp_pdt_cnt_selected; ?>" />
				
					<div class="card-box ">				
					<div class="row">
							<div class="col-sm-4">
							<div class="form-group">
									<label>Financial Year<span class="text-danger">*</span></label>							
									<select onchange="get_bill_no_by_cmpny_id_return($('#sel_company').val());" 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_no_by_cmpny_id_return(this.value);" name="sel_company" id="sel_company" class="form-control select2 jsrequired">
										<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>
									<input type="hidden" name="company_name" id="company_name" value =""  />
								</div>	
							</div>
							
							<div class="col-sm-2">
							<div class="form-group">
									<label>Invoice No</label>	
									<input type="number" class="form-control jsrequired" min="1" name="txt_bill_no" id="txt_bill_no" required  value="<?php echo $disp_inv_no; ?>" <?php echo $readonly ; ?> />
							</div>	
							</div>

							<div class="col-sm-2">
							<div class="form-group">
									<label>Debit Note</label>	
									<input type="text" class="form-control jsrequired"  name="p_invoice_id" id="p_invoice_id"   value="<?php echo $res_ed['p_invoice_id']; ?>"  readonly />
							</div>
							</div>
							</div>

							<div class="row">
								<div class="col-sm-4">
								<div class="form-group">
										<label>Invoice Date</label>	
										<?php
											$billDateValue = (!empty($disp_inv_no)) ? date('d-m-Y', strtotime($res_ed['p_bill_date'])) : '';
											?>						
										<input type="text" class="form-control jsrequired" name="txt_bill_date" id="txt_bill_date" readonly value="<?php echo $billDateValue ;?>" />

								</div>
								</div>
								
								<div class="col-sm-4">
								<div class="form-group">
									<label> Supplier Name</label>	
									<?php 
										$rslt_list = $db->get_rsltset("select * from m_supplier where sup_id='".$res_ed['sup_id']."'  ");
										
										
										?>						
									<input type="text" class="form-control jsrequired" name="txt_supplier" id="txt_supplier"  readonly value="<?php echo $rslt_list[0]['sup_name']; ?>"  />
									<input type="hidden" class="form-control jsrequired" name="txt_supplier_id" id="txt_supplier_id"  readonly value="<?php echo $rslt_list[0]['sup_id']; ?>"  />
								</div>
								</div>

								<div class="col-sm-4">
								<div class="form-group">
									<label> Supplier City</label>							
									<input type="text" class="form-control jsrequired" name="txt_supplier_city" id="txt_supplier_city"  readonly value="<?php echo $rslt_list[0]['sup_city']; ?>"  />
								</div>
								</div>
							</div>

							<div class="row">
								<div class="col-sm-4">
								<div class="form-group">
									<label> Supplier State</label>							
									<input type="text" class="form-control jsrequired" name="txt_supplier_state" id="txt_supplier_state"  readonly value="<?php echo $rslt_list[0]['sup_state']; ?>"  />
								</div>
								</div>
								
								<div class="col-sm-4">
								<div class="form-group">
									<label> Supplier GST</label>							
									<input type="text" class="form-control " name="txt_supplier_gst" id="txt_supplier_gst"  readonly value="<?php echo $rslt_list[0]['sup_gstno']; ?>"  />
								</div>
								</div>

								<div class="col-sm-4">
								<div class="form-group">
									<label> Pincode</label>							
									<input type="text" class="form-control jsrequired" name="txt_supplier_pin" id="txt_supplier_pin"  readonly value="<?php echo $rslt_list[0]['sup_postcode']; ?>"  />
								</div>
								</div>
								</div>

								<div class="row">
									
								<div class="col-sm-4">
							
								<div class="form-group">
									<label>Notes</label>							
									<input type="text" class="form-control" name="txt_notes" id="txt_notes"  readonly value="<?php echo $res_ed['notes']; ?>"  /> 
									
								</div>	
								</div>	

								<div class="col-sm-4">
								<div class="form-group">
								<label>Credit Notes</label>	
									<input type="text" class="form-control" name="txt_return_notes" id="txt_return_notes" value="<?php echo $res_ed['credit_notes']; ?>" />
								</div>
								</div>

							<div class="col-sm-4">
							
							<div class="form-group">
									<label>Return Date</label>							
									<input type="text" class="form-control jsrequired" name="txt_return_date" id="txt_return_date"  value="<?php echo date('d-m-Y', strtotime($res_ed['return_date'])); ?>" />
								</div>
								
								</div>
								</div>

								<div class="row">
								<div class="col-sm-12">
								<div class="form-group">
									<label>Comments </label>							
									<textarea rows="2" class="form-control" name="txt_comments" id="txt_comments" ><?php echo $res_ed['comments']; ?> </textarea>
									
								</div>	
								</div>	
								</div>	
								
						<br/>
						
						<div class="row">
							<div class="col-md-12">
								<div class="table-responsive challan-table">
									<table class="table table-bordered table-hover" id="tbl_item_det">
										<thead>
									<tr>
									<th></th>
										<th width="10%">Product SKU</th>
										<th width="30%">Product Details</th>												
										<th width="10%">Image</th>
										<th width="10%">Purchase Rate</th>
										<th width="5%">Discount (%)</th>
										<th width="5%">Discount (AMT)</th>
										<th width="15%">Amount Rs.</th>												
										<th width="10%">Status</th>												
											
									</tr>								
								</thead>	
								<tbody id="tbl_body_return_det">	
							<?php 
								if($pdt_sv_cnt >0){
									$ai=0;
									foreach($rslt_pdt_list as $r){
										$ai = $ai+1;
										$pdt_prev_img='NoImageAvailable.png';
										// $isChecked = in_array($r['pdt_sku'], array_column($return_ed, 'pdt_sku'));

										
										if (!empty($r['upload_img']) && ($act == 'update')) { 
											if(file_exists(CAAROOT_DIR."/uploads/product_image/".$r['upload_img']))
											{
												$pdt_prev_img = $r['upload_img'];	
											}											
										}	
									?>	
									
									<tr id="dy_rw_<?php echo $ai; ?>">
										<input type="hidden" name="hdn_pdt_cnt[]" value="<?php echo $ai; ?>" />
										<input type="hidden" name="hdn_prev_sv_id[]"  value="<?php echo $r['r_bill_det_id']; ?>"  />								
										<td>
										<!-- <input type="checkbox" class="form-check-input" name="chk_select_product[]" id="chk_select_product" <?php echo $isChecked ? 'checked' : ''; ?> /> -->
               							</td>

										<td>
											<input type="text" style="border: 0px ;" class="form-control pdtskucls autocmplte_pdtsku" name="txt_pdt_sku[]" id="txt_pdt_sku_<?php echo $ai; ?>"  style="width:100px;"  value="<?php echo $r['pdt_sku']; ?>" readonly />
										</td>
										
										<td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_<?php echo $ai; ?>" readonly    value="<?php echo $r['saree_desc']; ?>" />
										</td>
										<td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_pdt_img[]" id="txt_pdt_img_<?php echo $ai; ?>" readonly  style="width:100px;"  value="<?php echo $r['pdt_img']; ?>" />
										</td>
										<td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_<?php echo $ai; ?>" readonly  style="width:100px;"  value="<?php echo $r['purchase_price']; ?>" />
										</td>
										<!-- <td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_sale_price[]" id="txt_sale_price_<?php echo $ai; ?>"  onKeyPress="return isNumberKey(event,this)" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);"  style="width:100px;"  value="<?php echo $r['sale_price']; ?>" readonly/>
										</td> -->
										<td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_pdt_discount_per[]" id="txt_pdt_discount_per_<?php echo $ai; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" value="<?php echo $r['pdt_discount_percent']; ?>" readonly/>
									</td>
									<td>
											<input readonly type="text" style="border: 0px ;" class="form-control" name="txt_pdt_discount_amt[]" id="txt_pdt_discount_amt_<?php echo $ai; ?>" value="<?php echo $r['pdt_discount_amt']; ?>"  />
										</td>
										<td>
											<input type="text" style="border: 0px ;" class="form-control" name="txt_tot_amt[]" id="txt_tot_amt_<?php echo $ai; ?>" readonly  style="width:100px;"  value="<?php echo $r['tot_amount']; ?>"  />
										</td>
										<td><h5><input type="" class="form-control badger bg-success"  style="width:100px;" value="Returned" readonly /></h5></td>
											<?php
											// if ($r['status']== 2)
											// {
											// 	echo '';
											// }
											// else {
											// 	echo '<td><input type="text" class="form-control"  style="width:100px;"  value="Sold" readonly /></td>';
											// }
											?>
										
									</tr>	
									
									<?php			
										}		
									}	
									else{	
									?>		
										<tr>
											<td colspan="13">No products found for this bill.</td>
										</tr>
									<?php		
									}
										?>						
								</tbody>				
								
							</table>
						</div>
								
						
						<br/>
						<div class="row">
							<div class="col-sm-10">&nbsp;</div>
							
						</div>
						<br/>
						
						
						<div class="row">
							<div class="col-md-12">
								<div class="table-responsive challan-table">
									<table class="table table-bordered table-hover">
										<thead>
											<tr>
												<th width="20%"></th>
												<th width="30%"></th>
												<th width="20%"></th>
												<th width="20%"></th>
											</tr>
										</thead>										
										<tfoot>											
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>Amount</td>
												<td>
													<input readonly type="text" class="form-control" name="txt_tot_pur_amt" id="txt_tot_pur_amt" value="<?php echo $res_ed['tot_pur_amount']; ?>" />
												</td>
											</tr>
																					
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>Discount %</td>
												<td>		
													<input type="number" min=0 class="form-control" name="overall_discount_per" id="overall_discount_per" value="<?php echo $res_ed['discount_per']; ?>" />
												</td>
											</tr>										
																				
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>Discount Amount</td>
												<td>		
													<input  type="text" class="form-control" name="overall_discount_amt" id="overall_discount_amt"  readonly value="<?php echo $res_ed['after_discount_amt']; ?>" />
												</td>
											</tr>	
											<input  type="hidden" class="form-control" name="overall_total_amt" id="overall_total_amt" readonly />

											<!-- <tr>
												<td colspan="2">&nbsp;</td>
												<td>Total Amount</td>
												<td>		
												</td>
											</tr> -->
														
													
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>CGST (%)</td>
												<td>		
													<div class="input-group mb-3">
														<div class="input-group-prepend"></div>
													<input type="text" class="form-control" name="txt_cgst" id="txt_cgst" value="<?php echo $res_ed['cgst_per']; ?>" />
													<input type="text" class="form-control" name="txt_cgst_total" id="txt_cgst_total"  readonly value="<?php echo $res_ed['cgst_total']; ?>" />
													</div>
												</td>
											</tr>
											
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>SGST (%)</td>
												<td>		
													<div class="input-group mb-3">
														<div class="input-group-prepend"></div>
													<input  type="text" class="form-control" name="txt_sgst" id="txt_sgst"  value="<?php echo $res_ed['sgst_per']; ?>" /> 
													<input type="text" class="form-control" name="txt_sgst_total" id="txt_sgst_total"   readonly value="<?php echo $res_ed['sgst_total']; ?>" />
													</div>
												</td>												

											</tr>
											
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>IGST (%)</td>
												<td>		
													<div class="input-group mb-3">
														<div class="input-group-prepend"></div>
													<input  type="text" class="form-control" name="txt_igst" id="txt_igst"  value="<?php echo $res_ed['igst_per']; ?>" />
													<input type="text" class="form-control" name="txt_igst_total" id="txt_igst_total"   readonly value="<?php echo $res_ed['igst_total']; ?>" />
													</div>
												</td>
											</tr>
											
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>Tax Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_tax_amt" id="txt_tax_amt" value="<?php echo $res_ed['tot_tax_amt']; ?>" />
												</td>
											</tr>
											
											<tr>
												<td colspan="2">&nbsp;</td>
												<td>Final Invoice Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_final_pur_amt" id="txt_final_pur_amt" value="<?php echo $res_ed['final_pur_amt']; ?>" />
												</td>
											</tr>
											
										</tfoot>
									</table>						
									
								</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_return('frmReturn','purchase_return_actions.php','jvalidate','return','purchase_return_mng.php');" ><span id="spSubmit"><?php echo $btn; ?> Details</span></button>

										<input type="hidden" id="overall_product_id" name="overall_product_id[]" >
											<input type="hidden" id="overall_product_desc" name="overall_product_desc[]" >
											<input type="hidden" id="overall_product_purchase" name="overall_product_purchase[]" >
											<input type="hidden" id="overall_product_discount" name="overall_product_discount[]" >
											<input type="hidden" id="overall_product_discount_amt" name="overall_product_discount_amt[]" >
											<input type="hidden" id="overall_product_tot_amt" name="overall_product_tot_amt[]" >

 										<!-- <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','return','purchase_return_mng.php');" >Cancel</button>													 
										<input type="hidden" id="hdn_price" name="hdn_price"  value="<?php echo $res_ed['final_sale_amt']; ?>" />
									</div>
								</div>						
							</div>
							
						</div>
										
						
					</div>
					
				</form>
            </div>
        </div> <!-- end row -->	
			

<?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());		
	$('#txt_return_date').datepicker({	
		format: 'dd-mm-yyyy',
		startDate: '-100y',
		endDate: '+0d',
		autoclose: true,	
		assumeNearbyYear:20,	
		todayHighlight: true
		
	});	
	
	<?php if($act=="insert"){ ?> 
	$('#txt_return_date').datepicker('setDate', today);
	<?php } ?>
	
	// auto_complete_intialize(1);
	
	
		
});



function get_bill_no_by_cmpny_id_return(cmpny_id){
		var financial_id =  $('#financial_id').val();
		console.log(cmpny_id);
	if(cmpny_id !=''){					
		$.ajax({		
			url        : 'ajax_actions.php',
			method     : 'POST',
			dataType   : 'json',
			data       : 'action=get_purchase_id_return&company_id='+cmpny_id+'&financial_id='+financial_id,
			beforeSend: function() { loading(); },
			success: function(response){
				$("#p_invoice_id").val(response.rslt);
				unloading();
			}		
		});
	}
}

function funSave_return($frm,$urll,$acts,$stats,$lodlnk)
{
	if ($('#'+$acts).valid()) {
		if($('#txt_final_pur_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!", "purchase details save successfully", "success");										
						$("#"+$acts)[0].reset();
						$(location).attr('href', $lodlnk);
						unloading();
					}
					else if(response.rslt == "2"){
						swal("Success!", "purchase 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;
}


$(document).ready(function() {
   
	$('#tbl_body_return_det').on('change', 'input[name="chk_select_product[]"]', function() {
		var selectedProductIds = [];
		var selectedProductDescs = [];
		var selectedProductPurchases = [];
		var selectedProductDiscounts = [];
		var selectedProductDiscount_amts = [];
		var selectedProductTot_amts = [];
        var totalSaleAmount = 0;
        $('#tbl_body_return_det input[name="chk_select_product[]"]:checked').each(function() {
            var row = $(this).closest('tr');
            var productAmount = parseFloat(row.find('td:eq(7)').text()); // Assuming total amount is in the 8th column
			var product_id = row.find('td:eq(1)').text();
			var product_desc = row.find('td:eq(2)').text();
			var product_purchase = row.find('td:eq(4)').text();
			var product_discount = row.find('td:eq(5)').text();
			var product_discount_amt = row.find('td:eq(6)').text();

			// console.log(product_purchase);

			selectedProductIds.push(product_id); 
			selectedProductDescs.push(product_desc); 
			selectedProductPurchases.push(product_purchase); 
			selectedProductDiscounts.push(product_discount); 
			selectedProductDiscount_amts.push(product_discount_amt); 
			selectedProductTot_amts.push(productAmount); 
			
			
			$('#overall_product_id').val(selectedProductIds.join(','));
			$('#overall_product_desc').val(selectedProductDescs.join(','));
			$('#overall_product_purchase').val(selectedProductPurchases.join(','));
			$('#overall_product_discount').val(selectedProductDiscounts.join(','));
			$('#overall_product_discount_amt').val(selectedProductDiscount_amts.join(','));
			$('#overall_product_tot_amt').val(selectedProductTot_amts.join(','));
			
            totalSaleAmount += productAmount;
    
        });
        
        var discountPercentage = parseFloat($('#overall_discount_per').val());
		
        var discountAmount = (totalSaleAmount * discountPercentage) / 100;
		var finalAmount = totalSaleAmount - discountAmount;

        $('#txt_tot_pur_amt').val(totalSaleAmount.toFixed(2)); 
        $('#overall_discount_amt').val(discountAmount.toFixed(2));
		
        $('#overall_total_amt').val(finalAmount.toFixed(2));
		
		

        calculateTaxesAndFinalAmount();

	function calculateTaxesAndFinalAmount() {
	
	var totalSaleAmount = parseFloat($('#overall_total_amt').val());

	// Read the CGST, SGST, and IGST values from the fields (read-only from database)
	var cgstPercentage = parseFloat($('#txt_cgst').val());
	var sgstPercentage = parseFloat($('#txt_sgst').val());
	var igstPercentage = parseFloat($('#txt_igst').val());

	var cgstAmount = (totalSaleAmount * cgstPercentage) / 100;
	var sgstAmount = (totalSaleAmount * sgstPercentage) / 100;
	var igstAmount = (totalSaleAmount * igstPercentage) / 100;

	$('#txt_cgst_total').val(cgstAmount.toFixed(2));
	$('#txt_sgst_total').val(sgstAmount.toFixed(2));
	$('#txt_igst_total').val(igstAmount.toFixed(2));

	var totalTaxAmount = cgstAmount + sgstAmount + igstAmount;
	$('#txt_tax_amt').val(totalTaxAmount.toFixed(2));

	var finalSaleAmount = totalSaleAmount + totalTaxAmount;
	$('#txt_final_pur_amt').val(finalSaleAmount.toFixed(2));
	// console.log($('#txt_igst_total').val());

}
		
	});

    $("#sel_company").change(function() {
        var selectedCompanyId = $(this).val();
        var selectedCompanyName = $("#sel_company option:selected").text();
        
        // Update the input field with the selected company name
        $("#company_name").val(selectedCompanyName);
    });

    $('#txt_bill_no').keyup(function() {
		var finacial_id = $('#financial_id').val();
		var company_id = $('#sel_company').val();
		var company_name = $('#company_name').val();
        var billNumber = $(this).val();
		var purchase = 'purchase';
        
        $.ajax({
            url: 'ajax_actions.php', 
            method: 'GET',
            data: { bill_number: billNumber, financial_id: finacial_id, company_id: company_id, return:purchase  },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
					if (response.data.bill_date) {
						var dateParts = response.data.bill_date.split('-');
						var formattedDate = dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0];
						$('#txt_bill_date').val(formattedDate);
					} else {
					
						$('#txt_bill_date').val('');
					}

                    $('#txt_bill_no').val(response.data.bill_number);
                    $('#txt_supplier').val(response.data.supplier_name);
                    $('#txt_supplier_id').val(response.data.supplier_id);
                    $('#txt_company').val(response.data.company_name);
                    // $('#p_invoice_id').val(response.data.p_invoice_id);
                    
                    $('#txt_notes').val(response.data.notes);
					$('#txt_supplier_city').val(response.data.supplier_city);
					$('#txt_supplier_state').val(response.data.supplier_state);
					$('#txt_supplier_gst').val(response.data.supplier_gst);
					$('#txt_supplier_pin').val(response.data.supplier_pin);
					$('#overall_discount_per').val(response.data.discount_per );
					$('#txt_cgst').val(response.data.cgst );
					$('#txt_sgst').val(response.data.sgst );
					$('#txt_igst').val(response.data.igst );
                    populateProductDetails(response.data.product_details);
                } else {
                    // Handle error case
                }
            },
            error: function() {
                // Handle error case
            }
        });
    });

    function populateProductDetails(productDetails) {
        $('#tbl_body_return_det').empty();
        if (productDetails.length > 0) {
            productDetails.forEach(function(product) {
				var statusClass = 'btn btn-danger rounded-pill';
				var checkboxDisabled = 'disabled';
				if(product.status=='Available')
				{
					statusClass = 'btn btn-warning rounded-pill';
					checkboxDisabled = '';
				}
				else if(product.status=='Returned')
				{
					statusClass = 'btn btn-success rounded-pill';
				}
            
                var row = '<tr>' +
                    '<td><input type="checkbox" style="width: 20px; height: 20px;" class="form-check-input" name="chk_select_product[]" value="' + product.p_bill_det_id + '" ' + checkboxDisabled + ' /></td>' +
                    '<td>' + product.pdt_sku + '</td>' +
                    '<td>' + product.saree_desc + '</td>' +
                    '<td>' + product.pdt_img + '</td>' +
                    '<td>' + product.purchase_price + '</td>' +
					'<td>'+ product.pdt_discount_percent+'</td>' +
					'<td>'+ product.pdt_discount_amt+'</td>' +
                    '<td>' + product.tot_amount + '</td>' +
                    '<td style="text-align: center;font-s" ><button class="'+statusClass+'" style= "pointer-events: none; color:black;">' + product.status + '</button></td>' +
    				
					'</tr>';
                $('#tbl_body_return_det').append(row);
            });
        } else {
            var emptyRow = '<tr><td colspan="12">No products found for this bill.</td></tr>';
            $('#tbl_body_return_det').append(emptyRow);
        } 
    }

	

});



</script>


</body>
</html>
	  