<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/cartfunctions.php');
include ('../inc/repfunctions.php');
include ('../inc/invfunctions.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['additem'])){
$unqid=$_POST['additem'];   
addtosel($brid,$unqid,1);    
}

if(isset($_POST['tyserial'])){
$serial = $_POST['search'];
$sql="SELECT tbl_stock.unqid,tbl_stock.price,tbl_item.name,tbl_serial.serial FROM tbl_serial LEFT JOIN tbl_stock ON tbl_stock.invno=tbl_serial.purinv AND tbl_stock.pid=tbl_serial.pid LEFT JOIN tbl_item ON tbl_item.id=tbl_serial.pid WHERE tbl_serial.serial LIKE '%$serial%' AND tbl_serial.rci='Y' AND tbl_serial.brid='$brid' AND tbl_serial.status='0' LIMIT 20";    
$result = mysqli_query($con,$sql) or die(mysqli_error($con));



while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['unqid'],"label"=>$row['serial']);
}

echo json_encode($response);
exit;    
}

if(isset($_POST['addslitem'])){
$unqid=$_POST['addslitem'];
$serial=$_POST['serial'];

$sql="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND unqid='".$unqid."' AND avqty>0 AND status='1' LIMIT 1";	
$resl=mysqli_query($con,$sql) or die(mysqli_error($con));
$pid=get_fild_data('tbl_stock','','pid',"unqid='$unqid'"); 
if($resl->num_rows>0){   
if(selimei_exists($pid,$serial)){
return;
exit;    
} 
addtosel($brid,$unqid,1);   
add_selserial($pid,$unqid,$serial,'B');   

}else{

  $sqld="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND pid='$pid' AND avqty>0 AND status='1' LIMIT 1";	
  $resld=mysqli_query($con,$sqld) or die(mysqli_error($con));
  if($resld->num_rows>0){
    $rowpd = mysqli_fetch_array($resld);
    if(selimei_exists($rowpd['pid'],$serial)){
      $pmsg=array(
      'status' => 'exits',
      'message'=> 'Serial / IMEI already Added!!'    
      );
      echo json_encode($pmsg);
      return;    
    }
    if(selimei_pidewos($rowpd['unqid'])>0){
      $sid=selimei_pidewos($rowpd['unqid'])-1;    
      $_SESSION['axes_selse'][$sid]['imei']=$serial;
      $pmsg=array(
      'status' => 'success',
      'message'=> 'Serial Add to cart Successfully!!'    
      );
      echo json_encode($pmsg);
      return;    
    }else{    
      addtosel($brid,$rowpd['unqid'],1,'A');
      add_selserial($rowpd['pid'],$rowpd['unqid'],$serial,'B');    
      $pmsg=array(
      'status' => 'success',
      'message'=> 'Product Add to cart Successfully!!'    
      );
      echo json_encode($pmsg);
      return;
    }
  }else{
    $pmsg=array(
      'status' => 'exits',
      'message'=> 'Product Is Not Available!!'    
      );

  }

} 
 
}







// if(isset($_POST['itmsear'])){
// $search = $_POST['search'];
// $sql = "SELECT tbl_brstock.unqid,tbl_brstock.code,tbl_brstock.name,tbl_stock.cost,tbl_stock.price,tbl_brstock.avqty FROM tbl_brstock LEFT JOIN tbl_stock ON tbl_stock.unqid=tbl_brstock.unqid WHERE tbl_brstock.brid='$brid' AND tbl_brstock.status='1' AND (tbl_brstock.name LIKE '%$search%' OR tbl_brstock.code LIKE '%$search%') AND tbl_brstock.avqty>0 LIMIT 20";
// $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
// while($row = mysqli_fetch_array($result) ){
// $response[] = array("value"=>$row['unqid'],"label"=>$row['code'].' | '.$row['name'].' | Qty:'.$row['avqty'].' | '.$row['price']);
// }

// echo json_encode($response);
// exit;    
// }

//old scan barcode system

// if(isset($_POST['scanbarcode'])){
//   $out='';	
//   $bcode=strtoupper(remove_junk(escape($_POST['scanbarcode'])));
//   $qty=$_POST['qty'];    
//   $type=substr($bcode,0,3);
//   if(substr($type,0,2)==='OU'){$type='JOU';$bcode='J'.$bcode;}    
//   $parray = array('EMP','JOU','REV','PAV','EXP','PRE','PUR','POR','SRE','SEL','EST','SER','RCI','DLI','PDR','CLA','TRB','TRW');     
//   if(strlen(array_search($type,$parray))>0){
//   $pmsg=array(
//   'status' => 'invno',
//   'invoice'=> $bcode    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }    
      
//   $sql="SELECT tbl_stock.unqid FROM tbl_serial LEFT JOIN tbl_stock ON tbl_stock.invno=tbl_serial.purinv AND tbl_stock.pid=tbl_serial.pid WHERE tbl_serial.serial='$bcode' AND tbl_serial.rci='Y' AND tbl_serial.status='0' LIMIT 1";
//   $result=mysqli_query($con,$sql) or die(mysqli_error($con));
//   if($result->num_rows > 0){
//   $rowsl = mysqli_fetch_array($result);
//   $sql="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND unqid='".$rowsl['unqid']."' AND avqty>0 AND status='1' LIMIT 1";		
//   $resl=mysqli_query($con,$sql) or die(mysqli_error($con));
//   $rowp = mysqli_fetch_array($resl);
//   if(selimei_exists($rowp['pid'],$bcode)){
//   $pmsg=array(
//   'status' => 'exits',
//   'message'=> 'Serial / IMEI already Added!!'    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }
//   if(selimei_pidewos($rowp['unqid'])>0){
//   $sid=selimei_pidewos($rowp['unqid'])-1;    
//   $_SESSION['axes_selse'][$sid]['imei']=$bcode;
//   $pmsg=array(
//   'status' => 'success',
//   'message'=> 'Serial Add to cart Successfully!!'    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }else{    
//   addtosel($brid,$rowp['unqid'],1,'A');
//   add_selserial($rowp['pid'],$rowp['unqid'],$bcode,'B');    
//   $pmsg=array(
//   'status' => 'success',
//   'message'=> 'Product Add to cart Successfully!!'    
//   );
//   echo json_encode($pmsg);
//   return;
//   }
//   }else{
//   $bt=substr($bcode,0,2);    
//   if($bt=='GP'){
//   $sql="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND unqid='$bcode' AND avqty>0 AND status='1' LIMIT 1";
//   $result=mysqli_query($con,$sql) or die(mysqli_error($con));
//   if($result->num_rows > 0){
//   $rowgp = mysqli_fetch_array($result);    
//   addtosel($brid,$rowgp['unqid'],1);
//   $pmsg=array(
//   'status' => 'success',
//   'message'=> 'Product Add to cart Successfully!!'    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }else{
//   $pmsg=array(
//   'status' => 'fail',
//   'message'=> 'No item found!!'    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }
//   }else{
//   $sql="SELECT tbl_brstock.pid,tbl_brstock.name,tbl_brstock.code,tbl_brstock.unqid,tbl_stock.price FROM tbl_brstock LEFT JOIN tbl_item ON tbl_item.id=tbl_brstock.pid LEFT JOIN tbl_stock ON tbl_stock.unqid=tbl_brstock.unqid WHERE tbl_brstock.brid='$brid' AND tbl_brstock.avqty>0 AND tbl_brstock.status='1' AND  tbl_item.barcode='$bcode'";
//   $result=mysqli_query($con,$sql) or die(mysqli_error($con));
//   if($result->num_rows > 0){
//   $fitem=$result->num_rows;    
//   if($fitem > 1){
//   $out.='<br>';
//   while($row = mysqli_fetch_array($result)){
//   $out.='<input type="radio" name="prorbuton" class="prorbuton" value="'.$row['unqid'].'" onclick="myFunctions(this.value)">'.' '.$row['code'].' - '.$row['name'].' - '.$row['price'].'<br>';	
//   }
//   $pmsg=array(
//   'status' => 'multi',
//   'html'=> $out    
//   );
//   echo json_encode($pmsg);
//   return;        
//   }else{
//   $row = mysqli_fetch_array($result);
//   addtosel($brid,$row['unqid'],1,'B');
//   $pmsg=array(
//   'status' => 'success',
//   'message'=> 'Product Add to cart Successfully!!'    
//   );
//   echo json_encode($pmsg);
//   return;    
//   }    
//   }else{
//   $pmsg=array(
//   'status' => 'fail',
//   'message'=> 'No item found!!'    
//   );
//   echo json_encode($pmsg);    
//   }
//   }	
//   }
//   }


if(isset($_POST['scanbarcode'])){
$out='';	
$bcode=strtoupper(remove_junk(escape($_POST['scanbarcode'])));
$qty=$_POST['qty'];    
$type=substr($bcode,0,3);
if(substr($type,0,2)==='OU'){$type='JOU';$bcode='J'.$bcode;}    
$parray = array('EMP','JOU','REV','PAV','EXP','PRE','PUR','POR','SRE','SEL','EST','SER','RCI','DLI','PDR','CLA','TRB','TRW');     
if(strlen(array_search($type,$parray))>0){
$pmsg=array(
'status' => 'invno',
'invoice'=> $bcode    
);
echo json_encode($pmsg);
return;    
}  

$newbcode = substr($bcode, -5);
    
$sql="SELECT tbl_stock.unqid,tbl_stock.pid,tbl_serial.serial FROM tbl_serial LEFT JOIN tbl_stock ON tbl_stock.invno=tbl_serial.purinv AND tbl_stock.pid=tbl_serial.pid WHERE tbl_serial.serial='$bcode' OR tbl_serial.serial LIKE '%$newbcode' AND tbl_serial.rci='Y' AND tbl_serial.status='0' LIMIT 1";
$result=mysqli_query($con,$sql) or die(mysqli_error($con));
if($result->num_rows > 0){
    $rowsl = mysqli_fetch_array($result);
    $serial=$rowsl['serial'];

    $sql="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND unqid='".$rowsl['unqid']."' AND avqty>0 AND status='1' LIMIT 1";	
    $resl=mysqli_query($con,$sql) or die(mysqli_error($con));
        if($resl->num_rows>0){
            $rowp = mysqli_fetch_array($resl);
          
            if(selimei_exists($rowp['pid'],$serial)){
              $pmsg=array(
              'status' => 'exits',
              'message'=> 'Serial / IMEI already Added!!'    
              );
              echo json_encode($pmsg);
              return;    
            }
            if(selimei_pidewos($rowp['unqid'])>0){
              $sid=selimei_pidewos($rowp['unqid'])-1;    
              $_SESSION['axes_selse'][$sid]['imei']=$serial;
              $pmsg=array(
              'status' => 'success',
              'message'=> 'Serial Add to cart Successfully!!'    
              );
              echo json_encode($pmsg);
              return;    
            }else{    
              addtosel($brid,$rowp['unqid'],1,'A');
              add_selserial($rowp['pid'],$rowp['unqid'],$serial,'B');    
              $pmsg=array(
              'status' => 'success',
              'message'=> 'Product Add to cart Successfully!!'    
              );
              echo json_encode($pmsg);
              return;
            }

        }else{

          $sqld="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND pid='".$rowsl['pid']."' AND avqty>0 AND status='1' LIMIT 1";	
          $resld=mysqli_query($con,$sqld) or die(mysqli_error($con));
          $rowpd = mysqli_fetch_array($resld);
          if(selimei_exists($rowpd['pid'],$serial)){
            $pmsg=array(
            'status' => 'exits',
            'message'=> 'Serial / IMEI already Added!!'    
            );
            echo json_encode($pmsg);
            return;    
          }
          if(selimei_pidewos($rowpd['unqid'])>0){
            $sid=selimei_pidewos($rowpd['unqid'])-1;    
            $_SESSION['axes_selse'][$sid]['imei']=$serial;
            $pmsg=array(
            'status' => 'success',
            'message'=> 'Serial Add to cart Successfully!!'    
            );
            echo json_encode($pmsg);
            return;    
          }else{    
            addtosel($brid,$rowpd['unqid'],1,'A');
            add_selserial($rowpd['pid'],$rowpd['unqid'],$serial,'B');    
            $pmsg=array(
            'status' => 'success',
            'message'=> 'Product Add to cart Successfully!!'    
            );
            echo json_encode($pmsg);
            return;
          }

        }

}else{
  $bt=substr($bcode,0,2);    
  if($bt=='GP'){
    $sql="SELECT pid,unqid FROM tbl_brstock WHERE brid='$brid' AND unqid='$bcode' AND avqty>0 AND status='1' LIMIT 1";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
    if($result->num_rows > 0){
    $rowgp = mysqli_fetch_array($result);    
    addtosel($brid,$rowgp['unqid'],1);
    $pmsg=array(
    'status' => 'success',
    'message'=> 'Product Add to cart Successfully!!'    
    );
    echo json_encode($pmsg);
    return;    
    }else{
      $pmsg=array(
      'status' => 'fail',
      'message'=> 'No item found!!'    
      );
      echo json_encode($pmsg);
      return;    
    }
  }else{
    $sql="SELECT tbl_brstock.pid,tbl_brstock.name,tbl_brstock.code,tbl_brstock.unqid,tbl_stock.price FROM tbl_brstock LEFT JOIN tbl_item ON tbl_item.id=tbl_brstock.pid LEFT JOIN tbl_stock ON tbl_stock.unqid=tbl_brstock.unqid WHERE tbl_brstock.brid='$brid' AND tbl_brstock.avqty>0 AND tbl_brstock.status='1' AND  tbl_item.barcode='$bcode'";
    $result=mysqli_query($con,$sql) or die(mysqli_error($con));
    if($result->num_rows > 0){
      $fitem=$result->num_rows;    
      if($fitem > 1){
        $out.='<br>';
        while($row = mysqli_fetch_array($result)){
        $out.='<input type="radio" name="prorbuton" class="prorbuton" value="'.$row['unqid'].'" onclick="myFunctions(this.value)">'.' '.$row['code'].' - '.$row['name'].' - '.$row['price'].'<br>';	
        }
        $pmsg=array(
        'status' => 'multi',
        'html'=> $out    
        );
        echo json_encode($pmsg);
        return;        
      }else{
        $row = mysqli_fetch_array($result);
        addtosel($brid,$row['unqid'],1,'B');
        $pmsg=array(
        'status' => 'success',
        'message'=> 'Product Add to cart Successfully!!'    
        );
        echo json_encode($pmsg);
        return;    
      }    
    }else{
      $pmsg=array(
      'status' => 'fail',
      'message'=> 'No item found!!'    
    );
    echo json_encode($pmsg);    
    }
  }	
}
}


if(isset($_POST['itmsear'])){
$search = $_POST['search'];
$sql = "SELECT tbl_brstock.unqid,tbl_brstock.code,tbl_brstock.name,tbl_stock.cost,tbl_stock.price,tbl_brstock.avqty FROM tbl_brstock LEFT JOIN tbl_stock ON tbl_stock.unqid=tbl_brstock.unqid WHERE tbl_brstock.brid='$brid' AND tbl_brstock.status='1' AND (tbl_brstock.name LIKE '%$search%' OR tbl_brstock.code LIKE '%$search%') AND tbl_brstock.avqty>0 LIMIT 20";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
// while($row = mysqli_fetch_array($result) ){
// $response[] = array("value"=>$row['unqid'],"label"=>$row['code'].' | '.$row['name'].' | Qty:'.$row['avqty'].' | '.$row['price']);
// }

while($row = mysqli_fetch_array($result)){
  // Include HTML in the label
  $label = '<strong>' . $row['code'] . ' | ' . $row['name'] .'</strong>';
  $response[] = array(
      "value" => $row['unqid'],
      "label" => $label, // HTML included here
      "price" => $row['price'],
      "quantity" => $row['avqty'], // Add quantity
      "cost" => $row['cost'] // Add cost
  );
}

echo json_encode($response);
exit;    
}




if(isset($_POST['remove'])){
$ids = floatval($_POST['remove']);
$unqid=$_SESSION['axes_sales'][$ids]['unqid'];    
remove_sales($ids);
if(isset($_SESSION['axes_selse'])){    
remove_slimei($unqid);
}
$max=count($_SESSION['axes_sales']);
if($max <= 0){
unset($_SESSION['axes_sales']);
unset($_SESSION['axes_salesde']);
if(isset($_SESSION['axes_selse'])){
unset($_SESSION['axes_selse']);	
}	
}
if(isset($_SESSION['axes_selse'])){
$smax=count($_SESSION['axes_selse']);
if($smax <= 0){    
unset($_SESSION['axes_selse']);
}
}    
}

if(isset($_POST['upqty'])){
$ids=intval($_POST['upqty']);
$qty=floatval($_POST['qty']);
if($qty<0 || $qty==''){
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata);    
exit;
}
$unqid = $_SESSION['axes_sales'][$ids]['unqid'];
$eqty=(get_selestockinfo($brid,$unqid,'avqty')-get_selestockinfo($brid,$unqid,'sloc'));    
$dis = $_SESSION['axes_sales'][$ids]['disf'];
if($qty<=$eqty){
$_SESSION['axes_sales'][$ids]['qty']=$qty;
$_SESSION['axes_sales'][$ids]['check']='M';    
}elseif($qty>$eqty){
$_SESSION['axes_sales'][$ids]['qty']=$eqty;
$_SESSION['axes_sales'][$ids]['check']='M';    
}    
$price = $_SESSION['axes_sales'][$ids]['price'];
$sqty = $_SESSION['axes_sales'][$ids]['qty'];
$disamo = getfloatval(($dis*$sqty));
$stot = ($price*$sqty);
if($price>0){
$disp=(($dis/$price)*100);
}else{
$disp=0;	
}
$_SESSION['axes_sales'][$ids]['disp']=getfloatval($disp);
$_SESSION['axes_sales'][$ids]['disamo']=$disamo;
$_SESSION['axes_sales'][$ids]['subtot'] = getfloatval(($stot-$disamo));
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata);
}

if(isset($_POST['upprice'])){
$ids=intval($_POST['upprice']);
$amo=floatval($_POST['amo']);
if($amo<0 || $amo==''){
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata);    
exit;}
$qty=$_SESSION['axes_sales'][$ids]['qty'];
$dis=$_SESSION['axes_sales'][$ids]['disf'];
$_SESSION['axes_sales'][$ids]['price']=$amo;
$disamo= getfloatval(($dis*$qty));
$disp=(($dis/$amo)*100);
$_SESSION['axes_sales'][$ids]['disp']=getfloatval($disp);
$_SESSION['axes_sales'][$ids]['disamo']=$disamo;
$_SESSION['axes_sales'][$ids]['subtot']=(($amo*$qty)-$disamo);
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata);	
}

if(isset($_POST['check'])){
$ids=$_POST['pid'];
$val=$_POST['check'];
$max=count($_SESSION['axes_sales']);
for($i=0;$i<$max;$i++){
if($ids==$i){
$_SESSION['axes_sales'][$i]['check']=$val;	
}else{
$_SESSION['axes_sales'][$i]['check']=0;	
}	
}	
}

if(isset($_POST['upnote'])){
$ids=intval($_POST['upnote']);
$note=ucwords(remove_junk(escape($_POST['note'])));
$_SESSION['axes_sales'][$ids]['pnote']=$note;    
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata);    
}

if(isset($_POST['upwday'])){
  $ids=intval($_POST['upwday']);
  $wdays=floatval($_POST['wdays']);
  $_SESSION['axes_sales'][$ids]['wday']=$wdays;    
  $redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo'],$_SESSION['axes_sales'][$ids]['wday']);
  echo json_encode($redata);    
  }

if(isset($_POST['itemdisp'])){
$ids=intval($_POST['itemdisp']);
$disc=floatval($_POST['disp']);
//if( $disc==''){exit;}
$_SESSION['axes_sales'][$ids]['disp']=$disc;
$price=$_SESSION['axes_sales'][$ids]['price'];
$uqty=$_SESSION['axes_sales'][$ids]['qty'];
$dis=(($price*$disc)*0.01);
$disamo = ($dis*$uqty); 
$_SESSION['axes_sales'][$ids]['disf']=getfloatval($dis);
$_SESSION['axes_sales'][$ids]['disamo']=getfloatval($disamo);
$_SESSION['axes_sales'][$ids]['subtot']=(($price*$uqty)-$disamo);
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata); 
}

if(isset($_POST['itemdisf'])){
$ids=intval($_POST['itemdisf']);
$dica=floatval($_POST['disf']);
$price=$_SESSION['axes_sales'][$ids]['price'];
$uqty=$_SESSION['axes_sales'][$ids]['qty'];
$disp=(($dica/$price)*100);
$_SESSION['axes_sales'][$ids]['disf']=getfloatval($dica);
$disamo = ($dica*$uqty);
$_SESSION['axes_sales'][$ids]['disamo']=getfloatval($disamo);
if($dica<=0){
$_SESSION['axes_sales'][$ids]['disp']=getfloatval(0);	
}else{
$_SESSION['axes_sales'][$ids]['disp']=getfloatval($disp);	
}
$_SESSION['axes_sales'][$ids]['subtot']=(($price*$uqty)-$disamo);
$redata=array($_SESSION['axes_sales'][$ids]['qty'],$_SESSION['axes_sales'][$ids]['price'],$_SESSION['axes_sales'][$ids]['subtot'],$_SESSION['axes_sales'][$ids]['pnote'],$_SESSION['axes_sales'][$ids]['disp'],$_SESSION['axes_sales'][$ids]['disf'],$_SESSION['axes_sales'][$ids]['disamo']);
echo json_encode($redata); 
}

if(isset($_POST['foot'])){
$disp=$_SESSION['axes_salesde'][0]['disp'];
$redata=array($_SESSION['axes_salesde'][0]['disp'],(get_seldiscount_total(floatval($disp))-get_seldiscount_total()),get_seldiscount_total($disp),$_SESSION['axes_salesde'][0]['vatp'],$_SESSION['axes_salesde'][0]['vatamo'],$_SESSION['axes_salesde'][0]['aitp'],$_SESSION['axes_salesde'][0]['aitamo'],$_SESSION['axes_salesde'][0]['name'],$_SESSION['axes_salesde'][0]['others'],$_SESSION['axes_salesde'][0]['freight'],$_SESSION['axes_salesde'][0]['less'],$_SESSION['axes_salesde'][0]['gtotal']);
echo json_encode($redata);	
exit;
}

if(isset($_POST['seldis'])){
$disp=floatval($_POST['seldis']);
if(isset($_SESSION['axes_salesde'])){
if($disp>0){
$_SESSION['axes_salesde'][0]['disp']= getfloatval($disp);
$_SESSION['axes_salesde'][0]['disamo']=getfloatval(get_seldiscount_total(floatval($disp)));    
}else{    
$_SESSION['axes_salesde'][0]['disp']= getfloatval(0);
$_SESSION['axes_salesde'][0]['disamo']=getfloatval(0);    
}
}
}

if(isset($_POST['selvat'])){
$rvat=floatval($_POST['selvat']);
$disp=$_SESSION['axes_salesde'][0]['disp'];    
if(isset($_SESSION['axes_salesde'])){
if($rvat>0){	
$_SESSION['axes_salesde'][0]['vatp']= getfloatval($rvat);
$_SESSION['axes_salesde'][0]['vatamo']= getfloatval((((get_sales_total()-(get_seldiscount_total($disp)-get_seldiscount_total()))*$rvat)*0.01));    
}else{    
$_SESSION['axes_salesde'][0]['vatp']= 0;
$_SESSION['axes_salesde'][0]['vatamo']= 0;    
}
} 
}

if(isset($_POST['seltax'])){
$rtax=floatval($_POST['seltax']);
$disp=$_SESSION['axes_salesde'][0]['disp'];    
if(isset($_SESSION['axes_salesde'])){
if($rtax>0){	
$_SESSION['axes_salesde'][0]['aitp']= getfloatval($rtax);
$_SESSION['axes_salesde'][0]['aitamo']= getfloatval((((get_sales_total()-(get_seldiscount_total($disp)-get_seldiscount_total()))*$rtax)*0.01));    
}else{    
$_SESSION['axes_salesde'][0]['aitp']= 0;
$_SESSION['axes_salesde'][0]['aitamo']= 0;    
}
}
}

if(isset($_POST['others'])){
$ota=floatval($_POST['others']);
if(isset($_SESSION['axes_salesde'])){
$_SESSION['axes_salesde'][0]['others']=getfloatval($ota);	
}
}

if(isset($_POST['otname'])){
$otn=$_POST['otname'];
if($otn==''){return;}
if(isset($_SESSION['axes_salesde'])){
$_SESSION['axes_salesde'][0]['name']=ucwords($otn);	
}	
}

if(isset($_POST['freight'])){
$fre=floatval($_POST['freight']);
if(isset($_SESSION['axes_salesde'])){
$_SESSION['axes_salesde'][0]['freight']=getfloatval($fre);	
}
}

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

if(isset($_POST['removeitmsl'])){
$id=intval($_POST['removeitmsl']);
$unqid=$_SESSION['axes_selse'][$id]['unqid'];
$itid=get_cartitemid($unqid);
$itmqty=$_SESSION['axes_sales'][$itid]['qty'];

remove_selimei($id);    
if($itmqty<=1){
remove_sales($itid);    
}else{
$_SESSION['axes_sales'][$itid]['qty']=($itmqty-1);
$dis = $_SESSION['axes_sales'][$itid]['disf'];    
$price = $_SESSION['axes_sales'][$itid]['price'];
$sqty = $_SESSION['axes_sales'][$itid]['qty'];
$disamo = getfloatval(($dis*$sqty));
$stot = ($price*$sqty);
if($price>0){
$disp=(($dis/$price)*100);
}else{
$disp=0;	
}
$_SESSION['axes_sales'][$itid]['disp']=getfloatval($disp);
$_SESSION['axes_sales'][$itid]['disamo']=$disamo;
$_SESSION['axes_sales'][$itid]['subtot'] = getfloatval(($stot-$disamo));    
}
    
$max=count($_SESSION['axes_sales']);
if($max <= 0){
unset($_SESSION['axes_sales']);
unset($_SESSION['axes_salesde']);
if(isset($_SESSION['axes_selse'])){
unset($_SESSION['axes_selse']);	
}	
}    
}

if(isset($_POST['upimei'])){
$ids=intval($_POST['upimei']);
$serialno=strtoupper(remove_junk(escape($_POST['imeidata'])));
$pid=intval($_SESSION['axes_selse'][$ids]['pid']);
if($serialno!=''){
if(selimei_exists($pid,$serialno)){
$redata=array($_SESSION['axes_selse'][$ids]['imei']);
echo json_encode($redata);    
return;
exit;    
}
$_SESSION['axes_selse'][$ids]['imei']= $serialno;    
}else{
$_SESSION['axes_selse'][$ids]['imei']='';    
}    
$redata=array($_SESSION['axes_selse'][$ids]['imei']);
echo json_encode($redata); 
}

if(isset($_POST['audimei'])){
$id=$_POST['audimei'];
$pid=intval($_SESSION['axes_selse'][$id]['pid']);
$unqid=$_SESSION['axes_selse'][$id]['unqid'];    
$search = $_POST['search'];
$purinv=get_salesinfo($unqid,'invno');
    
$sql="SELECT pid,serial FROM tbl_serial WHERE purinv='$purinv' AND pid='$pid' AND serial LIKE '%$search%' AND brid='$brid' AND rci='Y' AND status='0' ORDER BY serial ASC LIMIT 30";		
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['pid'],"label"=>$row['serial']);
}

// encoding array to json format
echo json_encode($response);
exit;    
}

if(isset($_SESSION['axes_salesde'])){
if(is_array($_SESSION['axes_salesde'])){    
$disps=$_SESSION['axes_salesde'][0]['disp'];
if($disps>0){
$_SESSION['axes_salesde'][0]['disamo']=getfloatval(get_seldiscount_total(floatval($disps)));	
}else{
$_SESSION['axes_salesde'][0]['disamo']=getfloatval(get_seldiscount_total());	
}
$vatps=$_SESSION['axes_salesde'][0]['vatp'];
if($vatps>0){
$_SESSION['axes_salesde'][0]['vatamo']= getfloatval(((get_sales_total()-(get_seldiscount_total($disps)- get_seldiscount_total()))*$vatps)*0.01);	
}
$taxps=$_SESSION['axes_salesde'][0]['aitp'];
if($taxps>0){
$_SESSION['axes_salesde'][0]['aitamo']= getfloatval(((get_sales_total()-(get_seldiscount_total($disps)- get_seldiscount_total()))*$taxps)*0.01);	
}
$freight=$_SESSION['axes_salesde'][0]['freight'];
$vatamos=$_SESSION['axes_salesde'][0]['vatamo'];
$aitamos=$_SESSION['axes_salesde'][0]['aitamo'];
$other=$_SESSION['axes_salesde'][0]['others'];
$lesss=$_SESSION['axes_salesde'][0]['less'];    
}else{
$disps=0;
$vatps=0;
$vatamos=0;
$aitamos=0;
$freight=0;
$other=0;
$lesss=0;    
}
$_SESSION['axes_salesde'][0]['gtotal']=(get_sales_total()+$vatamos+$other+$aitamos+$freight)-((get_seldiscount_total(floatval($disps))- get_seldiscount_total())+$lesss);
}

if(isset($_POST['clear'])){
if(isset($_SESSION['axes_sales'])){
unset($_SESSION['axes_sales']);
unset($_SESSION['axes_salesde']);    
}
if(isset($_SESSION['axes_selse'])){
unset($_SESSION['axes_selse']);	
}
}

if(isset($_POST['getcus'])){
$search = $_POST['search'];
$sql="SELECT * FROM (SELECT CONCAT('CU_',id) AS id,code,name,cnumber FROM tbl_customer UNION ALL SELECT CONCAT('SU_',id) AS id,code,name,cnumber FROM tbl_supplier) AS customer WHERE (name LIKE '%$search%' OR code LIKE '%$search%' OR cnumber LIKE '%$search%') ORDER BY name ASC,code ASC LIMIT 30";		
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
    
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['id'],"label"=>$row['code'].' | '.$row['name'].' | '.$row['cnumber']);
}

// encoding array to json format
echo json_encode($response);
exit;
}

if(isset($_POST['checkbal'])){
if(strlen($_POST['checkbal'])>0){    
$id=str_replace('_','',$_POST['checkbal']);

$cdata=explode('_',remove_junk(escape($_POST['checkbal'])));
$cid = $cdata['1']; 

$_SESSION['axes_selcustomer'][0]['cusid']=$cid;

$ldebit=get_ledgervalnew($id,'D','N');
$lcredit=get_ledgervalnew($id,'C','N');
$lnet=($ldebit-$lcredit);


echo number_format($lnet,2);
}else{
echo '0.00';    
}    
}



if(isset($_POST['expcsv'])){
$fdate=$_POST['fdate'];
$tdate=$_POST['tdate'];
$output='';
$sql="SELECT Package_Description,Receiver_Name,IF(endata.type='CU' AND endata.cusid=0,(SELECT waddress FROM tbl_sales WHERE invno=endata.invno),(SELECT address FROM tbl_customer WHERE id=endata.cusid)) AS Receiver_Address,(SELECT mobile FROM tbl_sales WHERE invno=endata.invno) AS Receiver_Number,IF(endata.city!='',(SELECT name FROM tbl_district WHERE id=endata.city),'') AS Receiver_City,IF(endata.zone!='',(SELECT name FROM tbl_zone WHERE id=endata.zone),'') AS Receiver_Zone,IF(endata.type='CU' AND endata.cusid=0,(SELECT wemail FROM tbl_sales WHERE invno=endata.invno),(SELECT cemail FROM tbl_customer WHERE id=endata.cusid)) AS Recipient_Email,Price,'' AS Instructions,qty,date FROM (SELECT GROUP_CONCAT(tbl_item.name) AS Package_Description,SUM(tbl_traproduct.s_qty) AS qty,type,tid AS cusid,(SELECT did FROM tbl_sales WHERE invno=tbl_traproduct.invno) AS city,(SELECT zid FROM tbl_sales WHERE invno=tbl_traproduct.invno) AS zone,(SELECT name FROM tbl_sales WHERE invno=tbl_traproduct.invno) AS Receiver_Name,(SELECT total FROM tbl_sales WHERE invno=tbl_traproduct.invno) AS Price,(SELECT apdate FROM tbl_sales WHERE invno=tbl_traproduct.invno) AS date,invno
FROM tbl_traproduct LEFT JOIN tbl_item ON tbl_item.id=tbl_traproduct.pid WHERE mods='SE' GROUP BY invno) AS endata WHERE date BETWEEN '$fdate' AND '$tdate'";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$output.='<tr><th>Package_Description</th><th>Receiver_Name</th><th>Receiver_Address</th><th>Receiver_Number</th><th>Receiver_City</th><th>Receiver_Zone</th><th>Recipient_Email</th><th>Price</th><th>Instructions</th><th>Qty</th><th>Date</th></tr>';
while($row = mysqli_fetch_array($result) ){
$output.='<tr><td>'.$row['Package_Description'].'</td><td>'.$row['Receiver_Name'].'</td><td>'.$row['Receiver_Address'].'</td><td>'.$row['Receiver_Number'].'</td><td>'.$row['Receiver_City'].'</td><td>'.$row['Receiver_Zone'].'</td><td>'.$row['Recipient_Email'].'</td><td>'.$row['Price'].'</td><td>'.$row['Instructions'].'</td><td>'.$row['qty'].'</td><td>'.$row['date'].'</td></tr>';	
}
// encoding array to json format
echo $output;
}

if(isset($_POST['seldata'])){
$edata=array(check_price('P'),check_serial('S'));
echo json_encode($edata);
}

if(isset($_POST['addsales'])){
$invno = gen_newinvno('tbl_sales','SEL');
$apdate = remove_junk(escape($_POST['seldt']));
$nxtdt = remove_junk(escape($_POST['nextdt']));
    
$cdata=explode('_',remove_junk(escape($_POST['customer'])));
$cty=$cdata['0'];    
$cid = $cdata['1'];    

if($cid!=0){
if($cty=='CU'){    
$cname=get_fild_data('tbl_customer',$cid,'name');
$cmobile=get_fild_data('tbl_customer',$cid,'cnumber'); 
$climit=get_fild_data('tbl_customer',$cid,'creditlimit');  


}else{
$cname=get_fild_data('tbl_supplier',$cid,'name');
$cmobile=get_fild_data('tbl_supplier',$cid,'cnumber');     
}
$wdid='NULL';
$wzid='NULL';
$wadd='NULL';
$wemail='NULL';    
}else{
$cname=remove_junk(escape($_POST['wname']));
$cmobile=remove_junk(escape($_POST['wmobile']));
$wdid="'".remove_junk(escape($_POST['wdid']))."'";
$wzid="'".remove_junk(escape($_POST['wzid']))."'";
$wadd="'".remove_junk(escape($_POST['wadd']))."'"; 
$wemail="'".remove_junk(escape($_POST['wemail']))."'";     
}    
    
$baid = remove_junk(escape($_POST['baid']));    
$chkno = remove_junk(escape($_POST['chkno']));
$chkdt = remove_junk(escape($_POST['chkdt']));
if($chkno=='' || strlen($chkno)<2){$chkdt='NULL';$chkno='NULL';}//else{$chkdt="'".$chkdt."'";$chkno="'".$chkno."'";} 

$caname = remove_junk(escape($_POST['caname']));    
$chbid = remove_junk(escape($_POST['chbid']));
$caid = remove_junk(escape($_POST['caid']));
if(strlen($caname)<2){$chbid='NULL';$caid='NULL';}//else{$chbid="'".$chbid."'";$caid="'".$caid."'";}    

$mobid = remove_junk(escape($_POST['mobid']));    
$trxid = remove_junk(escape($_POST['trxid']));

if($baid!=''){
$debitid=$baid;
$details="'".'CHK_'.$chkno.'_'.$chkdt."'";    
}elseif(strlen($caname)>0){
$debitid=$caid;
$details="'".'CRD_'.$caname.'_'.$chbid."'";    
}elseif($mobid!=''){
$debitid=$mobid;
$details="'".'MOB_'.$trxid."'";    
}else{
$debitid='LE_2';
$details='NULL';    
}    
    
$pname = remove_junk(escape($_POST['pname']));    
$dipname = remove_junk(escape($_POST['dipname']));
$paddress = remove_junk(escape($_POST['paddress']));
    
$ref = remove_junk(escape($_POST['ref']));
$note = remove_junk(escape($_POST['note']));
$selp = remove_junk(escape($_POST['selp']));
if($selp=='' || $selp=='-Select-'){$selp='NULL';}else{$selp="'".$selp."'";} 

$otclient = remove_junk(escape($_POST['otclient']));
$otmobile = remove_junk(escape($_POST['otmobile']));

$adjust = remove_junk(escape($_POST['adjust']));
if($adjust==''){$adjust=0;}     
$cash = remove_junk(escape($_POST['cash']));
if($cash==''){$cash=0;}     

$itmdis=remove_junk(escape(get_seldiscount_total()));    
$disp=remove_junk(escape($_SESSION['axes_salesde'][0]['disp']));
$disamo=remove_junk(escape($_SESSION['axes_salesde'][0]['disamo']));   
$vatp=remove_junk(escape($_SESSION['axes_salesde'][0]['vatp']));
$vatamo=remove_junk(escape($_SESSION['axes_salesde'][0]['vatamo']));
$aitp=remove_junk(escape($_SESSION['axes_salesde'][0]['aitp']));
$aitamo=remove_junk(escape($_SESSION['axes_salesde'][0]['aitamo']));
$freight=remove_junk(escape($_SESSION['axes_salesde'][0]['freight']));
$otname=remove_junk(escape($_SESSION['axes_salesde'][0]['name']));
$otamo=remove_junk(escape($_SESSION['axes_salesde'][0]['others']));
$less=remove_junk(escape($_SESSION['axes_salesde'][0]['less']));
$subtot=get_sales_total();    
$gtotal=remove_junk(escape($_SESSION['axes_salesde'][0]['gtotal']));
if($disp>0){
$invdis=($disamo-$itmdis);    
}else{
$invdis=0;    
}    

if(($adjust+$cash)>=$gtotal){
$rcash=($gtotal-$adjust);
$change=(($adjust+$cash)-$gtotal);
$due=0;
$duedt='NULL';    
}else{
$rcash=$cash;
$change=0;
$due=($gtotal-($adjust+$cash));
$duedt="'".$nxtdt."'";    
}   

// Customer Limit Code
// if(get_fild_data('tbl_setting','13','sval')==0){
//   if($cty=='CU'){    
 
//     $climit=get_fild_data('tbl_customer',$cid,'creditlimit');  
//     $cusdebit=get_fild_data('tbl_cusdebit',$cid,'debit');
//     $cuscredit=get_fild_data('tbl_cuscredit',$cid,'credit');
//     $cusbal=$cusdebit-$cuscredit;
//     $totallimit=$cusbal+$due;
  
//   if($totallimit > $climit){
//     echo json_encode(array(
//     'status' => 'error',
//     'message'=> 'Sorry! Customer Limit Over!!'
//     ));
//     return;
//     exit;  
//     }
  
//   }


// }



    
if(!isset($_SESSION['axes_sales'])){
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! No item found!!'
));
return;
exit;  
}   

if(check_validqty($brid)){
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! Quantity not available!!'
));
return;
exit;     
} 

//SMS Code Start

if($cmobile>0){
$sql="SELECT * FROM tbl_sms WHERE id=1 LIMIT 1";
$smsde = mysqli_query($con,$sql);
$sms=mysqli_fetch_array($smsde);

if($sms['status']==1){
$lang=$sms['language'];
$appkey=$sms['appkey'];
$senderid=$sms['senderid'];
$type=$sms['type'];
$url=$sms['url'];
$htext=$sms['htext'];
$ftext=$sms['ftext'];

$hbtext=$sms['hbtext'];
$fbtext=$sms['fbtext'];


if($lang==1){
    $url = "$url";
    $data = [
      "api_key" => "$appkey",
      "type" => "$type",
      "contacts" => "$cmobile",
      "senderid" => "$senderid",
      "msg" => "$htext SN:$invno. Total Amount: $gtotal. Paid Amount: $cash. Due Amount: $due. $ftext.",
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

    echo json_encode(array(
      'status' => 'error',
      'message'=> $response
      ));
    exit;
    curl_close($ch);
}else{
  $url = "$url";
  $data = [
    "api_key" => "$appkey",
    "type" => "$type",
    "contacts" => "$cmobile",
    "senderid" => "$senderid",
    "msg" => "$hbtext রসিদ নং:$invno. সর্বমোট: $gtotal. পরিশোধ: $cash. বাকি: $due. $fbtext.",
  ];
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  $response = curl_exec($ch);
  curl_close($ch);

}

}
}

//SMS Code End




if(get_fild_data('tbl_setting','12','sval')==0){
if($chkno != 'NULL'){
$first = filter_var($baid, FILTER_SANITIZE_NUMBER_INT);
$acid = preg_replace("/[^[:alnum:][:space:]]/u", '', $first);
$sql="INSERT INTO tbl_cheqman(clientid,type,chkno,chkdt,amount,acid,refinv,ref,paymod,status,apdate,brid,uid,date) VALUES ('$cid','$cty','$chkno','$chkdt','$cash','$acid','$invno','$ref','REC','1','$apdate','$brid','$aid','$dtnow')";
mysqli_query($con,$sql) or die(mysqli_error($con)); 
$cash=0;
}  
} 



$refinv= $_SESSION['selesinv'];



$sql="INSERT INTO tbl_sales (invno,refinv,type,cusid,name,	mobile,did,zid,itemdis,subtot,disp,disamo,totdis,vatp,vatamo,aitp,aitamo,otname,otamo,freight,less,adamo,total,curid,ref,note,apdate,nxtduedate,ocusname,ocusmobile,pname,pdep,paddress,waddress,wemail,rawcash,changes,selp,debitid,details,brid,uid,date) VALUES ('$invno','$refinv','$cty','$cid','$cname','$cmobile',$wdid,$wzid,'$itmdis','$subtot','$disp','$invdis','$disamo','$vatp','$vatamo','$aitp','$aitamo','$otname','$otamo','$freight','$less','$adjust','$gtotal','0','$ref','$note','$apdate',$duedt,'$otclient','$otmobile','$pname','$dipname','$paddress',$wadd,$wemail,'$cash','$change',$selp,'$debitid',$details,'$brid','$aid','$dtnow')";  
$result = mysqli_query($con,$sql) or die(mysqli_error($con));

$sid=$con->insert_id;  

$ldata=explode('_',$debitid);
$lty=$ldata['0'];    
$lid = $ldata['1'];  


if($cash>0){
  if($lty=='MO'){
      $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$lty','$lid','$cash','$cid','$cty','$apdate','$ref','$aid','$brid','$dtnow')";
      $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
    }else if($lty=='BA'){
      $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$lty','$lid','$cash','$cid','$cty','$apdate','$ref','$aid','$brid','$dtnow')";
      $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
    }else if($lty=='LE'){
      $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$lty','$lid','$cash','$cid','$cty','$apdate','$ref','$aid','$brid','$dtnow')";
      $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
  }
    
}

if($disamo >0){
  $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','LE','36','$disamo','$cid','$cty','$apdate','$ref','$aid','$brid','$dtnow')";
  $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}


if($less >0){
    $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','LE','40','$less','$cid','$cty','$apdate','$ref','$aid','$brid','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}




if($vatamo >0){
    $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$cty','$cid','$vatamo','25','LE','$apdate','$ref','$aid','$brid','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}


if($freight >0){
    $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$cty','$cid','$freight','12','LE','$apdate','$ref','$aid','$brid','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}

if($otamo >0){
    $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$cty','$cid','$otamo','39','LE','$apdate','$ref','$aid','$brid','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}


if($aitamo >0){
    $sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,ref,uid,brid,date) VALUES ('$invno','$invno','$cty','$cid','$aitamo','38','LE','$apdate','$ref','$aid','$brid','$dtnow')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con)); 
}






$efid=mysqli_affected_rows($con);     

if($efid>0){
$max=count($_SESSION['axes_sales']);
for($i=0;$i<$max;$i++){
$pid = $_SESSION['axes_sales'][$i]['pid'];
$unqid= $_SESSION['axes_sales'][$i]['unqid'];   
$col=$_SESSION['axes_sales'][$i]['col'];
$siz=$_SESSION['axes_sales'][$i]['siz'];
$icdis=$_SESSION['axes_sales'][$i]['icdis'];
$icinvdis=$_SESSION['axes_sales'][$i]['icinvdis'];    
$cost=$_SESSION['axes_sales'][$i]['cost'];
$puqty=0;    
$qtyin=0;   
$soqty=$_SESSION['axes_sales'][$i]['qty'];
    
if(get_fild_data('tbl_setting','3','sval')==0){    
$qtyout=$_SESSION['axes_sales'][$i]['qty'];
$ploc=0;     
}else{
if(isset($_POST['sercv']) && $_POST['sercv']==0){
$qtyout=$_SESSION['axes_sales'][$i]['qty'];
$ploc=0;     
//}elseif(isset($_POST['sercv']) && $_POST['sercv']==1){
//$qtyout=0;
//$ploc=0;    
}else{
$qtyout=0;
$ploc=$_SESSION['axes_sales'][$i]['qty'];    
}       
}
    
$taxp=0;
$taxamo=0;
$idisp=$_SESSION['axes_sales'][$i]['disp'];
$idisf=$_SESSION['axes_sales'][$i]['disf'];
$disamo=$_SESSION['axes_sales'][$i]['disamo'];
$sdisp=0;
$sdisf=0;
$price=$_SESSION['axes_sales'][$i]['price'];
$isubtot=$_SESSION['axes_sales'][$i]['subtot'];
$wday=$_SESSION['axes_sales'][$i]['wday'];
$pnote=$_SESSION['axes_sales'][$i]['pnote'];    
    
$sql="INSERT INTO tbl_traproduct (type,tid,invno,refinv,pid,unqid,colid,sizid,icdis,icinvdis,cost,price,p_qty,p_in,s_qty,p_out,p_loc,taxp,taxamo,disp,disf,disamo,subtot,wday,mods,brid,waid,tramod,isinv,pnote,uid,apdate,date) VALUES ('$cty','$cid','$invno',NULL,'$pid','$unqid','$col','$siz','$icdis','$icinvdis','$cost','$price','$puqty','$qtyin','$soqty','$qtyout','$ploc','$taxp','$taxamo','$idisp','$idisf','$disamo','$isubtot','$wday','SE','$brid',NULL,NULL,'Y','$pnote','$aid','$apdate','$dtnow')";
    
$result = mysqli_query($con,$sql) or die(mysqli_error($con));   

//new code add for traledger1 product
$sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,uid,brid,date) VALUES ('$invno',NULL,'$cty','$cid','$isubtot','$pid','PD','$apdate','$aid','$brid','$dtnow')";
$result = mysqli_query($con,$sql) or die(mysqli_error($con)); 


$sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,uid,brid,date) VALUES ('$invno',NULL,'LE','14','$cost','$pid','PD','$apdate','$aid','$brid','$dtnow')";
$result = mysqli_query($con,$sql) or die(mysqli_error($con)); 


$sql="INSERT INTO tbl_traledger1 (invno,refinv,dty,did,amo,cid,cty,apdate,uid,brid,date) VALUES ('$invno',NULL,'PD','$pid','$price','34','LE','$apdate','$aid','$brid','$dtnow')";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));   



}

if(isset($_SESSION['axes_selse'])){
  $max=count($_SESSION['axes_selse']);
  for($i=0;$i<$max;$i++){
  $pid=$_SESSION['axes_selse'][$i]['pid'];
  $unqid=$_SESSION['axes_selse'][$i]['unqid'];    
  $serial=$_SESSION['axes_selse'][$i]['imei'];
    if(get_fild_data('tbl_setting','3','sval')==0){$dli='Y';}else{if(isset($_POST['sercv']) && $_POST['sercv']==0){$dli='Y';}else{$dli='N';}}    
    $sql="UPDATE tbl_serial SET unqid='$unqid',status='1' WHERE serial='$serial'";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));
    $sql="INSERT INTO tbl_serialsale (invno,pid,unqid,serial,mods,dli) VALUES ('$invno','$pid','$unqid','$serial','S','$dli')";
    $result = mysqli_query($con,$sql) or die(mysqli_error($con));    
    }    
  }

  //sales_update($sid,'tbl_sales',$dtnow); 
  unset($_SESSION['axes_selcustomer']);
  unset( $_SESSION['selesinv']);
  unset($_SESSION['axes_sales']);
  unset($_SESSION['axes_salesde']);
  if(isset($_SESSION['axes_selse'])){
  unset($_SESSION['axes_selse']);
  }    
    
  $act =remove_junk(escape('Sales Invoice: '.$invno));    
  write_activity($aid,'SEL','New sales invoice has been Created',$act);
  echo json_encode(array(
  'status' => 'success',
  'message'=> 'Sales Save Successfully!!',
  'invid'=> $sid    
  ));
  exit;    
}else{
  echo json_encode(array(
  'status' => 'error',
  'message'=> 'Sorry! Data Fail to Saved!!'
  ));    
}    
    
}


if(isset($_POST['savecus'])){
$name = ucwords(remove_junk(escape($_POST['name'])));
$code = get_genid('CU');
$cperson = remove_junk(escape($_POST['cperson']));
$cnumber = remove_junk(escape($_POST['cnumber']));
$cemail = remove_junk(escape($_POST['cemail']));    
$address = remove_junk(escape($_POST['address']));
$did = remove_junk(escape($_POST['did']));
if($did!=''){$did="'".$did."'";}else{$did='NULL';}
$zid = remove_junk(escape($_POST['zid']));
if($zid!=''){$zid="'".$zid."'";}else{$zid='NULL';}    
if(isset($_POST['cnumber'])){
$ducode = mysqli_query($con,"SELECT * FROM tbl_customer WHERE cnumber = '$cnumber'");
}
	
if($ducode->num_rows > 0) {
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! This contact number already exists!!'
));
return;
exit;
}else{
$sql="INSERT INTO tbl_customer(code,name,cperson,cnumber,cemail,address,did,zid,uid,date) VALUES ('$code','$name','$cperson','$cnumber','$cemail','$address',$did,$zid,'$aid','$dtnow')";    
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sid=$con->insert_id;    
$efid=mysqli_affected_rows($con);    
if($efid>0){
$act =remove_junk(escape('Customer name: '.$name));    
write_activity($aid,'CUS','New customer has been Added',$act);
echo json_encode(array(
'status' => 'success',
'cbal'=> '0.00',
'cudata'=> $code.'|'.$name.'|'.$cnumber,
'cuid'=> 'CU_'.$sid    
));
exit;   
}else{
echo json_encode(array(
'status' => 'error',
'message'=> 'Sorry! Customer Fail to Saved!!'
));    
} 
}    
}
?>

<?php if(isset($_POST['addcus'])){ ?>
<div class="col-md-12 popup_details_div addcustomer">
<div class="row">
<div id="server-results"><!-- For server results --></div>    
</div>
<div class="row">
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" maxlength="45" value="" id="name" class="form-control" placeholder="e.g. Md.Sumon Rahman"/>
<input type="hidden" name="savecus" readonly />    
</div>    
<div class="form-group">
<label>Contact Name</label>    
<input type="text" name="cperson" maxlength="45" value="" id="cperson" class="form-control" placeholder="e.g. Md.Rahman Sumon(CEO)"/>
</div>
<div class="form-group">
<label>Contact Number</label>    
<input type="text" name="cnumber" maxlength="18" value="" id="cnumber" class="form-control" placeholder="e.g. +88016161xxxxx70"/>
</div>
<div class="form-group">
<label>Contact Email</label>    
<input type="text" name="cemail" maxlength="45" value="" id="cemail" class="form-control" placeholder="e.g. info@axesgl.com"/>
</div>
<div class="form-group">    
<label>Address</label>
<textarea class="form-control" name="address" id="address" maxlength="250" rows="5" placeholder="Address"></textarea>    
</div>
<div class="row">
<div class="col-md-6">    
<div class="form-group">
<label>Select District</label>
<select class="form-control select2" name="did" id="did" onchange="getAllSubgroup(this.value)">
<option value="">-Select-</option>
<?php									
$querys=mysqli_query($con,"SELECT * FROM tbl_district ORDER BY name ASC")or die(mysqli_error($con));
while ($rows=mysqli_fetch_array($querys)){
?>
<option value="<?php echo $rows['id'];?>"><?php echo $rows['name'];?></option>
<?php } ?>
</select>    
</div>
</div>
<div class="col-md-6">    
<div class="form-group">
<label>Select Zone</label>
<select class="form-control select2" name="zid" id="zid">
<option value="">-Select-</option>    
</select>     
</div>
</div>    
</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-2 text-right" >
<input type="button" id="adcus" class="btn btn-flat bg-purple btn-sm " value="Save"/>
</div>
<div class="col-md-2"></div>    
</div>

<script type="text/javascript">
function chek_error(){
var name = $('#name').val();
var cnumber = $('#cnumber').val();
var address = $('#address').val();    
var cemail = $('#cemail').val();    
var result = true;
    
var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,8}|[0-9]{1,3})(\]?)$/;
    
$('.LV_validation_message').remove();
    
if(name.length<=0){
$('#name').addClass('LV_invalid_field');   
$('#name').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); } else {
$('#name').removeClass('LV_invalid_field'); 
}    
    
if(cnumber.length<=0){
$('#cnumber').addClass('LV_invalid_field');   
$('#cnumber').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); } else {
$('#cnumber').removeClass('LV_invalid_field'); 
}    

if(address.length<=0){
$('#address').addClass('LV_invalid_field');   
$('#address').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); } else {
$('#address').removeClass('LV_invalid_field'); 
}    
    
if(cemail.length >0){
result = expr.test(cemail);
if(result){
$('#cemail').removeClass('LV_invalid_field');        
}else{
$('#cemail').addClass('LV_invalid_field');
$('#cemail').after("<span class='LV_validation_message LV_invalid'>Not a valid email address!</span>").addClass('has-error');    
}    
}    
    
if(name.length<=0 || address.length<=0 || cnumber.length<=0 || !result){
return false;    
}else{
return true;     
}    
}

function getAllSubgroup(id){
$.ajax({
url: 'axe_getsub.php',
type: 'post',
data: {zone : id},
success:function(data) {
$('#zid').html(data);
}
});
};     
    
$(document).on('blur', '#name, #cnumber, #cemail', function() {
chek_error();    
});        
</script>    
<?php } ?>

<?php 
if(isset($_POST['checkview'])){
$cusd=explode('_',$_POST['cusid']);
$typ=$cusd[0];    
$cusid=$cusd[1];
$wname = $_POST['wname'];
$wmobil = $_POST['wmobil'];
$wdid = $_POST['wdid'];
$wzid = $_POST['wzid'];
$wadd = $_POST['wadd'];
$wemail = $_POST['wemail'];    
if(isset($_SESSION['axes_salesde'])){    
$gtotal=$_SESSION['axes_salesde'][0]['gtotal'];
}else{
$gtotal=0;    
}
$id=str_replace('_','',$_POST['cusid']);
$ldebit=get_ledgervalnew($id,'D','N');
$lcredit=get_ledgervalnew($id,'C','N');
if($cusid!=0){
$lnet=($ldebit-$lcredit);     
}else{
$lnet=0;    
}        
?>
<div class="addsersales">
<div class="row">
<div class="col-md-3 col-xs-6">
<div class="small-box">
<div class="inner">
<h3 id="pabamo"><?php echo $gtotal;?></h3>
<p>Total Receivable</p>
</div>

</div>
<input type="hidden" value="<?php echo $_POST['cusid']; ?>" id="customer" name="customer" readonly />
<input type="hidden" value="<?php if($lnet<0){echo ABS($lnet);}else{echo 0;} ?>" id="balance" name="balance" readonly />
<input type="hidden" value="<?php echo $wname;?>" name="wname" readonly />
<input type="hidden" value="<?php echo $wmobil;?>" name="wmobile" readonly />
<input type="hidden" value="<?php echo $wdid;?>" name="wdid" readonly />
<input type="hidden" value="<?php echo $wzid;?>" name="wzid" readonly />
<input type="hidden" value="<?php echo $wadd;?>" name="wadd" readonly /> 
<input type="hidden" value="<?php echo $wemail;?>" name="wemail" readonly />     
<input type="hidden" name="addsales" readonly />
<input type="hidden" name="scusid" id="scusid" value="<?php echo $cusid; ?>" readonly />    
</div>
<div class="col-md-3 col-xs-6">
<div class="small-box">
<div class="inner">
<h3 id="paidamo">0</h3>
<p>Receive Amount</p>
<input type="hidden" value="" id="recamo" name="recamo" readonly />    
</div>

</div>
</div>
<div class="col-md-3 col-xs-6">
<div class="small-box">
<div class="inner">
<h3 id="dueamo"><?php echo $gtotal;?></h3>
<p>Total Due</p>
</div>

</div>
</div>
<div class="col-md-3 col-xs-6">
<div class="small-box">
<div class="inner">
<h3 id="changamo">0</h3>
<p>Change</p>
</div>

</div>
</div>    
</div>
<div class="row">
<div class="col-md-4 col-xs-6">
<div class="form-group">
<label>Balance (<?php echo $lnet;?>)</label>    
<input type="text" maxlength="10" class="form-control cashr" value="0" name="adjust" id="adjust"  onkeypress="return isNumberKey(event)" placeholder="e.g. 500" autocomplete="off" <?php if($lnet>=0){echo 'disabled';}?>>    
</div>    
</div>
<div class="col-md-4 col-xs-6">
<div class="form-group">
<label>Cash</label>    
<input type="text" maxlength="10" class="form-control cashr" name="cash" id="cash"  onkeypress="return isNumberKey(event)" placeholder="e.g. 500" autocomplete="off">    
</div>    
</div>
<div class="col-md-2 col-xs-6">
<div class="form-group" >
<label>Sales Date</label>
<input type="text" class="form-control datetimepicker" name="seldt" id="seldt" value="<?php echo $today;?>" placeholder="Sales Date" autocomplete="off" readonly>
</div>
</div>
<div class="col-md-2 col-xs-6">
<div class="form-group" >
<label>Next Due Date</label>
<input type="text" class="form-control datetimepicker" name="nextdt" id="nextdt" value="<?php echo date('Y-m-d', strtotime('+7 days',strtotime($today)));?>" placeholder="Sales Date" autocomplete="off" readonly>
</div>    
</div>
</div>
<div class="row" style="border-top: 2px solid red; border-bottom: 2px solid black;">
<div class="col-xs-3"> <!-- required for floating -->
<!-- Nav tabs -->
<ul class="nav nav-tabs tabs-left sideways">
<li class="active"><a href="#bankpay" data-toggle="tab" class="tabpoint" id="tbank">Bank</a></li>
<li><a href="#cardpay" data-toggle="tab" class="tabpoint" id="tcard">Card</a></li>
<li><a href="#mobilepay" data-toggle="tab" class="tabpoint" id="tmobile">Mobile</a></li>
<li><a href="#project" data-toggle="tab">Project</a></li>
</ul>
</div>

<div class="col-xs-9">
<!-- Tab panes -->
<div class="tab-content" style="padding-top: 10px;">
<div class="tab-pane active" id="bankpay">
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Select Bank</label>    
<select class="form-control select2" name="baid" id="baid">
<option value="">-Select-</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 } ?>
</select>   
</div>    
</div>    
</div>
<div class="row">
<div class="col-md-6">
<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>
<div class="col-md-6">
<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>    
</div>    
</div>
<div class="tab-pane" id="cardpay">
<div class="row">
<div class="col-md-8">    
<div class="form-group">
<label>Card Holder Name</label>
<input type="text" maxlength="35" class="form-control" name="caname" id="caname" value="" placeholder="e.g. Md.Sumon" autocomplete="off">
</div> 
</div>     
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Card Holder Bank</label>    
<select class="form-control select2" name="chbid" id="chbid">
<option value="">-Select-</option>    
<?php
$sql="SELECT id,name FROM tbl_bank ORDER BY name 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 } ?>
</select>   
</div>    
</div>    
<div class="col-md-6">    
<div class="form-group">
<label>Deposit Bank</label>    
<select class="form-control select2" name="caid" id="caid">
<option value="">-Select-</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 } ?>
</select>   
</div>
</div>
</div>     
</div>
<div class="tab-pane" id="mobilepay">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Mobile Account</label>    
<select class="form-control select2" name="mobid" id="mobid">
<option value="">-Select-</option>    
<?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>   
</div>    
</div> 
<div class="col-md-6">
<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">
</div>    
</div>     
</div>    
</div>
<div class="tab-pane" id="project">
<div class="col-xs-5">
<div class="form-group">
<label>Person/Project Name</label>
<input type="text" name="pname" id="pname" maxlength="35" class="form-control" placeholder="Md.Nur Hossain, CEO" autocomplete="off">
</div>
<div class="form-group">
<label>Section/Department</label>
<input type="text" name="dipname" id="dipname" maxlength="35" class="form-control" placeholder="e.g Infomation Technology" autocomplete="off">
</div>    
</div>    
<div class="col-xs-7">    
<div class="form-group">    
<label>Address</label>
<textarea class="form-control" name="paddress" id="paddress" maxlength="150" rows="5" placeholder="Address"></textarea>    
</div>    
</div>    
</div>
</div>
</div>
<div class="clearfix"></div>    
</div>
<div class="row">
<br>   
<div class="col-md-4">
<div class="form-group">
<label>Ref</label>
<input type="text" maxlength="25" class="form-control" name="ref" id="ref" placeholder="e.g. #ORD8976453" autocomplete="off">    
</div>
<div class="form-group">
<label>Sales Person</label>    
<select class="form-control select2" name="selp" id="selp">
<option value="">-Select-</option>    
<?php
$sql="SELECT id,name FROM tbl_employe ORDER BY name ASC";    
$querys=mysqli_query($con,$sql)or die(mysqli_error($con));
while ($rows=mysqli_fetch_array($querys)){
?>
<option value="<?php echo $rows['id'];?>"><?php echo $rows['name'];?></option>
<?php } ?>
</select>    
</div>    
</div>
<div class="col-md-8">    
<div class="form-group">    
<label>Note</label>
<textarea class="form-control" name="note" id="note" maxlength="150" rows="5" placeholder="Invoice Note"></textarea>    
</div>    
</div>    
</div>
<div class="row">
<?php if(get_fild_data('tbl_setting','3','sval')==1){ ?>   
<div class="col-md-12">
<div class="col-md-4">
<div class="form-group">
<label><?php if(get_fild_data('tbl_setting','1','sval')==0){echo 'Sales Delivery Now';}else{echo 'বিক্রয় কৃত পণ্য বিতরণ এখনি';}?></label>    
<select class="form-control select2" name="sercv" id="sercv">    
<option <?php if(get_fild_data('tbl_setting','3','sval')==0){echo 'selected';} ?> value="0"><?php if(get_fild_data('tbl_setting','1','sval')==0){echo 'Yes';}else{echo 'হ্যাঁ';}?></option>
<option <?php if(get_fild_data('tbl_setting','3','sval')==1){echo 'selected';} ?> value="1"><?php if(get_fild_data('tbl_setting','1','sval')==0){echo 'No';}else{echo 'না';}?></option>
<!--<option value="2"><?php //if(get_fild_data('tbl_setting','1','sval')==0){echo 'Lock';}else{echo 'লক';}?></option>-->    
</select>    
</div>
</div>    
<div class="col-md-8">    
<div class="secdiv" style="margin-bottom: 10px;"><span>Other Billing Name (Optional)</span></div>    
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="otclient" maxlength="35" class="form-control" placeholder="e.g Sumon">
</div>    
</div>
<div class="col-md-6">    
<div class="form-group">
<label>Mobile</label>
<input type="text" name="otmobile" maxlength="18" class="form-control" placeholder="e.g 016161700">
</div>
</div>
</div>   
</div>
<?php }else{ ?>
<div class="secdiv" style="margin-bottom: 10px;"><span>Other Billing Name (Optional)</span></div>    
<div class="col-md-6">
<div class="form-group">
<label>Name</label>
<input type="text" name="otclient" maxlength="35" class="form-control" placeholder="e.g Sumon">
</div>    
</div>
<div class="col-md-6">    
<div class="form-group">
<label>Mobile</label>
<input type="text" name="otmobile" maxlength="18" class="form-control" placeholder="e.g 016161700">
</div>
</div>    
<?php } ?>    
</div>    
</div>    
<div class="row">
<div class="col-md-12 text-center side-checkhead">
<button class="btn btn-flat bg-blue saveseinv" id="saveinv"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp;Save</button>    
<button class="btn btn-flat bg-gray saveseinv" id="sinvprint"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp; Invoice &nbsp;&nbsp;<i class="fa fa-print"></i></button>
<button class="btn btn-flat bg-gray saveseinv" id="srecprint"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp; POS &nbsp;&nbsp;<i class="fa fa-print"></i></button>
<button class="btn btn-flat bg-gray saveseinv" id="sichprint"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp; Invoice &amp; Challan &nbsp;&nbsp;<i class="fa fa-print"></i></button>    
</div>    
</div>
<script type="text/javascript">
function cashcalculation(){
var pab = parseFloat($('#pabamo').html());
var cash = parseFloat($('#cash').val());
var adv = parseFloat($('#balance').val());
var adj = parseFloat($('#adjust').val());    
var paid=0; due=0; chang=0;
if(isNaN(cash)){
cash=0;    
}
if(isNaN(adj)){
adj=0;    
}
    
if((cash+adj)<=pab){
paid=cash;
due=(pab-(cash+adj));
chang=0;    
}else{
paid=pab;
due=0;
chang=((cash+adj)-pab);    
}
$('#paidamo').html(paid);
$('#dueamo').html(due);
$('#changamo').html(chang);   
}
    
$(document).on('keyup', '#cash', function() { 
cashcalculation();
});
    
$(document).on('keyup', '#adjust', function() {
var pab = parseFloat($('#pabamo').html());    
var adv = parseFloat($('#balance').val());
var adj = parseFloat($('#adjust').val());    
var maxad = 0;
if(pab<=adv){
maxad=pab;
}else{
maxad=adv;    
}
if(adj>maxad){
$('#adjust').val(maxad);    
}    
cashcalculation();
});
    
$(document).on('change', '#baid', 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;     
}else{
$('#chkno').val('');
$('#chkdt').val('');    
document.getElementById("chkno").disabled=true; 
document.getElementById("chkdt").disabled=true;    
}    
});    
    
$(document).on('click', '.tabpoint', function() { 
var tval=$(this).attr('id');
if (tval=='tbank'){
$("#caname").val("");    
$("#chbid").val("").trigger("change");
$("#caid").val("").trigger("change");
$("#mobid").val("").trigger("change");
$("#trxid").val("");    
}else if(tval=='tcard'){
$("#baid").val("").trigger("change");
$("#chkno").val("");
$("#chkdt").val("");    
$("#mobid").val("").trigger("change");
$("#trxid").val("");
}else if(tval=='tmobile'){
$("#baid").val("").trigger("change");
$("#chkno").val("");
$("#chkdt").val("");
$("#caname").val("");    
$("#chbid").val("").trigger("change");
$("#caid").val("").trigger("change");    
}
          
});    

function chek_error(){
var result = true;    
var baid = $('#baid').val();
var chkno = $('#chkno').val();
var chkdt = $('#chkdt').val();
    
var caname = $('#caname').val();
var chbid = $('#chbid').val();
var caid = $('#caid').val();
    
var mobid = $('#mobid').val();
var trxid = $('#trxid').val(); 

$('.LV_invalid_field').removeClass('LV_invalid_field');     
$('.LV_validation_message').remove();    
    
if(baid != ''){
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(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(caname.length>0){
if(chbid == '-Select-' || chbid == ''){
$('#chbid').addClass('LV_invalid_field');   
$('#chbid').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); 
result=false;
} else {
$('#chbid').removeClass('LV_invalid_field');
result=true;    
}
    
if(caid == '-Select-' || caid == ''){
$('#caid').addClass('LV_invalid_field');   
$('#caid').after("<span class='LV_validation_message LV_invalid'>Can't be empty!</span>").addClass('has-error'); 
result=false;
} else {
$('#caid').removeClass('LV_invalid_field');
result=true;    
}    
}    

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

if(!result){
return false;    
}else{
return true;     
}    
    
}
    
$(".select2").select2();    
$('.datetimepicker').datepicker({format: "yyyy-mm-dd", autoclose: true, clearBtn: true, orientation: 'auto bottom'});    
</script>    
<?php } ?>

<?php 
if(isset($_POST['checkout'])){
$cusd=explode('_',$_POST['cusid']);
$typ=$cusd[0];    
$cusid=$cusd[1];    
?>
<div class="col-md-12 cart-border-left text-center">
<div class="horizontal-scroll">
<h5 class="text-center" style="font-size: 20px;">Sales Details</h5> 
<div>
<div class="text-center header-line-height">
<small class="text-center" style="font-size: 15px;"><?php echo get_cominfo('1','name');?></small>
<br> <small class="text-center"><?php echo date("d M Y", strtotime($today));?></small>
<br> <small class="text-center" style="font-size: 12px;"><strong>Sales Receipt</strong></small>
<!--<br> <small class="text-left">Sold By: John Doe</small>--> 
<br> <small><span>Sold To: <?php if($cusid!=0){if($typ=='SU'){echo get_fild_data('tbl_supplier',$cusid,'name');}else{echo get_fild_data('tbl_customer',$cusid,'name');}}else{echo 'Walk-In Customer';};?></span></small> 
<small class="text-left invoice-show" style="display: none;">Invoice ID:</small>
</div> 
<div class="invoice-table">
<table class="table product-card-font" style="font-weight: 500;">
<thead class="border-top-0">    
<tr>
<th class="cart-summary-table text-left">Items</th> 
<th class="cart-summary-table text-left">Qty</th> 
<th class="cart-summary-table text-right">Price</th>
<th class="cart-summary-table text-right">Discount</th>
<th class="cart-summary-table text-right">Total</th>
</tr>   
</thead> 
<tbody>
<?php 
$s=0;    
if(isset($_SESSION['axes_sales'])){
$max=count($_SESSION['axes_sales']);
for($i=($max-1);$i>=0;$i=$i-1){
$name=$_SESSION['axes_sales'][$i]['name'];
$col=$_SESSION['axes_sales'][$i]['col'];
if($col==0){$col='';}
$siz=$_SESSION['axes_sales'][$i]['siz'];
if($siz==0){$siz='';}    
$qty=$_SESSION['axes_sales'][$i]['qty'];
$price=$_SESSION['axes_sales'][$i]['price'];
$disp=$_SESSION['axes_sales'][$i]['disp'];    
$subtot=$_SESSION['axes_sales'][$i]['subtot'];
$pnote=$_SESSION['axes_sales'][$i]['pnote'];
if($col=='' && $siz==''){
$name=$name;    
}elseif($col!='' && $siz==''){
$name= $name.' '.get_fild_data('tbl_color',$col,'name');    
}elseif($col=='' && $siz!=''){
$name= $name.' '.get_fild_data('tbl_size',$siz,'sval');    
}elseif($col!='' && $siz!=''){    
$name= $name.' '.get_fild_data('tbl_color',$col,'name').' '.get_fild_data('tbl_size',$siz,'sval');    
}     
$s+=1;    
?>    
<tr>
<td class="cart-summary-table text-left"><?php echo $name;?><br></td>
<td class="cart-summary-table"><?php echo $qty;?></td> 
<td class="text-right cart-summary-table"><?php echo numtolocal($price,''); ?></td> 
<td class="text-right cart-summary-table"><?php echo $disp;?> %</td> 
<td class="text-right cart-summary-table"><?php echo numtolocal($subtot,''); ?></td>
<?php }} ?>     
</tbody> 
<tfoot>
<?php 
$disp=$_SESSION['axes_salesde'][0]['disp'];
$vatp=$_SESSION['axes_salesde'][0]['vatp'];
$vatamo=$_SESSION['axes_salesde'][0]['vatamo'];
$aitp=$_SESSION['axes_salesde'][0]['aitp'];
$aitamo=$_SESSION['axes_salesde'][0]['aitamo'];
$otname=$_SESSION['axes_salesde'][0]['name'];
$others=$_SESSION['axes_salesde'][0]['others'];
$less=$_SESSION['axes_salesde'][0]['less'];
$freight=$_SESSION['axes_salesde'][0]['freight'];
$gtotal=$_SESSION['axes_salesde'][0]['gtotal'];    
?>    
<tr>
<td class="cart-summary-table font-weight-bold text-left">Sub Total</td> 
<td class="cart-summary-table"></td>
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table"><?php echo numtolocal(get_sales_total(),'Tk');?></td>
</tr>
<?php if(get_seldiscount_total()>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left">Discount(<?php echo $disp.'';?>%)</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal(get_seldiscount_total($disp),'Tk');?></td>
</tr>    
<?php } ?>
<?php if($vatamo>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left">VAT(<?php echo $vatp.'';?>%)</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($vatamo,'Tk');?></td>
</tr>    
<?php } ?>
<?php if($aitamo>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left">AIT(<?php echo $aitp.'';?>%)</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($aitamo,'Tk');?></td>
</tr>    
<?php } ?>    
<?php if($others>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left"><?php echo $otname;?></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($others,'Tk');?></td>
</tr>    
<?php } ?>
<?php if($freight>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left">Freight</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($freight,'Tk');?></td>
</tr>    
<?php } ?> 
<?php if($less>0){?>
<tr>
<td class="cart-summary-table font-weight-bold text-left">Adjust</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($less,'Tk');?></td>
</tr>    
<?php } ?>     
<tr>
<td class="cart-summary-table font-weight-bold text-left">Total</td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="cart-summary-table"></td> 
<td class="text-right cart-summary-table "><?php echo numtolocal($gtotal,'Tk');?></td>
</tr> 
</tfoot>
</table>
</div>
</div>
</div>
</div>   
<?php } ?>
