<?php

include 'load.php';

?>
<?php
require_once 'header.php';
?>

<?php
require_once 'navbar.php';
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $products = $_POST['products'];
    $order_id = $_POST['order_id'];
    $customer_name =$_POST['customer_name'];
    $stock ='';
    $total_margin = 0;
    
    foreach ($products as $proid => $productData) {
        $quantity = $productData['quantity'];

        $sql =  "SELECT * FROM tbl_stock WHERE prid='$proid'";
        $result = $conn->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                $stock = $row['qty'];
            }
            $dec_quantity = $stock + $quantity;
            $update =  "UPDATE tbl_stock SET qty = '$dec_quantity' WHERE prid='$proid'";
           if( $conn->query($update) === true){
            echo "Record updated successfully";
           }else{
            echo"record update fail";
           };
           
        }

        echo "Product ID: $proid, Quantity: $quantity <br>";
        // save return products
        $insert = "INSERT INTO tbl_return_items (prid, qty, order_id) VALUES ('$proid', '$quantity', '$order_id')";

        if ($conn->query($insert) === TRUE) {
            echo "Successfully inserted";
        } else {
            echo "Error: " . $insert . "<br>" . $conn->error;
        }
        
        // get amount of return product
        $fetch = "SELECT profitmargin FROM mobileproducts WHERE prid='$proid'";

        $fetch_query = $conn->query($fetch);
        
        if ($fetch_query) {
            if ($fetch_query->num_rows > 0) {
                $margin = $fetch_query->fetch_assoc();
               $real_margin = $margin['profitmargin']; 
               $total_margin += $real_margin;
            } else {
                echo "No results found.";
            }
        } else {
            echo "Error: " . $conn->error;
        }
    }
    // insert data to table return
    $return_datetime = date("Y/m/d");

    $insert_return = "INSERT INTO tbl_return (order_id, return_datetime, return_amount) VALUES ('$order_id', '$return_datetime', '$total_margin')";
    
    if ($conn->query($insert_return) === true) {
        // header("Location: salesreturnlist.php"); // Redirect to new.php
        echo '<script>window.location.href = "createsales_return.php";</script>';
        exit();
    } else {
        echo "Error: " . $insert_return . "<br>" . $conn->error;
    }
    
}
?>
