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

$rslt_pdt_list = $db->get_rsltset("select * from t_purchase_entry_details where 1=1 and IsActive=1 and p_invoice_no='".$res_ed['p_invoice_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['p_invoice_no'];
$disp_inv_no = $res_ed['actu_inv_no'];


}
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; ?> Purchase Entry</h4>						
            </div>
        </div>
		<!-- Page-Title - END -->	
					
		<div class="row">
			<div class="col-sm-12">
				<form id="jvalidate" name="frmPurchase" 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-12">
							
								<div class="form-group">
									<label>Financial Year<span class="text-danger">*</span></label>							
									<select onchange="get_inv_no_by_cmpny_id($('#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-6">
								
								<div class="form-group">
									<label>Select Company<span class="text-danger">*</span></label>							
									<select onchange="get_inv_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 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">
										<option value="">Select</option>
										<?php 
										$rslt_list = $db->get_rsltset("select 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:none ;">
									<div class="col-sm-3">
									<label>Gst: <span id="supplier_gst_no" style="color:green; font-size:12px;"></span></label>
									</div>
									<div class="col-sm-8">
									<label>Address: <span id="supplier_address" style="color:green; font-size:12px;"></span></label>
									</div>
									<div class="col-sm-3">
									<label>City: <span id="supplier_city" style="color:green; font-size:12px;"></span></label>
									</div>
									<div class="col-sm-3">
									<label>State: <span id="supplier_state" style="color:green; font-size:12px;"></span></label>
									</div>
									<div class="col-sm-3">
									<label>Pincode:<span id="supplier_postcode" style="color:green; font-size:12px;"></span></label>

									</div>
									</div>
								</div>	
								
							</div>
							
							<div class="col-sm-6">
							
								<div class="form-group">
									<label>Invoice No</label>							
									<input type="text" class="form-control jsrequired" name="txt_inv_no" id="txt_inv_no" value="<?php echo $disp_inv_no; ?>" />
								</div>		

								<div class="form-group">
									<label>Invoice Date</label>							
									<input type="text" class="form-control jsrequired" name="txt_inv_date" id="txt_inv_date" value="<?php echo  date('d-m-Y', strtotime($res_ed['p_invoice_date'])); ?>"  />
								</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="1%">#</th>-->
												<th width="20%">Product SKU</th>
												<th width="30%">Saree Description</th>
												<th width="20%">Image</th>
												<th width="20%">Purchase Rate</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['p_invoice_det_id']; ?>" />
													<td>
														<input type="text" class="form-control pdtskucls" name="txt_pdt_sku[]" id="txt_pdt_sku_<?php echo $ai; ?>" value="<?php echo $r['pdt_sku']; ?>" onchange="check_pdt_sku(this.id, this.value);" />

													</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']; ?>" />
													</td>
													<td>
														<input id="pdt_img_<?php echo $ai; ?>" name="pdt_img[]" type="file" accept="image/jpeg,image/png,jpg|png" onchange="readURL1(this,<?php echo $ai; ?>);" />
														<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 cls_pdt_rate" name="txt_pdt_rate[]" id="txt_pdt_rate_<?php echo $ai; ?>"  value="<?php echo $r['purchase_rate']; ?>" onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" />
														
														<?php 
														if($ai >1){
														?>
														<a onclick="delete_pdt_row(<?php echo $ai; ?>,<?php echo $r['p_invoice_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 pdtskucls" name="txt_pdt_sku[]" id="txt_pdt_sku_1"  onchange="check_pdt_sku(this.id,this.value);" />
													<span id="sku_last_id"></span>
												</td>
												<td>
													<input type="text" class="autocmplte_sareedesc form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_1" />
												</td>
												<td>
													<input id="pdt_img_1" name="pdt_img[]" type="file" accept="image/jpeg,image/png,jpg|png" onchange="readURL1(this,1);" />
													<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 cls_pdt_rate" name="txt_pdt_rate[]" id="txt_pdt_rate_1" onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" />
												</td>	
											</tr>

											<?php	
											}
											?>	
																						
										</tbody>
										<tfoot>
											<tr>
												<td colspan="3">&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="2">&nbsp;</td>
												<td>Total Purchase Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_tot_purchase_amt" id="txt_tot_purchase_amt" value="<?php echo $res_ed['tot_pur_amount']; ?>" />
												</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" 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="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"  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="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"  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="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 Purchase Amount</td>
												<td>		
													<input readonly type="text" class="form-control" name="txt_final_purchase_amt" id="txt_final_purchase_amt" value="<?php echo $res_ed['final_pur_amt']; ?>" />
												</td>
											</tr>
											
										</tfoot>
									</table>
								</div>
							</div>
						</div>
						
						<div class="row">
							<div class="col-sm-4">&nbsp;</div>
					
							<div class="col-sm-8">						
								<!--<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_purchase('frmPurchase','purchase_actions.php','jvalidate','purchase','purchase_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('frmPurchase','jvalidate','purchase','purchase_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";  ?> 

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

});


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="form-control pdtskucls" name="txt_pdt_sku[]"  id="txt_pdt_sku_'+rw_cnt+'" onchange="check_pdt_sku(this.id,this.value);" /></td> <td><input type="text" class="autocmplte_sareedesc form-control" name="txt_pdt_desc[]" id="txt_pdt_desc_'+rw_cnt+'" /></td>  <td> <input id="pdt_img_'+rw_cnt+'" name="pdt_img[]" type="file" accept="image/jpeg,image/png,jpg|png" onchange="readURL1(this,'+rw_cnt+');" /> <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 cls_pdt_rate" name="txt_pdt_rate[]" id="txt_pdt_rate_'+rw_cnt+'"  onKeyPress="return isNumberKey(event,this)" onchange="final_amount_calculations();" /> <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 readURL1(input,rw_id) { 
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $("[id*=preview_img_"+rw_id+"]").attr("src", e.target.result);
        };
        reader.readAsDataURL(input.files[0]);       
    }
}

function amount_calc_by_pdt(rw_val){
	//actual rate amount calculation
	var pdt_rate = parseFloat($("#txt_pdt_rate_"+rw_val).val());
	
	//split cgst, sgst amount - START
	var cgst_tax_val = parseFloat($("#txt_cgst_"+rw_val).val());	
	if(isNaN(cgst_tax_val)) {
		cgst_tax_val =0;
	}
	var sgst_tax_val = parseFloat($("#txt_sgst_"+rw_val).val());	
	if(isNaN(sgst_tax_val)) {
		sgst_tax_val =0;
	}
	var igst_tax_val = parseFloat($("#txt_igst_"+rw_val).val());	
	if(isNaN(igst_tax_val)) {
		igst_tax_val =0;
	}
	
	var cgst_tax_amt = parseFloat(pdt_rate*0.01*cgst_tax_val).toFixed(0);
	var sgst_tax_amt = parseFloat(pdt_rate*0.01*sgst_tax_val).toFixed(0);
	var igst_tax_amt = parseFloat(pdt_rate*0.01*igst_tax_val).toFixed(0);
	
	var pdt_tax_amt = parseFloat(parseFloat(cgst_tax_amt) + parseFloat(sgst_tax_amt) + parseFloat(igst_tax_amt)).toFixed(0);
	$("#txt_tax_amt_"+rw_val).val(pdt_tax_amt); 
	
	//product total amount calculation
	var pdt_tot_amt = parseFloat(pdt_rate) + parseFloat(pdt_tax_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_rate").each(function() { 
	    lst_pdt_amt = parseFloat(lst_pdt_amt) + parseFloat($(this).val());
    });	
	
	$("#txt_tot_purchase_amt").val(parseFloat(lst_pdt_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(lst_pdt_amt*0.01*cgst_tax_val).toFixed(0);
	$('#txt_cgst_total').val(cgst_tax_amt);

	var sgst_tax_amt = parseFloat(lst_pdt_amt*0.01*sgst_tax_val).toFixed(0);
	$('#txt_sgst_total').val(sgst_tax_amt);

	var igst_tax_amt = parseFloat(lst_pdt_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_pur_amt = parseFloat(lst_pdt_amt) + parseFloat(tot_tax_amt);
	
	$("#txt_final_purchase_amt").val(parseFloat(final_pur_amt).toFixed(0));
	
}

function funSave_purchase($frm,$urll,$acts,$stats,$lodlnk)
{
	if ($('#'+$acts).valid()) {
		if($('#txt_over_all_total').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);							 
			});
			
			var c=0;
			var file_data;
			$('input[type="file"]').each(function(){
				file_data = $('input[type="file"]')[c].files;
				for(var i = 0;i<file_data.length;i++){
                   m_data.append("uploadimg_"+c, file_data[i]); // we can put more than 1 image file
				}				
				c++;
			});
						

			$.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!", "Invoice details save successfully", "success");										
						$("#"+$acts)[0].reset();
						$(location).attr('href', $lodlnk);
						unloading();
					}
					else if(response.rslt == "2"){
						swal("Success!", "Invoice details update successfully", "success");										
						$("#"+$acts)[0].reset();
						$(location).attr('href', $lodlnk);
						unloading();
					}
					else if(response.rslt == "3"){
						swal("Error!", response.err_msg, "warning");										
						//$("#"+$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: 'purchase_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 check_pdt_sku(txt_bx_id,pdt_sku){
	if(pdt_sku){
		
		if($("#sel_company").val()){
		
			$.ajax({
				url: 'purchase_actions.php',
				type: 'POST',
				dataType : 'json',
				data: 'action=check_pdt_sku&pdt_sku='+pdt_sku+'&company_name='+$("#sel_company").val()+'&invoice_id='+$("#edit_id").val(),
				beforeSend: loading(),
				success: function(response) {				
					if(response.rslt == "-9"){
						swal("Failure!", response.err_msg, "warning");
						$("#"+txt_bx_id).val("");
					}				
					unloading();
				}
			});

			  var obj = {};
  			  var i = 0;

			 $(".pdtskucls").each(function(){			 	 
			     if(obj.hasOwnProperty(this.value)) {
			      alert("there is a duplicate value " + this.value);
			      $('#'+txt_bx_id).val("")
			    } else {
			      obj[this.value] = this.value;
			    }
			  });

		}
		else{
			swal("Failure!", "Please Select Company", "warning");
		}
	}
}


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_supplier_details(sup_id){	
	
	if(sup_id !=''){	
		var psno = $('#hdn_pdt_sno').val();
		$('#txt_pdt_desc_'+psno).val('');
		$.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"){					
					//cst tax value bind on 
					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;

					$("#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);	
					$(".row").show();

					var sup_state_name = response.sup_state.toLowerCase().replace(/\s/g,'');

					var sup_type = response.sup_type;					
										
					if(sup_state_name !='tamilnadu'){
						if(sup_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);
					}

					if(sup_type == 1){
						$("#txt_cgst").val(0);
						$("#txt_sgst").val(0);							
						$("#txt_igst").val(0);
					}
					
				}			
				unloading();
			}
		});   	
	}
	auto_complete_intialize(1);
}


function get_inv_no_by_cmpny_id(cmpny_id){
	var financial_id =  $('#financial_id').val();
	if(cmpny_id !=''){					
		$.ajax({		
			url        : 'ajax_actions.php',
			method     : 'POST',
			dataType   : 'json',
			data       : 'action=get_inv_no_by_company_id&company_id='+cmpny_id+'&financial_id='+financial_id,
			beforeSend: function() { loading(); },
			success: function(response){
				$("#txt_inv_no").val(response.rslt);
				$("#sku_last_id").html("Last Sku: "+response.pdt_sku);

				unloading();
			}		
		});
	}
}

function auto_complete_intialize(rw_cnt){		
	$('.autocmplte_sareedesc').autocomplete({ 
		width:400,
		lookup: function (query, done) {		
			$.ajax({
				url  : "autocomplete_actions.php?pageaction=autocomplete_purchase_entry&srch_type=saree_desc&supplier="+$("#sel_supplier").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);
		}
	});
}

</script>



</body>
</html>
	  