<?php
require_once __DIR__ . '/../include/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') die('Invalid Request');

$order_id     = intval($_POST['order_id']);
$assign_qty   = intval($_POST['assign_qty']);
$delivery_man = intval($_POST['delivery_man']);

// basic validation
if ($order_id <= 0) die("Order invalid");
if ($assign_qty <= 0) die("Invalid assign qty");
if ($delivery_man <= 0) die("Please select delivery man");

// compute available from order_measurements
$st = $conn->prepare("SELECT IFNULL(SUM(total_qty),0) AS total, IFNULL(SUM(delivered_qty),0) AS delivered FROM order_measurements WHERE order_id = ?");
$st->bind_param('i', $order_id);
$st->execute();
$stRow = $st->get_result()->fetch_assoc();

$total = intval($stRow['total']);
$delivered = intval($stRow['delivered']);
$available = $total - $delivered;
if ($available < 0) $available = 0;

if ($assign_qty > $available) {
    die("Error: Trying to assign more than available (available = $available).");
}

// insert order-level assignment (measurement_id = NULL)
$stmt = $conn->prepare("
    INSERT INTO delivery_assignments
    (order_id, measurement_id, assigned_qty, delivery_man_id, status, delivered_qty, assign_date)
    VALUES (?, NULL, ?, ?, 'assigned', 0, NOW())
");
$stmt->bind_param("iii", $order_id, $assign_qty, $delivery_man);
$stmt->execute();
$stmt->close();

// Note: we do not change orders.status here — status is controlled by delivered_qty totals.
// redirect back
header("Location: orders_list.php?msg=assigned");
exit;
?>