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

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

if (!isset($_GET['id'])) {
    die("Meter ID missing.");
}

$meterId   = (int)$_GET['id'];
$role      = $_SESSION['role_name'] ?? '';
$companyId = $_SESSION['company_id'] ?? null; // kept for compatibility

/* ===============================
   Fetch Operational Meter (UPDATED)
================================= */

if ($role === 'SUPER_ADMIN') {
    $stmt = $pdo->prepare("
        SELECT 
            om.*,
            ba.account_name,
            bc.customer_name
        FROM operational_meters om
        LEFT JOIN billing_accounts ba ON om.account_id = ba.id
        LEFT JOIN billing_customers bc ON ba.customer_id = bc.id
        WHERE om.id = ?
        LIMIT 1
    ");
    $stmt->execute([$meterId]);
} else {
    $stmt = $pdo->prepare("
        SELECT 
            om.*,
            ba.account_name,
            bc.customer_name
        FROM operational_meters om
        LEFT JOIN billing_accounts ba ON om.account_id = ba.id
        LEFT JOIN billing_customers bc ON ba.customer_id = bc.id
        WHERE om.id = ?
        LIMIT 1
    ");
    $stmt->execute([$meterId]);
}

$meter = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$meter) {
    die("Operational meter not found or access denied.");
}

/* ===============================
   Fetch Status History
================================= */

$stmt = $pdo->prepare("
    SELECT h.*, u.full_name
    FROM operational_meter_status_history h
    LEFT JOIN users u ON u.id = h.changed_by
    WHERE h.operational_meter_id = ?
    ORDER BY h.id DESC
");
$stmt->execute([$meterId]);
$history = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">

    <div class="page-header">
        <h2>Meter Details</h2>
        <p class="page-subtitle">
            Operational meter overview.
        </p>
    </div>

    <!-- ALERTS -->

    <?php if (!empty($_SESSION['error'])): ?>
        <div style="background:#fee2e2; color:#991b1b; padding:12px; margin-bottom:15px; border-radius:6px;">
            <?= htmlspecialchars($_SESSION['error']) ?>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION['success'])): ?>
        <div style="background:#dcfce7; color:#166534; padding:12px; margin-bottom:15px; border-radius:6px;">
            <?= htmlspecialchars($_SESSION['success']) ?>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <div class="topbar">
        <a class="btn secondary" href="meters.php">
            ← Back to Operational Meters
        </a>
    </div>

    <!-- ===============================
         METER INFO
    ================================== -->

    <div class="table-wrap" style="margin-top:20px; overflow-x:auto;">
        <table style="min-width:900px; width:100%; border-collapse:collapse;">
            <tbody>

                <?php
                $rows = [
                    'ID' => $meter['id'],
                    'Meter Number' => $meter['meter_number'],

                    // 🔥 UPDATED FIELD
                    'Customer / Account' => 
                        (!empty($meter['customer_name']) || !empty($meter['account_name']))
                        ? htmlspecialchars($meter['customer_name'] ?? 'N/A') . ' - ' . htmlspecialchars($meter['account_name'] ?? 'N/A')
                        : '<span style="color:#999;">Unassigned</span>',

                    'Status' => '<span class="status ' . htmlspecialchars($meter['status']) . '">' . htmlspecialchars($meter['status']) . '</span>',
                    'Activated At' => $meter['activated_at'],
                    'Created By (User ID)' => $meter['created_by'],
                    'Created At' => $meter['created_at'],
                ];

                foreach ($rows as $label => $value):
                ?>
                    <tr>
                        <th style="background:#0f172a; color:white; text-align:left; padding:14px; width:35%;">
                            <?= htmlspecialchars($label) ?>
                        </th>
                        <td style="padding:14px;">
                            <?= $value ?>
                        </td>
                    </tr>
                <?php endforeach; ?>

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

    <!-- ===============================
         LIFECYCLE ACTIONS
    ================================== -->

    <div style="margin-top:30px;">

        <h3>Lifecycle Actions</h3>

        <?php if ($meter['status'] === 'ACTIVE'): ?>

            <form method="POST" action="meter_action.php" style="margin-bottom:15px;">
                <input type="hidden" name="meter_id" value="<?= $meter['id'] ?>">
                <input type="text"
                       name="reason"
                       placeholder="Reason for suspension"
                       style="width:100%; padding:8px; margin-bottom:8px;">
                <button class="btn warning" name="action" value="suspend">
                    Suspend
                </button>
            </form>

            <form method="POST" action="meter_action.php">
                <input type="hidden" name="meter_id" value="<?= $meter['id'] ?>">
                <input type="text"
                       name="reason"
                       placeholder="Reason for disconnection"
                       style="width:100%; padding:8px; margin-bottom:8px;">
                <button class="btn danger" name="action" value="disconnect">
                    Disconnect
                </button>
            </form>

        <?php elseif ($meter['status'] === 'SUSPENDED'): ?>

            <form method="POST" action="meter_action.php" style="margin-bottom:15px;">
                <input type="hidden" name="meter_id" value="<?= $meter['id'] ?>">
                <button class="btn success" name="action" value="activate">
                    Activate
                </button>
            </form>

            <form method="POST" action="meter_action.php">
                <input type="hidden" name="meter_id" value="<?= $meter['id'] ?>">
                <input type="text"
                       name="reason"
                       placeholder="Reason for disconnection"
                       style="width:100%; padding:8px; margin-bottom:8px;">
                <button class="btn danger" name="action" value="disconnect">
                    Disconnect
                </button>
            </form>

        <?php elseif ($meter['status'] === 'DISCONNECTED'): ?>

            <div class="muted">
                This meter has been permanently disconnected.
            </div>

        <?php endif; ?>

    </div>

    <!-- ===============================
         STATUS HISTORY
    ================================== -->

    <div style="margin-top:40px;">
        <h3>Status History</h3>

        <div class="table-wrap" style="margin-top:15px; overflow-x:auto;">
            <table style="min-width:1000px; width:100%; border-collapse:collapse;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Old Status</th>
                        <th>New Status</th>
                        <th>Reason</th>
                        <th>Changed By</th>
                        <th>Changed At</th>
                    </tr>
                </thead>

                <tbody>

                    <?php if (!$history): ?>
                        <tr>
                            <td colspan="6">No status changes recorded.</td>
                        </tr>
                    <?php else: ?>

                        <?php foreach ($history as $h): ?>
                            <tr>
                                <td><?= htmlspecialchars($h['id']) ?></td>
                                <td><?= htmlspecialchars($h['old_status']) ?></td>
                                <td>
                                    <span class="status <?= htmlspecialchars($h['new_status']) ?>">
                                        <?= htmlspecialchars($h['new_status']) ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars($h['reason'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($h['full_name'] ?? $h['changed_by']) ?></td>
                                <td><?= htmlspecialchars($h['changed_at']) ?></td>
                            </tr>
                        <?php endforeach; ?>

                    <?php endif; ?>

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

</div>

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