<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/cartfunctions.php');
include ('../inc/repfunctions.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];    
$today = strftime("%Y-%m-%d", time());    
$dtnow = date("Y-m-d h:i:s", time());    
}else{
header('Location:../index.php');
exit;    
}

if(isset($_POST['addretinv'])){
$inv=$_POST['addretinv'];

read_pureturndata($inv);
$sql="SELECT * FROM tbl_purchase WHERE invno='$inv' LIMIT 1";    
$selre=mysqli_query($con,$sql) or die(mysqli_error($con));    
$ret=mysqli_fetch_array($selre);    
$_SESSION['pureturninv']=$ret['id'];    
}

if(isset($_POST['invsear'])){
$search = $_POST['search'];
$sql = "SELECT invno,name FROM tbl_purchase LEFT JOIN tbl_supplier ON tbl_supplier.id=tbl_purchase.supid WHERE invno LIKE '%$search%' LIMIT 15";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['invno'],"label"=>$row['invno'].' | '.$row['name']);
}

echo json_encode($response);
exit;    
}

if(isset($_POST['srlsear'])){
$search = $_POST['search'];
$sql = "SELECT purinv AS invno,serial,name FROM tbl_serial LEFT JOIN tbl_item ON tbl_item.id=tbl_serial.pid WHERE tbl_serial.rci='Y' AND tbl_serial.status='0' AND tbl_serial.serial LIKE '%$search%' LIMIT 15";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['invno'],"label"=>$row['invno'].' | '.$row['name'].' | '.$row['serial']);
}

echo json_encode($response);
exit;    
}

if(isset($_POST['upreqty'])){
$ids=intval($_POST['upreqty']);
$qty=$_POST['qty'];
if($qty<0 || $qty==''){
$redata=array($_SESSION['axes_pureturn'][$ids]['rqty'],$_SESSION['axes_pureturn'][$ids]['subtot']);
echo json_encode($redata);    
exit;
}
$unqid = $_SESSION['axes_pureturn'][$ids]['unqid'];
$sold = $_SESSION['axes_pureturn'][$ids]['qty'];   
$prqty = $_SESSION['axes_pureturn'][$ids]['prqty'];
$eqty=($sold-$prqty);    
if($qty<=$eqty){
$_SESSION['axes_pureturn'][$ids]['rqty']=$qty;		
}   
$cost = $_SESSION['axes_pureturn'][$ids]['cost'];
$sqty = $_SESSION['axes_pureturn'][$ids]['rqty'];
$dis = $_SESSION['axes_pureturn'][$ids]['disf'];    
$disamo = getfloatval(($dis*$sqty));
$stot = ($cost*$sqty);
if($cost>0){
$disp=(($dis/$cost)*100);
}else{
$disp=0;	
}
$_SESSION['axes_pureturn'][$ids]['disamo']=$disamo;
$_SESSION['axes_pureturn'][$ids]['subtot'] = getfloatval(($stot-$disamo));
$redata=array($_SESSION['axes_pureturn'][$ids]['rqty'],$_SESSION['axes_pureturn'][$ids]['subtot']);
echo json_encode($redata);
}

if(isset($_POST['check'])){
$ids=$_POST['pid'];
$val=$_POST['check'];
$max=count($_SESSION['axes_pureturnse']);
for($i=0;$i<$max;$i++){
if($ids==$i){
$pid=$_SESSION['axes_pureturnse'][$i]['pid'];
$erqty=pureserial_count($pid);
$irqty=get_pureturncartqty($pid);
if($irqty>0 && $erqty<$irqty){
$_SESSION['axes_pureturnse'][$i]['check']=$val;    
}else{
$_SESSION['axes_pureturnse'][$i]['check']=0;    
}    	
}	
}
$redata=array($_SESSION['axes_pureturnse'][$ids]['check']);
echo json_encode($redata);    
}

if(isset($_POST['less'])){
$less=floatval($_POST['less']);
if(isset($_SESSION['axes_pureturnde'])){
if($less>0){
$_SESSION['axes_pureturnde'][0]['less']= getfloatval($less);    
}else{    
$_SESSION['axes_pureturnde'][0]['less']= 0;   
}
}
}

if(isset($_SESSION['axes_pureturnde'])){
if(is_array($_SESSION['axes_pureturnde'])){ 
$disps=$_SESSION['axes_pureturnde'][0]['disp'];
if($disps>0){
$_SESSION['axes_pureturnde'][0]['disamo']=getfloatval(get_puretdiscount_total(floatval($disps)));	
}else{
$_SESSION['axes_pureturnde'][0]['disamo']=getfloatval(get_puretdiscount_total());	
}
$vatps=$_SESSION['axes_pureturnde'][0]['vatp'];
if($vatps>0){
$_SESSION['axes_pureturnde'][0]['vatamo']= getfloatval(((get_pureturn_total()-(get_puretdiscount_total($disps)- get_puretdiscount_total()))*$vatps)*0.01);	
}
$taxps=$_SESSION['axes_pureturnde'][0]['taxp'];
if($taxps>0){
$_SESSION['axes_pureturnde'][0]['taxamo']= getfloatval(((get_pureturn_total()-(get_puretdiscount_total($disps)- get_puretdiscount_total()))*$taxps)*0.01);	
}    
$vatamos=$_SESSION['axes_pureturnde'][0]['vatamo'];
$taxamos=$_SESSION['axes_pureturnde'][0]['taxamo'];
$disps=$_SESSION['axes_pureturnde'][0]['disp'];
$invdue=$_SESSION['axes_pureturnde'][0]['invdue'];    
$lesss=$_SESSION['axes_pureturnde'][0]['less'];    
}else{
$vatamos=0;
$taxamos=0;
$disps=0;
$invdue=0;    
$lesss=0;
}
$gtotal=getfloatval(get_pureturn_total()+$vatamos+$taxamos)-((get_puretdiscount_total(floatval($disps))- get_puretdiscount_total())+$lesss);
if($gtotal<=$invdue){
$_SESSION['axes_pureturnde'][0]['adjdue']=$gtotal;
$_SESSION['axes_pureturnde'][0]['gtotal']=0;    
}elseif($gtotal>$invdue){
$_SESSION['axes_pureturnde'][0]['adjdue']=$invdue;    
$_SESSION['axes_pureturnde'][0]['gtotal']=getfloatval($gtotal-$invdue);    
}    

}

if(isset($_POST['purdata'])){
$edata=array(
check_pureturn_err(),pureturn_totqty());
echo json_encode($edata);
}

if(isset($_POST['addreturn'])){
$invno = gen_newinvno(' tbl_preturn','PRE');
$refinv = remove_junk(escape($_SESSION['axes_pureturnde'][0]['invno']));   
$apdate = remove_junk(escape($_POST['retdt']));
$nxtdt = remove_junk(escape($_POST['nxtdt']));
    
$cty=$_SESSION['axes_pureturnde'][0]['type'];    
$cid =$_SESSION['axes_pureturnde'][0]['cusid'];
$ddata=explode('_',remove_junk(escape($_POST['did'])));
$dty=$ddata['0'];    
$did = $ddata['1'];    
$chkno = remove_junk(escape($_POST['chkno']));
$chkdt = remove_junk(escape($_POST['chkdt']));
$trxid = remove_junk(escape($_POST['trxid']));

if($dty=='BA'){
$debitid=remove_junk(escape($_POST['did']));
$details="'".'CHK_'.$chkno.'_'.$chkdt."'";        
}elseif($dty=='MO'){
$debitid=remove_junk(escape($_POST['did']));
$details="'".'MOB_'.$trxid."'";    
}else{
$debitid='LE_2';
$details='NULL';    
}    
    
if($chkno=='' || strlen($chkno)<2){$chkdt='NULL';$chkno='NULL';}else{$chkdt="'".$chkdt."'";$chkno="'".$chkno."'";}    
$amo = remove_junk(escape($_POST['amo']));
if($amo==''){$amo=0;} 
$adjust = remove_junk(escape($_POST['adj']));
if($adjust==''){$adjust=0;}    
$note = remove_junk(escape($_POST['note']));

$itmdis=remove_junk(escape(get_puretdiscount_total()));    
$disp=remove_junk(escape($_SESSION['axes_pureturnde'][0]['disp']));
$disamo=remove_junk(escape($_SESSION['axes_pureturnde'][0]['disamo']));   
$vatp=remove_junk(escape($_SESSION['axes_pureturnde'][0]['vatp']));
$vatamo=remove_junk(escape($_SESSION['axes_pureturnde'][0]['vatamo']));
$taxp=remove_junk(escape($_SESSION['axes_pureturnde'][0]['taxp']));
$taxamo=remove_junk(escape($_SESSION['axes_pureturnde'][0]['taxamo']));
$less=remove_junk(escape($_SESSION['axes_pureturnde'][0]['less']));
$subtot=get_pureturn_total();
$adamo=remove_junk(escape($_SESSION['axes_pureturnde'][0]['adjdue']));    
$gtotal=remove_junk(escape($_SESSION['axes_pureturnde'][0]['gtotal']));
if($disp>0){
$invdis=($disamo-$itmdis);    
}else{
$invdis=0;    
}    

if(($adjust+$amo)>=$gtotal){
$rcash=($gtotal-$adjust);
$change=(($adjust+$amo)-$gtotal);
$due=0;
$duedt='NULL';    
}else{
$rcash=$amo;
$change=0;
$due=($gtotal-($adjust+$amo));
$duedt="'".$nxtdt."'";    
}    
    
if(!isset($_SESSION['axes_pureturn'])){
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! No item found!!'
));
return;
exit;  
}     

$sql="INSERT INTO  tbl_preturn (invno,refinv,type,cusid,name,mobile,itemdis,subtot,disp,disamo,totdis,vatp,vatamo,taxp,taxamo,less,adjust,adamo,total,note,apdate,nxtduedate,rawcash,changes,debitid,details,brid,uid,date) VALUES ('$invno','$refinv','$cty','$cid',NULL,NULL,'$itmdis','$subtot','$disp','$invdis','$disamo','$vatp','$vatamo','$taxp','$taxamo','$less','$adamo','$adjust','$gtotal','$note','$apdate',$duedt,'$amo','$change','$debitid',$details,'$brid','$aid','$dtnow')";
   
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sid=$con->insert_id;    
$efid=mysqli_affected_rows($con);    

if($efid>0){
$max=count($_SESSION['axes_pureturn']);
for($i=0;$i<$max;$i++){
$pid = $_SESSION['axes_pureturn'][$i]['pid'];
$unqid= $_SESSION['axes_pureturn'][$i]['unqid'];   
$col=$_SESSION['axes_pureturn'][$i]['col'];
$siz=$_SESSION['axes_pureturn'][$i]['siz'];
$cost=$_SESSION['axes_pureturn'][$i]['cost'];
$puqty=0;    
$qtyin=0;
$soqty=0;    
$qtyout=$_SESSION['axes_pureturn'][$i]['rqty'];
$taxp=0;
$taxamo=0;
$idisp=$_SESSION['axes_pureturn'][$i]['disp'];
$idisf=$_SESSION['axes_pureturn'][$i]['disf'];
$disamo=$_SESSION['axes_pureturn'][$i]['disamo'];
$sdisp=0;
$sdisf=0;
$price=$_SESSION['axes_pureturn'][$i]['price'];
$isubtot=$_SESSION['axes_pureturn'][$i]['subtot'];
$wday=$_SESSION['axes_pureturn'][$i]['wday'];
$pnote=$_SESSION['axes_pureturn'][$i]['pnote'];    
    
$sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,colid,sizid,cost,price,p_qty,p_in,s_qty,p_out,taxp,taxamo,disp,disf,disamo,subtot,wday,mods,brid,waid,tramod,isinv,pnote,uid,apdate,date) VALUES ('$cty','$cid','$invno','$refinv','$pid','$unqid','$col','$siz','$cost','$price','$puqty','$qtyin','$soqty','$qtyout','$taxp','$taxamo','$idisp','$idisf','$disamo','$isubtot','$wday','PR','$brid',NULL,NULL,'Y',NULL,'$aid','$apdate','$dtnow')";
if($qtyout>0){    
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
}
}

if(isset($_SESSION['axes_pureturnse'])){
$max=count($_SESSION['axes_pureturnse']);
for($i=0;$i<$max;$i++){
$pid=$_SESSION['axes_pureturnse'][$i]['pid'];   
$serial=$_SESSION['axes_pureturnse'][$i]['serial'];
$check=$_SESSION['axes_pureturnse'][$i]['check'];
if($check==1){    
$sql="UPDATE tbl_serial SET reinvno='$invno',status='2' WHERE serial='$serial'";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
}
}    
}
//purchret_update($sid,'tbl_preturn',$dtnow);
unset($_SESSION['axes_pureturn']);
unset($_SESSION['axes_pureturnde']);
if(isset($_SESSION['pureturninv'])){    
unset($_SESSION['pureturninv']);
}
if(isset($_SESSION['axes_pureturnse'])){
unset($_SESSION['axes_pureturnse']);
}    
    
$act =remove_junk(escape('Return Invoice: '.$invno));    
write_activity($aid,'PRE','New return invoice has been Created',$act);
echo json_encode(array(
'status' => 'success',
'message'=> 'Return Save Successfully!!'   
));
exit;    
}else{
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! Data Fail to Saved!!'
));    
}    
    
}
?>

<?php 
if(isset($_POST['saveret'])){
if(isset($_SESSION['axes_pureturnde'])){    
$total=$_SESSION['axes_pureturnde'][0]['gtotal'];   
}else{
$total=0.00;    
}
$id=$_SESSION['axes_pureturnde'][0]['type'].$_SESSION['axes_pureturnde'][0]['cusid'];
$cusid=$_SESSION['axes_pureturnde'][0]['cusid'];
$indue=$_SESSION['axes_pureturnde'][0]['invdue'];    
$ldebit=get_ledgerval($id,'D','N');
$lcredit=get_ledgerval($id,'C','N');
if($cusid!=0){
$lnet=($ldebit-$lcredit);
if($lnet<0){
$lnet=($lnet+$indue);    
}else{
$lnet=($lnet-$indue);    
}    
}else{
$lnet=0;    
}    
?>    
<div class="col-md-12 popup_details_div addpurchase">
<div class="row">
<div class="form-group text-center">
Total Receivable: <span style="font-size: 22px;font-weight: bold;color: blue;"><?php echo number_format($total,2); ?></span>    
</div>    
</div>
<div class="row">
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="row">
<div class="col-md-6">    
<div class="form-group" >
<label>Return Date</label>
<input type="text" class="form-control datetimepicker" name="retdt" id="retdt" value="<?php echo $today;?>" placeholder="Return Date" autocomplete="off" readonly>
</div>
</div>
<div class="col-md-6">    
<div class="form-group" >
<label>Next Receiv Date</label>
<input type="text" class="form-control datetimepicker" name="nxtdt" id="nxtdt" value="<?php echo date('Y-m-d', strtotime('+7 days',strtotime($today)));?>" placeholder="Due Date" autocomplete="off" readonly>
</div>
</div>     
</div>    
    
<div class="form-group">
<label>Return To</label>    
<select class="form-control select2" name="did" id="did">
<option value="LE_2">Cash</option>    
<?php
$sql="SELECT tbl_bacount.id,CONCAT(tbl_bank.sort,' - ',tbl_bacount.acno) AS name FROM tbl_bacount LEFT JOIN tbl_bank ON tbl_bank.id=tbl_bacount.bid ORDER BY tbl_bank.sort ASC";    
$querys=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rows=mysqli_fetch_array($querys)){
?>
<option value="<?php echo 'BA_'.$rows['id'];?>"><?php echo $rows['name'];?></option>
<?php } ?>
<?php
$sql="SELECT id,name,mobile FROM tbl_acmobile ORDER BY name ASC";    
$querys=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rows=mysqli_fetch_array($querys)){
?>
<option value="<?php echo 'MO_'.$rows['id'];?>"><?php echo $rows['name'].' - '.$rows['mobile'];?></option>
<?php } ?>    
</select>
<input type="hidden" name="addreturn" readonly />  
</div>
<div class="form-group">
<label>Cheque No</label>
<input type="text" maxlength="20" class="form-control" name="chkno" id="chkno" value="" placeholder="e.g. KA7865467" autocomplete="off" disabled="disabled">
</div>
<div class="form-group" >
<label>Cheque Date</label>
<input type="text" class="form-control datetimepicker" name="chkdt" id="chkdt" value="" placeholder="Cheque Date" autocomplete="off" disabled="disabled" readonly>
</div>
<div class="form-group">
<label>TrxID</label>
<input type="text" maxlength="20" class="form-control" name="trxid" id="trxid" value="" placeholder="e.g. KA7865467" autocomplete="off" disabled="disabled">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Balance(<?php echo $lnet;?>)</label>
<?php 
$adv=0;
if($lnet<0){
$ad=ABS($lnet);
if($ad>=$total){$adv=$total;}else{$adv=$ad;}    
}else{
$adv=0;    
}    
?>    
<input type="text" maxlength="10" class="form-control" value="<?php echo $adv; ?>" name="adj" id="adj"  onkeypress="return isNumberKey(event)" placeholder="e.g. 500" autocomplete="off" <?php if($lnet>=0){echo 'disabled';}?>>
<input type="hidden" value="<?php if($lnet<0){echo ABS($lnet);}else{echo 0;} ?>" id="balance" name="balance" readonly />    
</div>    
</div>
<div class="col-md-6">
<div class="form-group">
<label>Cash</label>    
<input type="text" maxlength="10" class="form-control" name="amo" id="amo"  onkeypress="return isNumberKey(event)" placeholder="e.g. 500" autocomplete="off"> 
<input type="hidden" value="<?php echo $total; ?>" id="reamo" name="reamo" readonly />    
</div>    
</div>    
</div>    

<div class="form-group">
<label>Note</label>
<textarea class="form-control" maxlength="150" rows="3" name="note" placeholder="Note"></textarea>
</div>    
</div>    
<div class="col-md-1"></div>    
</div>    
</div>    

</div>
<div class="clearfix" ></div>
<div class="col-md-12 nopadding widgets_area"></div>    
<div class="row"style="margin-top: 15px" >
<div class="col-md-8"></div>
<div class="col-md-4 text-right" >
<input type="button" id="finret" class="btn btn-flat bg-purple btn-sm " value="Save Return"/>
</div> 
</div>

<script type="text/javascript">
function chek_error(){
var did = $('#did').val();
var chkno = $('#chkno').val();
var chkdt = $('#chkdt').val();
var seldt = $('#retdt').val();
var trxid = $('#trxid').val();    
var result = true;    
ty = did.split("_");
type=ty[0];
$('.LV_invalid_field').removeClass('LV_invalid_field');     
$('.LV_validation_message').remove();    

if(retdt.length<=0){
$('#retdt').addClass('LV_invalid_field');   
$('#retdt').after("<span class='LV_validation_message LV_invalid'>Enter Sales Date!</span>").addClass('has-error');
result=false;    
}else{
$('#retdt').removeClass('LV_invalid_field');
result=true;    
}    
    
if(did == '-Select-' || did == ''){
$('#did').addClass('LV_invalid_field');   
$('#did').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); 
result=false;
} else {
$('#did').removeClass('LV_invalid_field');
result=true;    
}     

if(type=='BA'){    
if(chkno.length>=0 && chkno.length<5){
$('#chkno').addClass('LV_invalid_field');   
$('#chkno').after("<span class='LV_validation_message LV_invalid'>Enter Valid Cheque No!</span>").addClass('has-error'); 
result=false;
}else{
$('#chkno').removeClass('LV_invalid_field');
result=true;    
}    

if(chkno.length>0){
if(chkdt.length<=0){
$('#chkdt').addClass('LV_invalid_field');   
$('#chkdt').after("<span class='LV_validation_message LV_invalid'>Enter Cheque Date!</span>").addClass('has-error');
result=false;    
}else{
$('#chkdt').removeClass('LV_invalid_field');
result=true;    
}    
}    
}    

if(type=='MO'){
if(trxid.length<=0){
$('#trxid').addClass('LV_invalid_field');   
$('#trxid').after("<span class='LV_validation_message LV_invalid'>Enter Transaction ID!</span>").addClass('has-error');
result=false;    
}else{
$('#trxid').removeClass('LV_invalid_field');
result=true;    
}    
}    
    
if(!result){
return false;    
}else{
return true;     
}    
   
}
    
$(document).on('change', '#did', function() {
id_arr = $(this).val();
id = id_arr.split("_");
type=id[0];
if(type=='BA'){
document.getElementById("chkno").disabled=false; 
document.getElementById("chkdt").disabled=false;
$('#trxid').val('');    
document.getElementById("trxid").disabled=true;    
}else if(type=='MO'){
document.getElementById("trxid").disabled=false;     
$('#chkno').val('');
$('#chkdt').val('');    
document.getElementById("chkno").disabled=true; 
document.getElementById("chkdt").disabled=true;    
}else{    
$('#chkno').val('');
$('#chkdt').val('');
$('#trxid').val('');     
document.getElementById("chkno").disabled=true; 
document.getElementById("chkdt").disabled=true;
document.getElementById("trxid").disabled=true;     
}    
});
    
$(document).on('blur', '#amo, #did, #chkno, #chkdt, #trxid', function() {
chek_error();    
});
    
function cashcalculation(){
var pab = parseFloat($('#reamo').val());
var cash = parseFloat($('#amo').val());
var adv = parseFloat($('#balance').val());
var adj = parseFloat($('#adj').val());    
var paid=0;
   
if(isNaN(cash)){
cash=0;    
}
if(isNaN(adj)){
adj=0;    
}
    
if((cash+adj)<=pab){
paid=cash;    
}else{
paid=(pab-adj);    
}
$('#amo').val(paid); 
}

$(document).on('keyup', '#amo', function() { 
cashcalculation();
});
    
$(document).on('keyup', '#adj', function() {
var pab = parseFloat($('#reamo').val());    
var adv = parseFloat($('#balance').val());
var adj = parseFloat($('#adj').val());    
var maxad = 0;
if(pab<=adv){
maxad=pab;
}else{
maxad=adv;    
}
if(adj>maxad){
$('#adj').val(maxad);    
}    
cashcalculation();
});    
    
$(".select2").select2(); 
$('.datetimepicker').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto bottom'});    
</script>    
<?php } ?>