<?php
// Handle stock in/out
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manage_stock'])) {
    $item_id = $_POST['item_id'];
    $type = $_POST['movement_type'];
    $quantity = abs((int)$_POST['quantity']);
    $remarks = trim($_POST['remarks']);
    $moved_by = $_SESSION['admin_name'] ?? 'Admin';

    if ($type === 'OUT') $quantity *= -1;

    // Update quantity
    $connection->query("UPDATE inventory_items SET quantity = quantity + ($quantity) WHERE id = $item_id");

    // Insert movement log
    $stmt = $connection->prepare("INSERT INTO inventory_movements (item_id, movement_type, quantity, remarks, moved_by) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param("isiss", $item_id, $type, abs($quantity), $remarks, $moved_by);
    $stmt->execute();

    $_SESSION['msg'] = "Stock updated successfully.";
    $_SESSION['type'] = "success";
    header("Location: inventory_movement");
    exit;
}

$items = $connection->query("SELECT i.*, c.name AS category FROM inventory_items i LEFT JOIN inventory_categories c ON i.category_id = c.id");
?>

<div class="card">
    <div class="panel panel-primary">
        <div class="panel-heading d-flex justify-content-between align-items-center">
            <h4 class="text-center">Manage Inventory Stock</h4>
        </div>

        <div class="panel-body" style="padding: 20px;">
            <table class="table table-bordered table-striped">
                <thead>
                    <tr class="text-center">
                        <th>S/N</th>
                        <th>Item</th>
                        <th>Category</th>
                        <th>Qty</th>
                        <th>Min Qty</th>
                        <th>Status</th>
                        <th>Stock IN/OUT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; while ($item = $items->fetch_assoc()): ?>
                        <tr class="text-center">
                            <td><?= $sn++ ?></td>
                            <td><?= $item['name'] ?></td>
                            <td><?= $item['category'] ?></td>
                            <td><?= $item['quantity'] ?></td>
                            <td><?= $item['min_quantity'] ?></td>
                            <td>
                                <?php if ($item['quantity'] < $item['min_quantity']): ?>
                                    <span class="badge badge-danger">Low</span>
                                <?php else: ?>
                                    <span class="badge badge-success">OK</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#stockModal<?= $item['id'] ?>">
                                    <i class="fa fa-edit"></i> Adjust
                                </button>
                            </td>
                        </tr>
            
                        <!-- Movement History Row -->
                        <tr>
                            <td colspan="7">
                                <strong>Stock History:</strong>
                                <table class="table table-sm table-hover table-bordered mt-2">
                                    <thead class="text-center">
                                        <tr>
                                            <th>#</th>
                                            <th>Type</th>
                                            <th>Qty</th>
                                            <th>Remarks</th>
                                            <th>By</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody class="text-center">
                                        <?php
                                        $movements = $connection->query("SELECT * FROM inventory_movements WHERE item_id = {$item['id']} ORDER BY id DESC");
                                        $m_sn = 1;
                                        while ($row = $movements->fetch_assoc()):
                                        ?>
                                            <tr>
                                                <td><?= $m_sn++ ?></td>
                                                <td><?= $row['movement_type'] ?></td>
                                                <td><?= $row['quantity'] ?></td>
                                                <td><?= htmlspecialchars($row['remarks']) ?></td>
                                                <td><?= $row['moved_by'] ?></td>
                                                <td><?= date("d M Y, h:i A", strtotime($row['date_moved'])) ?></td>
                                            </tr>
                                        <?php endwhile; ?>
                                        <?php if ($m_sn === 1): ?>
                                            <tr><td colspan="6" class="text-muted text-center">No movements yet.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            
            <!-- ✅ All Stock Modals (after the table) -->
            <?php
            $items->data_seek(0); // Reset result set for modal loop
            while ($item = $items->fetch_assoc()):
            ?>
            <div class="modal fade" id="stockModal<?= $item['id'] ?>" tabindex="-1" role="dialog">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <form method="POST" action="">
                        <div class="modal-header bg-info text-white">
                            <h5 class="modal-title">Adjust Stock - <?= $item['name'] ?></h5>
                            <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                        </div>
            
                        <div class="modal-body">
                            <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                            <div class="form-group">
                                <label>Movement Type</label>
                                <select name="movement_type" class="form-control" required>
                                    <option value="IN">Stock IN</option>
                                    <option value="OUT">Stock OUT</option>
                                </select>
                            </div>
            
                            <div class="form-group">
                                <label>Quantity</label>
                                <input type="number" name="quantity" class="form-control" min="1" required>
                            </div>
            
                            <div class="form-group">
                                <label>Remarks</label>
                                <textarea name="remarks" class="form-control" placeholder="E.g., received shipment, damaged stock, etc."></textarea>
                            </div>
                        </div>
            
                        <div class="modal-footer">
                            <button type="submit" name="manage_stock" class="btn btn-success">
                                <i class="fa fa-save"></i> Save
                            </button>
                        </div>
                    </form>
                </div>
              </div>
            </div>
            <?php endwhile; ?>

        </div>
    </div>
</div>
