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

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

/* ==============================
   TENANT / COMPANY ISOLATION
============================== */

$company_id = $_SESSION['company_id'] ?? 0;
$role_id    = $_SESSION['role_id'] ?? 0;

if (!$company_id && $role_id != 7) {
    die("Company not identified.");
}

/* ==============================
   FETCH METERS (TENANT ISOLATION CORRECT)
============================== */

if ($role_id == 7) {
    // SUPER_ADMIN sees everything

    $stmt = $pdo->query("
        SELECT 
            m.*,
            c.company_name
        FROM meters m
        LEFT JOIN companies c 
            ON m.current_holder_company_id = c.id
        ORDER BY m.created_at DESC
    ");

} else {
    // Everyone else sees only meters currently held by their company

    $stmt = $pdo->prepare("
        SELECT 
            m.*,
            c.company_name
        FROM meters m
        LEFT JOIN companies c 
            ON m.current_holder_company_id = c.id
        WHERE m.current_holder_company_id = ?
        ORDER BY m.created_at DESC
    ");

    $stmt->execute([$company_id]);
}

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

/* ==============================
   STATUS HELPER (SAFE + NORMALIZED)
============================== */

function status_class($status) {

    $status = strtoupper(trim((string)$status));

    $allowed = [
        'IN_STOCK',
        'WITH_DISTRIBUTOR',
        'READY_FOR_INSTALL',
        'ACTIVE',
        'FAULTY',
        'REPLACED'
    ];

    return in_array($status, $allowed, true) ? $status : 'IN_STOCK';
}

/* ==============================
   LOAD UNIVERSAL LAYOUT
============================== */

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

<div class="container">

    <div class="page-header">
        <h2>Meter Inventory</h2>
        <p class="page-subtitle">
            Manage all meters in the EDM Core system including stock,
            distributor allocations, installations and faulty units.
        </p>
    </div>

    <div class="topbar">
        <a class="btn" href="add_meter.php">+ Add Meter</a>
        <a class="btn secondary" href="dashboard.php">← Back to Dashboard</a>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Meter Number</th>
                    <th>Type</th>
                    <th>Holder</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>

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

            <?php foreach ($meters as $meter): 

                $meterId     = (int)$meter['id'];
                $meterNumber = htmlspecialchars($meter['meter_number']);
                $meterType   = htmlspecialchars($meter['meter_type']);

                $holder = htmlspecialchars(
                    $meter['company_name'] ?? 'EDM Warehouse'
                );

                $statusRaw  = strtoupper(trim($meter['status'] ?? 'IN_STOCK'));
                $statusSafe = status_class($statusRaw);

            ?>

                <tr>
                    <td><?= $meterNumber ?></td>
                    <td><?= $meterType ?></td>
                    <td><?= $holder ?></td>

                    <td>
                        <span class="status <?= $statusSafe ?>">
                            <?= htmlspecialchars($statusSafe) ?>
                        </span>
                    </td>

                    <td>
                        <div class="actions">

                           <?php if ($statusSafe === 'FAULTY'): ?>

    <a class="action-btn black"
       href="replacement_request.php?meter_id=<?= $meterId ?>">
        Replacement
    </a>

<?php elseif ($statusSafe === 'ACTIVE'): ?>

    <span class="action-btn gray">
        Locked
    </span>

<?php elseif ($statusSafe === 'READY_FOR_INSTALL'): ?>

    <a class="action-btn green"
       href="official_install.php?id=<?= $meterId ?>">
        Official Install
    </a>

<?php else: ?>

    <a class="action-btn"
       href="transfer_meter.php?id=<?= $meterId ?>">
        Transfer
    </a>

    <?php if ($statusSafe === 'WITH_DISTRIBUTOR'): ?>

        <a class="action-btn black"
           href="return_meter.php?id=<?= $meterId ?>">
            Return
        </a>

    <?php endif; ?>

<?php endif; ?>

                        </div>

                        <?php if ($statusSafe === 'FAULTY'): ?>
                            <div class="muted" style="margin-top:6px;">
                                Faulty meters are locked to Replacement workflow.
                            </div>
                        <?php endif; ?>

                    </td>
                </tr>

            <?php endforeach; ?>
            <?php endif; ?>

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

</div>

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