<?php
include "config.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id'], $_POST['issued_qty'])) {
    $order_item_id = intval($_POST['order_id']);   // actually this is item_id, not whole order
    $new_issue     = intval($_POST['issued_qty']); // user entered issued quantity (increment value)

    // get existing values for that order_item
    $sql = "SELECT order_id, quantity, issued_qty, balance_qty 
            FROM order_items 
            WHERE id = $order_item_id";
    $res = mysqli_query($con, $sql);

    if ($res && mysqli_num_rows($res) > 0) {
        $data = mysqli_fetch_assoc($res);

        $order_id     = (int)$data['order_id'];  // parent order id
        $total_qty    = (int)$data['quantity'];
        $issued_qty   = (int)$data['issued_qty'];
        $balance_qty  = (int)$data['balance_qty'];

        // calculate possible new issued qty
        $updated_issued  = $issued_qty + $new_issue;
        $updated_balance = $total_qty - $updated_issued;

        if ($updated_issued > $total_qty) {
            // echo "<script>alert('Error: Issued quantity cannot exceed total quantity!');window.location.href = 'manage-orders';</script>";
                    echo "<script>
                            alert('Error: Issued quantity cannot exceed total quantity!');
                            window.location.href = 'manage.php?order_id={$order_id}';
                        </script>";
        } else {
            // update this order_item
            $update = "UPDATE order_items 
                       SET issued_qty = $updated_issued, 
                           balance_qty = $updated_balance 
                       WHERE id = $order_item_id";
            if (mysqli_query($con, $update)) {

                // 🔹 check if all items of this order are fully issued
                $check = mysqli_query($con, 
                    "SELECT SUM(balance_qty) AS remaining 
                     FROM order_items 
                     WHERE order_id = $order_id");
                $rowCheck = mysqli_fetch_assoc($check);

                if ($rowCheck && (int)$rowCheck['remaining'] === 0) {
                    // if all balance = 0 → Delivered
                    // mysqli_query($con, "UPDATE orders SET status = 'Delivered' WHERE id = $order_id");
                    mysqli_query($con, "UPDATE order_items SET status = 'Delivered' WHERE id = $order_item_id");
                }

                echo "<script>
                        alert('Issued quantity updated successfully');
                       
                        window.location.href = 'manage.php?order_id={$order_id}';
                    </script>";
            } else {
                echo "<script>alert('DB Error: " . mysqli_error($con) . "');</script>";
            }
        }
    } else {
        echo "<script>alert('Order not found!');window.location.href = 'manage-orders';</script>";
    }
}
?>
