<?php
include "config.php";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id'], $_POST['issued_qty'])) {
    $order_item_id = intval($_POST['order_id']);   
    $new_issue     = intval($_POST['issued_qty']); // new issued qty

    // get total quantity
    $sql = "SELECT order_id, quantity 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'];
        $total_qty = (int)$data['quantity'];

        if ($new_issue > $total_qty) {
            echo "<script>alert('Error: Issued quantity cannot exceed total quantity!');
                  window.location.href = 'manage.php?order_id={$order_id}';</script>";
            exit;
        }

        $balance_qty = $total_qty - $new_issue;
        $status = $new_issue == 0 ? "Confirmed" : ($new_issue < $total_qty ? "Processing" : "Delivered");

        $update = "UPDATE order_items 
                   SET issued_qty = $new_issue, 
                       balance_qty = $balance_qty, 
                       status = '$status' 
                   WHERE id = $order_item_id";

        if (mysqli_query($con, $update)) {
            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 item not found!');window.location.href = 'manage-orders';</script>";
    }
}
?>
