<?php
require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('inventory.manage');

require_once __DIR__ . '/../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;
$role = $_SESSION['role_name'] ?? '';

if ($role === 'SUPER_ADMIN') {
    $stmt = $pdo->query("
        SELECT u.*, p.brand, p.model
        FROM inventory_units u
        JOIN inventory_products p ON u.product_id = p.id
        ORDER BY u.created_at DESC
    ");
} else {
    $stmt = $pdo->prepare("
        SELECT u.*, p.brand, p.model
        FROM inventory_units u
        JOIN inventory_products p ON u.product_id = p.id
        WHERE u.company_id = ?
        ORDER BY u.created_at DESC
    ");
    $stmt->execute([$company_id]);
}

$units = $stmt->fetchAll(PDO::FETCH_ASSOC);

$breadcrumb = "Inventory Units";
require_once __DIR__ . '/../../includes/layout.php';
?>

<div class="container">

    <div class="page-header">
        <h2>Inventory Units</h2>
        <p class="page-subtitle">
            Physical device tracking (serial-level inventory).
        </p>
    </div>

    <div class="topbar">
        <a class="btn" href="add_unit.php">+ Add Unit</a>
        <a class="btn secondary" href="../operations/meters.php">← Back to All Meters</a>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
 <th>Meter</th>
<th>Product</th>
<th>Status</th>
<th>Created</th>
<th>Action</th>
                </tr>
            </thead>
            <tbody>

            <?php if (!$units): ?>
                <tr>
                    <td colspan="4">No units found.</td>
                </tr>
            <?php else: ?>

            <?php foreach ($units as $u): ?>
                <tr>
    <td><?= htmlspecialchars($u['meter_number']) ?></td>
    <td><?= htmlspecialchars($u['brand'] . ' ' . $u['model']) ?></td>
    <td><?= htmlspecialchars($u['status']) ?></td>
    <td><?= htmlspecialchars($u['created_at']) ?></td>

    <td>
        <?php if ($u['status'] !== 'ACTIVE' && $u['status'] !== 'REPLACED'): ?>
            <a class="btn small"
               href="move_unit.php?id=<?= $u['id'] ?>">
               Move
            </a>
        <?php else: ?>
            <span class="muted">Locked</span>
        <?php endif; ?>
    </td>
</tr>
            <?php endforeach; ?>

            <?php endif; ?>

            </tbody>
        </table>
    </div>

</div>

<?php require_once __DIR__ . '/../../includes/layout_footer.php'; ?>