<?php 
include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdmeSalesEntry($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_sales_entry_main where IsActive != '2' and s_bill_no = '".base64_decode($id)."' ";
$res_ed = $db->get_a_line($str_ed);

/*
$rslt_pdt_list = $db->get_rsltset("select t1.*,t2.upload_img from t_sales_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 t1.*,'' as upload_img from t_sales_entry_details t1 where 1=1 and t1.IsActive=1 and t1.s_bill_no='".$res_ed['s_bill_no']."' ");

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

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

$edit_id = $res_ed['s_bill_no'];
$disp_inv_no = $res_ed['actu_bill_no'];
$notes = $res_ed['notes'];

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

<div class="wrapper">
    <div class="container">        
		<!-- Page-Title - START -->
        <div class="row">
            <div class="col-sm-12">										
                <h4 class="page-title"><?php echo $operation; ?> Sales Entry</h4>						
            </div>
        </div>
		<!-- Page-Title - END -->	
					
		<div class="row">
			<div class="col-sm-12">
				<form id="jvalidate" name="frmSales" role="form" class="form-horizontal" action="#" 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-6">
								
								<div class="form-group">
									<label>Select Company<span class="text-danger">*</span></label>							
									<select onchange="get_bill_no_by_cmpny_id(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>
								</div>	
								
								<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">
										<option value="">Select</option>
										<?php 
										$rslt_list = $db->get_rsltset("select 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>
								</div>	
								
							</div>
							
							<div class="col-sm-6">
							
								<div class="form-group">
									<label>Bill No</label>							
									<input type="text" class="form-control jsrequired" name="txt_bill_no" id="txt_bill_no" value="<?php echo $disp_inv_no; ?>" readonly />
								</div>		

								<div class="form-group">
									<label>Bill Date</label>							
									<input type="text" class="form-control jsrequired" name="txt_bill_date" id="txt_bill_date" value="<?php echo $res_ed['s_bill_date']; ?>"  />
								</div>	
								
							</div>

							<div class="col-sm-12">
							
								<div class="form-group">
									<label>Notes</label>							
									<input type="text" class="form-control" name="txt_notes" id="txt_notes" value="<?php echo $notes; ?>" />
								</div>		
								
							</div>							
							
						</div>
						
						
						<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 width="10%">Product SKU</th>
												<th width="20%">Product Details</th>												
												<th width="10%">Image</th>
												<th width="10%">Purchase Rate</th>
												<th width="10%">Sale Price</th>	
												<th width="15%">Discount (%)</th>
												<th width="15%">Amount Rs.</th>												
											</tr>
										</thead>
										<tbody id="tbl_body_category_det">
											<?php 
											if($pdt_sv_cnt >0){
												$ai=0;
												foreach($rslt_pdt_list as $r){
													$ai = $ai+1;
													$pdt_prev_img='NoImage.png';
													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['s_bill_det_id']; ?>" />
													
													<td>
														<input type="text" class="autocmplte_pdtsku form-control" name="txt_pdt_sku[]" id="txt_pdt_sku_<?php echo $ai; ?>" value="<?php echo $r['pdt_sku']; ?>" />														
													</td>
													
													<td>														
														<input type="text" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_<?php echo $ai; ?>" value="<?php echo $r['saree_desc']; ?>" readonly />
													</td>
													
													<td>														
														<img id="preview_img_<?php echo $ai; ?>" src="<?php echo BASE_URL; ?>uploads/product_image/<?php echo $pdt_prev_img; ?>" width="50px" height="50px" align="absmiddle"/>	
													</td>
													
													<td>														
														<input type="text" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_<?php echo $ai; ?>" value="<?php echo $r['purchase_price']; ?>" readonly />
													</td>
													
													<td>														
														<input type="text" class="form-control" name="txt_sale_price[]" id="txt_sale_price_<?php echo $ai; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" value="<?php echo $r['sale_price']; ?>" />
													</td>
													
													<td>
														<input type="text" 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']; ?>" />
														<input readonly type="text" 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" class="form-control cls_pdt_tot_amt" name="txt_tot_amt[]" id="txt_tot_amt_<?php echo $ai; ?>" value="<?php echo $r['tot_amount']; ?>" readonly /> <?php if($ai!=1) { ?><a onclick="remove_pdt_row('<?php echo $ai; ?>')" href="javascript:;"><span class="icon-close" style="display:inline"></span></a><?php } ?>

													</td>	
													
												</tr>	
												
											<?php 
												}
											}
											else{ ?>
												
												<tr id="dy_rw_1">
												<input type="hidden" name="hdn_pdt_cnt[]" value="1" />
												<input type="hidden" name="hdn_prev_sv_id[]" value="0" />
												<td>
													<input type="text" class="form-control autocmplte_pdtsku" name="txt_pdt_sku[]" id="txt_pdt_sku_1"  />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_1" readonly />
												</td>
												<td>
													<img id="preview_img_1" src="<?php echo BASE_URL; ?>uploads/product_image/NoImage.png" width="50px" height="50px" align="absmiddle"/>
												</td>
												<td>
													<input type="text" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_1" readonly />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_sale_price[]" id="txt_sale_price_1" onchange="amount_calc_by_pdt(1);" />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_pdt_discount_per[]" id="txt_pdt_discount_per_1" onchange="amount_calc_by_pdt(1);" />
													<input readonly type="text" class="form-control" name="txt_pdt_discount_amt[]" id="txt_pdt_discount_amt_1"  />
												</td>
												<td>
													<input type="text" class="form-control cls_pdt_tot_amt" name="txt_tot_amt[]" id="txt_tot_amt_1" readonly />
												</td>	
											</tr>
													
											<?php		
											}	?>
											
										</tbody>
										<tfoot>
											<tr>
												<td colspan="6">&nbsp;</td>
												<td>
													<a onclick="add_dynamic_pdt_rw()" class="btn btn-warning waves-effect waves-light" href="javascript:;">Add <span class="m-l-5"> <i class="fa fa-plus"></i></span></a>
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&nbsp;</td>
												<td>Total Sale Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_tot_sale_amt" id="txt_tot_sale_amt" value="<?php echo $res_ed['total_sale_amount']; ?>" />
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&nbsp;</td>
												<td>Discount (%)</td>
												<td>		
													<input type="text" class="form-control" name="txt_cmn_discount_per" id="txt_cmn_discount_per" onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" value="<?php echo $res_ed['discount_per']; ?>" />
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&nbsp;</td>
												<td>After Discount Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_after_discount_amt" id="txt_after_discount_amt" value="<?php echo $res_ed['after_discount_amt']; ?>" />
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&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" onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" value="<?php echo $res_ed['cgst_per']; ?>" />
													<input type="text" class="form-control" name="txt_cgst_total" id="txt_cgst_total" onKeyPress="return isNumberKey(event,this)" value="<?php echo $res_ed['cgst_total']; ?>" readonly/>
													</div>
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&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"  onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" value="<?php echo $res_ed['sgst_per']; ?>" />
													<input type="text" class="form-control" name="txt_sgst_total" id="txt_sgst_total" onKeyPress="return isNumberKey(event,this)" value="<?php echo $res_ed['sgst_total']; ?>" readonly/>
													</div>
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&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"  onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" value="<?php echo $res_ed['txt_igst']; ?>" />
													<input type="text" class="form-control" name="txt_igst_total" id="txt_igst_total" onKeyPress="return isNumberKey(event,this)" value="<?php echo $res_ed['igst_total']; ?>" readonly/>
													</div>
												</td>
											</tr>
											
											<tr>
												<td colspan="5">&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="5">&nbsp;</td>
												<td>Final Sale Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_final_sale_amt" id="txt_final_sale_amt" value="<?php echo $res_ed['final_sale_amt']; ?>" />
												</td>
											</tr>
											
										</tfoot>
									</table>
								</div>
							</div>
						</div>
						
						
						<!--<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 width="10%">Product SKU</th>
												<th width="20%">Product Details</th>												
												<th width="10%">Sale Price</th>	
												<th width="10%">Tax (%)</th>
												<th width="10%">CGST (%)</th>
												<th width="10%">SGST (%)</th>
												<th width="10%">IGST (%)</th>
												<th width="10%">Tax Amount</th>
												<th width="10%">Amount Rs.</th>												
											</tr>
										</thead>
										<tbody id="tbl_body_category_det">
											<?php 
											if($pdt_sv_cnt >0){
												$ai=0;
												foreach($rslt_pdt_list as $r){
													$ai = $ai+1;
													$pdt_prev_img='NoImage.png';
													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['s_bill_det_id']; ?>" />
													<td>
														<input type="text" class="autocmplte_pdtsku form-control" name="txt_pdt_sku[]" id="txt_pdt_sku_<?php echo $ai; ?>" value="<?php echo $r['pdt_sku']; ?>" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_<?php echo $ai; ?>" value="<?php echo $r['saree_desc']; ?>" readonly />
														
														<img id="preview_img_<?php echo $ai; ?>" src="<?php echo BASE_URL; ?>uploads/product_image/<?php echo $pdt_prev_img; ?>" width="50px" height="50px" align="absmiddle"/>	
														
														<input type="text" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_<?php echo $ai; ?>" value="<?php echo $r['purchase_price']; ?>" readonly />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_sale_price[]" id="txt_sale_price_1" onchange="amount_calc_by_pdt(1);" value="<?php echo $r['sale_price']; ?>" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_m_tax[]" id="txt_m_tax_<?php echo $ai; ?>" value="<?php echo $r['m_tax_percent']; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_cgst[]" id="txt_cgst_<?php echo $ai; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" value="<?php echo $r['cgst_tax']; ?>" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_sgst[]" id="txt_sgst_<?php echo $ai; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" value="<?php echo $r['sgst_tax']; ?>" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_igst[]" id="txt_igst_<?php echo $ai; ?>" onchange="amount_calc_by_pdt(<?php echo $ai; ?>);" value="<?php echo $r['igst_tax']; ?>" />
													</td>
													<td>
														<input type="text" class="form-control" name="txt_tax_amt[]" id="txt_tax_amt_<?php echo $ai; ?>" value="<?php echo $r['tax_amount']; ?>" readonly  />
													</td>
													<td>
														<input type="text" class="form-control cls_pdt_tot_amt" name="txt_tot_amt[]" id="txt_tot_amt_<?php echo $ai; ?>" value="<?php echo $r['tot_amount']; ?>" readonly />
														
														<?php 
														if($ai >1){
														?>
														<a onclick="delete_pdt_row(<?php echo $ai; ?>,<?php echo $r['s_bill_det_id']; ?>)" href="javascript:;"><span class="icon-close" style="display:inline"></span></a> 
														<?php	
														}
														?>
														
													</td>												
												</tr>
												
												
												<?php		
												}												
											}else{
											?>
											
											<tr id="dy_rw_1">
												<input type="hidden" name="hdn_pdt_cnt[]" value="1" />
												<input type="hidden" name="hdn_prev_sv_id[]" value="0" />
												<td>
													<input type="text" class="form-control autocmplte_pdtsku" name="txt_pdt_sku[]" id="txt_pdt_sku_1"  />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_1" readonly />
												</td>
												<td>
													<img id="preview_img_1" src="<?php echo BASE_URL; ?>uploads/product_image/NoImage.png" width="50px" height="50px" align="absmiddle"/>
												</td>
												<td>
													<input type="text" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_1" readonly />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_sale_price[]" id="txt_sale_price_1" onchange="amount_calc_by_pdt(1);" />
												</td>
												<td>
													<input type="text" class="form-control" name="txt_pdt_discount_per[]" id="txt_pdt_discount_per_1" onchange="amount_calc_by_pdt(1);" />
													<input readonly type="text" class="form-control" name="txt_pdt_discount_amt[]" id="txt_pdt_discount_amt_1"  />
												</td>
												<td>
													<input type="text" class="form-control cls_pdt_tot_amt" name="txt_tot_amt[]" id="txt_tot_amt_1" readonly />
												</td>	
											</tr>

											<?php	
											}
											?>	
																						
										</tbody>
										<tfoot>
											<tr>
												<td colspan="8">&nbsp;</td>
												<td>
													<a onclick="add_dynamic_pdt_rw()" class="btn btn-warning waves-effect waves-light" href="javascript:;">Add <span class="m-l-5"> <i class="fa fa-plus"></i></span></a>
												</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">
										<label>Over All Total</label>
										<input readonly type="text" class="form-control" name="txt_over_all_total" id="txt_over_all_total" value="<?php echo $disp_over_all_tot; ?>" />
									</div>
								</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 class="btn btn-primary waves-effect waves-light" type="button" onClick="javascript:funSave_sales('frmSales','sales_actions.php','jvalidate','sales','sales_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('frmSales','jvalidate','sales','sales_mng.php');" >Cancel</button>													 
										
									</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"> 
$(function () {	
	var date = new Date();
	var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());		
	$('#txt_bill_date').datepicker({	
		format: 'yyyy-mm-dd',
		startDate: '-100y',
		endDate: '+0d',
		autoclose: true,	
		assumeNearbyYear:20,	
		todayHighlight: true
		
	});	
	
	<?php if($act=="insert"){ ?> 
	$('#txt_bill_date').datepicker('setDate', today);
	<?php } ?>
	
	auto_complete_intialize(1);
	
	
		
});


function auto_complete_intialize(rw_cnt){		
	$('.autocmplte_pdtsku').autocomplete({ 
		lookup: function (query, done) {		
			$.ajax({
				url  : "autocomplete_actions.php?pageaction=autocomplete_salesentry&srch_type=pdt_sku&company_name="+$("#sel_company").val()+"&srch_keyword="+query,
				dataType: "json",						
				success: function (data)
				{					
				 done(data);				 
				}				
			});			
		},
		onSelect:function(dt){
			var current_element = $(this).prop("id");
			rw_cnt = current_element.replace("txt_pdt_sku_","");                         
			bind_product_details(rw_cnt, dt.value, dt.data);
		}
	});
}

function bind_product_details(rw_id, pdt_sku, pdt_inv_det_id){
	$.ajax({
		url: 'ajax_actions.php',
		type: 'POST',
		dataType : 'json',
		data: 'action=get_product_det_by_pdtsku&product_sku='+pdt_sku+'&pdt_invDet_id='+pdt_inv_det_id,
		beforeSend: loading(),
		success: function(response) {				
			if(response.rslt == "1"){
				//swal("Success!", "sync success", "success");
				$("#txt_pdt_desc_"+rw_id).val(response.pdt_desc);
				$("#txt_purchase_price_"+rw_id).val(response.pdt_price);
				$("[id*=preview_img_"+rw_id+"]").attr("src", response.pdt_img_url);
			}			
			unloading();
		}
	});
}


function add_dynamic_pdt_rw(){			
	var rw_cnt = parseInt($("#hdn_pdt_sno").val()) +1;
		
	var dy_html = ' <tr id="dy_rw_'+rw_cnt+'"><input type="hidden" name="hdn_pdt_cnt[]" value="'+rw_cnt+'" /><input type="hidden" name="hdn_prev_sv_id[]" value="0" /><td><input type="text" class="autocmplte_pdtsku form-control" name="txt_pdt_sku[]" id="txt_pdt_sku_'+rw_cnt+'"  /></td>  <td><input type="text" class="form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_'+rw_cnt+'" readonly /> </td> <td> <img id="preview_img_'+rw_cnt+'" src="<?php echo BASE_URL; ?>uploads/product_image/NoImage.png" width="50px" height="50px" align="absmiddle"/> </td> <td><input type="text" class="form-control" name="txt_purchase_price[]" id="txt_purchase_price_'+rw_cnt+'" readonly /></td> <td> <input type="text" class="form-control" name="txt_sale_price[]" id="txt_sale_price_'+rw_cnt+'" onchange="amount_calc_by_pdt('+rw_cnt+');" /> </td> <td><input type="text" class="form-control" name="txt_pdt_discount_per[]" id="txt_pdt_discount_per_'+rw_cnt+'" onchange="amount_calc_by_pdt('+rw_cnt+');" /> <input readonly type="text" class="form-control" name="txt_pdt_discount_amt[]" id="txt_pdt_discount_amt_'+rw_cnt+'"  /> </td> <td><input type="text" class="form-control cls_pdt_tot_amt" name="txt_tot_amt[]" id="txt_tot_amt_'+rw_cnt+'" readonly /> <a onclick="remove_pdt_row('+rw_cnt+')" href="javascript:;"><span class="icon-close" style="display:inline"></span></a> </td></tr> ';
		
	$("#tbl_body_category_det").append(dy_html);
	$("#hdn_pdt_sno").val(rw_cnt);	
	
	auto_complete_intialize(rw_cnt);
}

function remove_pdt_row(rw_id){
	$("#dy_rw_"+rw_id).remove();
	
	final_amount_calculations();
}


function amount_calc_by_pdt(rw_val){
	//actual rate amount calculation
	var pdt_rate = parseFloat($("#txt_sale_price_"+rw_val).val());
	
	//product discount
	var pdt_discount_per = parseFloat($("#txt_pdt_discount_per_"+rw_val).val());	
	if(isNaN(pdt_discount_per)) {
		pdt_discount_per =0;
	}		
	var pdt_discount_amt = parseFloat(pdt_rate*0.01*pdt_discount_per).toFixed(0);
	$("#txt_pdt_discount_amt_"+rw_val).val(parseFloat(pdt_discount_amt).toFixed(0)); 
			
	//product total amount calculation
	var pdt_tot_amt = parseFloat(pdt_rate) - parseFloat(pdt_discount_amt);
	$("#txt_tot_amt_"+rw_val).val(parseFloat(pdt_tot_amt).toFixed(0)); 
	
	final_amount_calculations();
}

function final_amount_calculations(){	
	var lst_pdt_amt =0;
	$("input:text.cls_pdt_tot_amt").each(function() { 
	    lst_pdt_amt = parseFloat(lst_pdt_amt) + parseFloat($(this).val());
    });		
	$("#txt_tot_sale_amt").val(parseFloat(lst_pdt_amt).toFixed(0)); 
	
	//common discount
	var cmn_discount_per = parseFloat($("#txt_cmn_discount_per").val());	
	if(isNaN(cmn_discount_per)) {
		cmn_discount_per =0;
	}
	var cmn_discount_amt = parseFloat(lst_pdt_amt*0.01*cmn_discount_per).toFixed(0);
	var after_discount_amt = parseFloat(lst_pdt_amt) - parseFloat(cmn_discount_amt);
	$("#txt_after_discount_amt").val(parseFloat(after_discount_amt).toFixed(0));
	
	//CGST and SGST Calculation
	var cgst_tax_val=0; var sgst_tax_val=0; var igst_tax_val=0;
		
	if($("#txt_cgst").val()){
		cgst_tax_val=parseFloat($("#txt_cgst").val());
	}
	if($("#txt_sgst").val()){
		sgst_tax_val=parseFloat($("#txt_sgst").val());
	}
	if($("#txt_igst").val()){
		igst_tax_val=parseFloat($("#txt_igst").val());
	}
	
	var cgst_tax_amt = parseFloat(after_discount_amt*0.01*cgst_tax_val).toFixed(0);
	$('#txt_cgst_total').val(cgst_tax_amt);	
	var sgst_tax_amt = parseFloat(after_discount_amt*0.01*sgst_tax_val).toFixed(0);
	$('#txt_sgst_total').val(sgst_tax_amt);	
	var igst_tax_amt = parseFloat(after_discount_amt*0.01*igst_tax_val).toFixed(0);
	$('#txt_igst_total').val(igst_tax_amt);		
	
	var tot_tax_amt = parseFloat(cgst_tax_amt) + parseFloat(sgst_tax_amt) + parseFloat(igst_tax_amt);
	
	$("#txt_tax_amt").val(parseFloat(tot_tax_amt).toFixed(0));
	
	var final_sale_amt = parseFloat(after_discount_amt) + parseFloat(tot_tax_amt);
	
	$("#txt_final_sale_amt").val(parseFloat(final_sale_amt).toFixed(0));
	
}

function funSave_sales($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 delete_pdt_row(row_id, pdt_det_id){
	if(row_id !='' && pdt_det_id !=''){
		swal({
			title: "Are you sure?",
			text: "You will not be able to recover this details!",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "Yes, delete it!",
			closeOnConfirm: true,
			closeOnCancel: true
		},
		function () {			
			 $.ajax({
				url: 'sales_actions.php',
				type: 'POST',
				dataType : 'json',
				data: 'action=del_pdt_det&pdt_det_id='+pdt_det_id,
				beforeSend: loading(),
				success: function(response) {				
					if(response.rslt == "1"){
						swal("Success!", "Product Delete Successfully", "success");
						$("#dy_rw_"+row_id).remove();
	
						final_amount_calculations();
					}					
					else if(response.rslt == "-9"){
						swal("Failure!", response.err_msg, "warning");
					}
					else{
						swal("Failure!", "somehing missing try some time", "warning");
					}					
					unloading();
				}
			});
		}); 	
	}	
}

function isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	
   return true;
}


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"){					
					//cst tax value bind on 
					var cus_state_name = response.cus_state.toLowerCase().replace(/\s/g,'');
										
					if(cus_state_name !='tamilnadu'){
						if(cus_state_name == ''){
							$("#txt_cgst").val(2.5);
							$("#txt_sgst").val(2.5);
							
							$("#txt_igst").val(0);
						}
						else{
							$("#txt_igst").val(5);
							
							$("#txt_cgst").val(0);
							$("#txt_sgst").val(0);
						}
					}else{
						$("#txt_cgst").val(2.5);
						$("#txt_sgst").val(2.5);
							
						$("#txt_igst").val(0);
					}
					
				}			
				unloading();
			}
		});   	
	}
}

function get_bill_no_by_cmpny_id(cmpny_id){
	if(cmpny_id !=''){					
		$.ajax({		
			url        : 'ajax_actions.php',
			method     : 'POST',
			dataType   : 'json',
			data       : 'action=get_bill_no_by_company_id&company_id='+cmpny_id,
			beforeSend: function() { loading(); },
			success: function(response){
				$("#txt_bill_no").val(response.rslt);
				unloading();
			}		
		});
	}
}

</script>



</body>
</html>
	  