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

$check=0;

$sql1=mysqli_query($con,"SELECT *, (SELECT name from users where id=purchases.AddedBy) as user from purchases where purchase_id=$purchase_id");
    while ($rc=mysqli_fetch_array($sql1)) {
$pd=$rc['product_id'];
       $quantity_pirchased=$rc['quantity'];
       $ss1c=mysqli_fetch_array(mysqli_query($con,"SELECT quantity from products where id='$pd'"));
       $quantity_instock=$ss1c['quantity'];    
       if ($quantity_pirchased>$quantity_instock) {
       	$check=$check+1;

       }
   }
       
     if ($check>0) {
      echo"<script>alert('Failed: The quantity purchased is greater than the quantity in stock. '),history;</script>";
       
       echo "<script>
    
    window.location='../reports/purchases_report.php';
    </script>";
    
       }else{
       	$sqll1=mysqli_query($con,"SELECT *, (SELECT name from users where id=purchases.AddedBy) as user from purchases where purchase_id=$purchase_id");
       	while ($result1=mysqli_fetch_array($sqll1)) {
		$product_id=$result1['product_id'];
		$quantity=$result1['quantity'];	
		$buying_price=$result1['unit_price'];	
		$userid=$result1['AddedBy'];
		$uname=$result1['user'];
		$expiry=$result1['expiry_date'];
		$batch_no=$result1['batch_no'];
		$supplier=$result1['supplier'];
		 $tlogsql=mysqli_fetch_array(mysqli_query($con,"select * from products where id='$product_id'"));
        $pname=$tlogsql['product_name'];

		$sql2=mysqli_query($con,"INSERT into getstock(product_id,quantity,unitprice,batch_no,expiry_date,supplier,branch_id,business_id,user_id) Values('$product_id','$quantity','$buying_price','$batch_no','$expiry','$supplier','$branch','$business','$id_user')");
		$sqlrestock=mysqli_query($con,"UPDATE stock set quantity=quantity-$quantity where product_name='$product_id'");
		$sqlrestock=mysqli_query($con,"UPDATE products set quantity=quantity-$quantity where id=$product_id");

		$action=" Recorded a purchases return of product with details"."<br> product Name: ".$pname."<br> product Unit price: ".$buying_price."<br> product quantity: ".$quantity."<br> total_price: ".$buying_price*$quantity;
 $log_sql1=mysqli_query($con,"INSERT INTO logs(user_id, activity,branch_id,business_id) VALUES 
('$id_user','$action','$branch','$business')");
	}

	$sql3="DELETE from purchase_totals where id=$purchase_id";
	$sql11=mysqli_query($con,"DELETE from purchases where purchase_id=$purchase_id");
	if (mysqli_query($con,$sql3)) {

   
		 echo "<script>
    
    window.location='new_purchase.php';
   </script>";
	}else{
		echo $sql3."<br>".mysqli_error($con);
	}

       }
	
?>