<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$store_id = 3; // Housekeeping Store
$requisition_id = intval($_GET['requisition_id'] ?? 0);

// ==================== Fetch Requisition ====================
$req = $conn->query("SELECT * FROM hk_requisitions WHERE id=$requisition_id AND status='Approved'")->fetch_assoc();
if(!$req){
    echo "<script>alert('Invalid or non-approved requisition');window.location='hk_inventory.php';</script>";
    exit;
}

// ==================== Submit Dispatch ====================
if(isset($_POST['dispatch'])){
    $recipient = $conn->real_escape_string($_POST['recipient'] ?? '');
    $remarks   = $conn->real_escape_string($_POST['remarks'] ?? '');

    foreach($_POST['dispatch_qty'] as $item_id => $qty){
        $qty = intval($qty);
        if($qty > 0){
            // Reduce stock
            $conn->query("UPDATE product_stock 
                          SET quantity = quantity - $qty 
                          WHERE product_id=$item_id AND store_id=$store_id");

            // Record dispatch
            $conn->query("INSERT INTO hk_dispatch_items(requisition_id, product_id, quantity, dispatched_by, recipient, remarks) 
                          VALUES($requisition_id, $item_id, $qty, {$_SESSION['user_id']}, '$recipient', '$remarks')");
        }
    }

    // Mark requisition as dispatched
    $conn->query("UPDATE hk_requisitions SET status='Dispatched' WHERE id=$requisition_id");

    echo "<script>alert('Stock dispatched successfully');window.location='hk_inventory.php';</script>";
    exit;
}

// ==================== Fetch Requisition Items ====================
$items = $conn->query("
    SELECT hki.*, p.name, ps.quantity AS available_stock
    FROM hk_requisition_items hki
    LEFT JOIN products p ON hki.product_id=p.id
    LEFT JOIN product_stock ps ON hki.product_id=ps.product_id AND ps.store_id=$store_id
    WHERE hki.requisition_id=$requisition_id
");
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<button class="btn btn-secondary mb-3" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
<h3 class="text-center">🚚 Dispatch Stock for Requisition #<?= $requisition_id ?></h3>
<hr>

<form method="POST">
<div class="row mb-3">
    <div class="col-md-6">
        <label>Recipient Name <span class="text-danger">*</span></label>
        <input type="text" name="recipient" class="form-control" placeholder="Enter recipient name" required>
    </div>
    <div class="col-md-6">
        <label>Remarks / Notes</label>
        <input type="text" name="remarks" class="form-control" placeholder="Optional notes for dispatch">
    </div>
</div>

<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
<th>#</th>
<th>Product</th>
<th>Requested Qty</th>
<th>Available Stock</th>
<th>Dispatch Qty</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
while($row = $items->fetch_assoc()):
    $available = intval($row['available_stock']);
?>
<tr>
<td><?= $i ?></td>
<td><?= htmlspecialchars($row['name']) ?></td>
<td><?= $row['quantity'] ?></td>
<td><?= $available ?></td>
<td>
<!-- Removed min/max validation -->
<input type="number" name="dispatch_qty[<?= $row['product_id'] ?>]" 
       value="<?= $row['quantity'] ?>" 
       class="form-control">
</td>
</tr>
<?php $i++; endwhile; ?>
</tbody>
<tfoot>
<tr class="fw-bold bg-light">
<td colspan="4" class="text-end">Total Dispatch Qty:</td>
<td id="totalDispatch">0</td>
</tr>
</tfoot>
</table>

<button type="submit" name="dispatch" class="btn btn-primary w-100">
<i class="fa fa-truck"></i> Dispatch Selected Stock
</button>
</form>
</div>

<script>
// Calculate total dispatch dynamically
const inputs = document.querySelectorAll('input[name^="dispatch_qty"]');
const totalField = document.getElementById('totalDispatch');

function updateTotal() {
    let total = 0;
    inputs.forEach(input => total += parseInt(input.value) || 0);
    totalField.innerText = total;
}

inputs.forEach(input => input.addEventListener('input', updateTotal));
updateTotal();
</script>

<?php include 'includes/footer.php'; ?>
