<?php
require_once __DIR__ . '/../include/db.php';

$order_id = intval($_GET['id'] ?? 0);
if (!$order_id) die('Order ID missing.');

$orderRes = $conn->prepare("SELECT id, buyer_name FROM orders WHERE id = ?");
$orderRes->bind_param('i', $order_id);
$orderRes->execute();
$order = $orderRes->get_result()->fetch_assoc();
if (!$order) die('Order not found.');


// Total qty from measurements
$q1 = $conn->prepare("SELECT IFNULL(SUM(total_qty),0) AS total FROM order_measurements WHERE order_id = ?");
$q1->bind_param('i', $order_id);
$q1->execute();
$total = $q1->get_result()->fetch_assoc()['total'];

// Delivered qty from assignments
$q2 = $conn->prepare("SELECT IFNULL(SUM(delivered_qty),0) AS delivered FROM delivery_assignments WHERE order_id = ?");
$q2->bind_param('i', $order_id);
$q2->execute();
$delivered = $q2->get_result()->fetch_assoc()['delivered'];

$available = $total - $delivered;
if ($available < 0) $available = 0;


// delivery men
$dmRes = $conn->query("SELECT id, name FROM delivery_men WHERE active = 1 ORDER BY name ASC");
?>
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Assign Order <?= $order_id ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="p-4">
<div class="container">
    <h3>Assign Order #<?= $order['id'] ?> — <?= htmlspecialchars($order['buyer_name']) ?></h3>

    <div class="card my-3 p-3">
        <p><strong>Total Qty:</strong> <?= $total ?></p>
        <p><strong>Already Delivered:</strong> <?= $delivered ?></p>
        <p><strong>Available to Assign:</strong> <?= $available ?></p>

        <form method="post" action="assign_submit.php">
            <input type="hidden" name="order_id" value="<?= $order_id ?>">

            <div class="mb-3">
                <label class="form-label">Select Delivery Man</label>
                <select name="delivery_man" class="form-select" required>
                    <option value="">-- select --</option>
                    <?php while($d = $dmRes->fetch_assoc()): ?>
                        <option value="<?= intval($d['id']) ?>"><?= htmlspecialchars($d['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label">Assign Qty</label>
                <input type="number" name="assign_qty" class="form-control" min="1" max="<?= $available ?>" required>
            </div>

            <button class="btn btn-success">Assign</button>
            <a href="order_list.php" class="btn btn-secondary">Back</a>
        </form>
    </div>
</div>
</body>
</html>
