<?php
// include "config.php";

// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//     $order_id = intval($_POST['id']);
//     $action   = $_POST['action'];

//     if ($action === "approve") {
//         $status = "Confirmed";
//     } elseif ($action === "reject") {
//         $status = "Cancelled";
//     } else {
//         echo "Invalid action";
//         exit;
//     }

//     $sql = "UPDATE orders SET status = '$status' WHERE id = $order_id";

//     if (mysqli_query($con, $sql)) {
//         echo "success";
//     } else {
//         echo "error";
//     }
// }
?>

<?php
include "config.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = intval($_POST['id']);
    $action   = $_POST['action']; // approve or reject

    if ($action === "approve") {
        $status = "Processing";
    } elseif ($action === "reject") {
        $status = "Cancelled";
    } elseif ($action === "Delivered") {
        $status = "Delivered";
    }
    
    else {
        echo "Invalid action";
        exit;
    }

    // Update order status
    $sql = "UPDATE order_items SET status = '$status' WHERE id = $order_id";
    if (mysqli_query($con, $sql)) {

        // If cancelled, restore stock
        if ($status == "Cancelled") {
            $items_sql = "SELECT product_id, quantity FROM order_items WHERE id = $order_id";
            $items_res = mysqli_query($con, $items_sql);

            while ($row = mysqli_fetch_assoc($items_res)) {
                $product_id = $row['product_id'];
                $qty        = $row['quantity'];

                // Restore stock in tbl_stock_items
                $update_stock = "UPDATE tbl_stock_items 
                                 SET stock = stock + $qty 
                                 WHERE id = $product_id";
                mysqli_query($con, $update_stock);
            }
        }

        echo "success";
    } else {
        echo "error";
    }
}
?>
