<?php 
        session_start();
$id_user=$_SESSION['id'];
$business=$_SESSION['business_id'];
$branch=$_SESSION['branch_id'];
          $id = $_GET['id'];
    
    
  include '../includes/connection.php';

$sql = mysqli_fetch_assoc(mysqli_query($con,"SELECT * FROM purchases where id='$id'"));
$mproduct_name=$sql['product_id'];
$mquantity=$sql['quantity_remaining'];
$rdate=$sql['expiry_date'];
$batch_no=$sql['batch_no'];
$retprice=$sql['unit_price'];

$reason="Expiry of quantity: ".$mquantity." with batch Number:".$batch_no." On ".$rdate;

$sqs = mysqli_fetch_array(mysqli_query($con,"select * from stock where product_name='$mproduct_name' && branch_id='$branch'"));
$quan=$sqs['quantity'];
$nquant=(int)$quan-(int)$mquantity;

$sqlst = mysqli_query($con,"update stock set quantity='$nquant' where product_name='$mproduct_name' ");
$sqlps = mysqli_query($con,"update products set quantity='$nquant' where id='$mproduct_name' ");

if ($sqlst) {
   $id_user=$_SESSION['id'];
  $ret1=mysqli_fetch_array(mysqli_query($con,"select * from stock where product_name='$mproduct_name' && branch_id='$branch'"));

  $retproduct=$ret1['product_name'];
  $return=mysqli_query($con,"INSERT INTO returns_out(product_id,quantity,price,branch_id,Reason,date,AddedBy) values('$mproduct_name','$mquantity','$retprice','$branch','$reason','$rdate','$id_user')");
 
  $ups1=mysqli_fetch_array(mysqli_query($con,"select * from products where id='$mproduct_name' && branch_id='$branch'"));
 $pname1=$ups1['product_name'];

 
  $activity="Recorded exipred  stock of  product ($mquantity) ".$pname1;
 $log_sql1=mysqli_query($con,"INSERT INTO logs(user_id, activity,branch_id) VALUES 
('$id_user','$activity','$branch')");

if ($log_sql1 && $return) {
//alert(' $mquantity units of $pname1 removed from stock succesfully');
	$delete = mysqli_query($con,"UPDATE purchases set quantity_remaining='0' where id='$id'");
    
 if(!$delete){
     die("Could not delete. Please ".mysqli_error($con));
 }
    else if($delete){?>

     
     <script>window(location="short_expiry.php");</script>
     <?php 
    }
    
} else {
    echo "Error: Failed to add log <br>" . mysqli_error($con);
}
}


    
        ?>

