<?session_start();
require_once('functions.php');
$dbc=mysqli_connect('localhost','jbxnmmli_spo','@@!@SWQ!Y6tgaq@!@','jbxnmmli_pso');
$user=$_SESSION['user'];
$product=mysqli_real_escape_string($dbc,$_POST['PNAME']);
$qty=$_POST['QTY'];

$code=$_POST['pcode'];
$receipt=$_POST['receipt'];
$credit=$_POST['CREDIT'];
$y="select * from sales where number='$receipt'  and p_name='$product'  limit 1";
$sql=mysqli_query($dbc,$y);
 $k=mysqli_num_rows($sql);
if($k==1){
$row=mysqli_fetch_array($sql);
$vat=$row['vat'];
$qty1=$row['qty'];
$price=$row['price'];
$less=$row['price']*$qty;
$total=$row['price']*$qty;
$totall=$row['p_price']*$qty;
$prof=$total-$totall;
$id=$row['sale_id'];
$vvat=16/100*$total;
//$sid=GetStock();
//$cash=GetCash();
//$cost=GetCostG();
//$sales=GetSALES();
//$vid=GetVat();
//$kid=GetKra();
if($qty1>$qty||$qty1==$qty){
$name=mysqli_real_escape_string($dbc,$row['p_name']);
$y="update sales set qty=qty-'$qty',total_p=total_p-'$total', prof=prof-'$prof' where sale_id='$id' and number='$receipt'";
$sql=mysqli_query($dbc,$y);
$gl=mysqli_query($dbc,("select amount,cust from x_report where receipt='$receipt' and type='INVOICE'"));
$vb=mysqli_fetch_array($gl);
  $dii=$vb['cust'];
  $amn=$vb['amount'];

$y="update products set left_p=left_p+'$qty',sold=sold-'$qty'  where p_name='$product' ";
$sql=mysqli_query($dbc,$y);
$d="update x_report set amount=amount-$total where receipt='$receipt' and amount>0 limit 1";
$dd=mysqli_query($dbc,$d);



$upd="update ledgers set credit=credit-'$total' where invoice='$receipt' and account_id='$sales' and description='$product'";
  $sql=mysqli_query($dbc,$upd);
 $pdu= "update ledgers set debit=debit-'$total', qty=qty-'$qty' where invoice='$receipt' and account_id!='$sales' and description='$product' and debit>0";
  $sql=mysqli_query($dbc,$pdu);
 $pud= "update ledgers set credit=credit-'$total', qty=qty-'$qty' where invoice='$receipt' and account_id!='$sales' and description='$product' and credit>0";
  $sqll=mysqli_query($dbc,$pud);

$r="insert into  return_in(product,code,qty,date,price,vat,total_p,receipt,credit)values('$product','$code',
'$qty',NOW(),'$price','$vvat','$total','$receipt','$credit')";
$sql=mysqli_query($dbc,$r);
$c="select * from products where p_name='$product' limit 1";
$cc=mysqli_query($dbc,$c);
$ccc=mysqli_fetch_array($cc);
$stock=$ccc['left_p'];
$pid=$ccc['product_id'];
//$v="insert into audit(product,date,value,reason,qty,number,stock,user)VALUES('$pid',NOW(),'RETURN IN','CREDIT NOTE','$qty','$credit','$stock','$user')";
//$vv=mysqli_query($dbc,$v);
}
}
header("location: return_in.php");
?>