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

$sql1=mysqli_query($con,"SELECT *,(SELECT saletype from sales where id=sales_details.order_id) as saletype, (SELECT staff from sales where id=sales_details.order_id) as staff from sales_details where order_id=$orderid");
	while ($result1=mysqli_fetch_array($sql1)) {
		$product_id=$result1['product_id'];
		$quantity=$result1['quantity'];	
		$selling=$result1['selling_price'];	
		$staff=$result1['staff'];
		$saletype=$result1['saletype'];
		if ($saletype==1) {
                $sst="Wholesale";
            }else{
                $sst="Retail";
            }
		 $tlogsql=mysqli_fetch_array(mysqli_query($con,"select * from products where id='$product_id'"));
        $pname=$tlogsql['product_name'];

		$sql2=mysqli_query($con,"INSERT into temp(saletype,product_id,quantity,unit_price,staff,branch_id,user,business_id) Values('$saletype','$product_id','$quantity','$selling','$staff','$branch','$id_user','$business')");
		$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=$sst." Sale: Recorded a sales return of product with details"."<br> product Name: ".$pname."<br> product Unit price: ".$selling."<br> product quantity: ".$quantity."<br> total_price: ".$selling*$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 sales where id=$orderid";
	$sql11=mysqli_query($con,"DELETE from sales_details where order_id=$orderid");
	if (mysqli_query($con,$sql3)) {

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