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

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

$companyId = $_SESSION['company_id'] ?? null;
$isSuper   = !empty($_SESSION['is_super_admin']);

$meterId = isset($_GET['meter_id']) ? (int)$_GET['meter_id'] : 0;

/* ===============================
   Fetch Meters
================================= */
if ($isSuper) {

    $stmt = $pdo->prepare("
        SELECT id, meter_number
        FROM operational_meters
        WHERE status = 'ACTIVE'
        ORDER BY meter_number ASC
    ");
    $stmt->execute();

} else {

    $stmt = $pdo->prepare("
        SELECT id, meter_number
        FROM operational_meters
        WHERE company_id = ?
        AND status = 'ACTIVE'
        ORDER BY meter_number ASC
    ");
    $stmt->execute([$companyId]);

}

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


/* ===============================
   Fetch Reading History
================================= */

$history = [];

if ($meterId > 0) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM meter_readings
        WHERE meter_id = ?
        ORDER BY reading_date DESC, reading_datetime DESC
    ");

    $stmt->execute([$meterId]);

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

require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="container">

<div class="page-header">
<h2>Meter Reading History</h2>
<p class="page-subtitle">
View historical readings captured for operational meters.
</p>
</div>


<!-- ===============================
     Meter Selector
================================= -->

<form method="GET" style="margin-bottom:20px;">

<select name="meter_id" onchange="this.form.submit()" style="padding:8px;">

<option value="">Select Meter</option>

<?php foreach ($meters as $m): ?>

<option value="<?= (int)$m['id'] ?>"
<?= ($meterId == $m['id']) ? 'selected' : '' ?>>

<?= htmlspecialchars($m['meter_number']) ?>

</option>

<?php endforeach; ?>

</select>

</form>


<?php if ($meterId > 0): ?>

<div class="table-wrap">

<table style="width:100%;border-collapse:collapse;">

<thead>

<tr>

<th>Date</th>
<th>Reading Value</th>
<th>Type</th>
<th>Source</th>
<th>Captured</th>

</tr>

</thead>

<tbody>

<?php if (!$history): ?>

<tr>
<td colspan="5" style="text-align:center;">No readings found</td>
</tr>

<?php else: ?>

<?php foreach ($history as $r): ?>

<tr>

<td><?= htmlspecialchars($r['reading_date']) ?></td>

<td><?= number_format($r['reading_value'],3) ?></td>

<td><?= htmlspecialchars($r['reading_type']) ?></td>

<td><?= htmlspecialchars($r['source']) ?></td>

<td><?= htmlspecialchars($r['reading_datetime']) ?></td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

<?php endif; ?>

</div>

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