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

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

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

if (!$meterId) {
    die("Meter ID missing.");
}

/* ===============================
   Load Meter
================================= */

$stmt = $pdo->prepare("
SELECT om.*, c.company_name, t.tariff_name
FROM operational_meters om
LEFT JOIN companies c ON c.id = om.company_id
LEFT JOIN tariffs t ON t.id = om.tariff_id
WHERE om.id = ?
");

$stmt->execute([$meterId]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$meter) {
    die("Meter not found.");
}


/* ===============================
   Latest Reading
================================= */

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

$stmt->execute([$meterId]);
$latestReading = $stmt->fetch(PDO::FETCH_ASSOC);


/* ===============================
   Consumption Graph Data
================================= */

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

$stmt->execute([$meterId]);
$graphReadings = $stmt->fetchAll(PDO::FETCH_ASSOC);

$labels = [];
$data = [];

$previous = null;

foreach ($graphReadings as $r) {

$current = (float)$r['reading_value'];

if ($previous !== null) {

$labels[] = $r['reading_date'];
$data[] = $current - $previous;

}

$previous = $current;

}

/* ===============================
   Consumption Analysis
================================= */

$avgConsumption = 0;
$maxConsumption = 0;
$alerts = [];

if(count($data) > 0){

$avgConsumption = array_sum($data) / count($data);
$maxConsumption = max($data);

foreach($data as $k => $v){

if($avgConsumption > 0 && $v > ($avgConsumption * 3)){

$alerts[] = [
'date' => $labels[$k],
'value' => $v
];

}

}

}

/* ===============================
   Last 10 Readings
================================= */

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

$stmt->execute([$meterId]);
$readings = $stmt->fetchAll(PDO::FETCH_ASSOC);


/* ===============================
   Last 5 Invoices
================================= */

$stmt = $pdo->prepare("
SELECT invoice_number, total, invoice_date
FROM invoices
WHERE meter_id = ?
ORDER BY invoice_date DESC
LIMIT 5
");

$stmt->execute([$meterId]);
$invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">

<div class="page-header">
<h2>Meter Dashboard</h2>
<p class="page-subtitle">
Operational overview of the selected meter.
</p>
</div>


<div class="stat-card">

<h3>Meter Information</h3>

<p><strong>Meter Number:</strong> <?= htmlspecialchars($meter['meter_number']) ?></p>

<p><strong>Company:</strong> <?= htmlspecialchars($meter['company_name'] ?? '-') ?></p>

<p><strong>Tariff:</strong> <?= htmlspecialchars($meter['tariff_name'] ?? '-') ?></p>

<p><strong>Status:</strong> <?= htmlspecialchars($meter['status']) ?></p>

</div>



<div class="stat-card">

<h3>Latest Reading</h3>

<?php if ($latestReading): ?>

<p>
<strong><?= number_format($latestReading['reading_value'],3) ?></strong>
</p>

<p class="muted">
Captured: <?= htmlspecialchars($latestReading['reading_date']) ?>
</p>

<?php else: ?>

<p>No readings captured yet.</p>

<?php endif; ?>

</div>



<div class="stat-card">

<h3>Consumption Graph</h3>

<div style="margin-bottom:10px;font-size:13px;color:#555;">

Average Consumption:
<strong><?= number_format($avgConsumption,2) ?></strong>

&nbsp;&nbsp;&nbsp;

Peak Consumption:
<strong><?= number_format($maxConsumption,2) ?></strong>

</div>

<canvas id="usageChart" height="120"></canvas>

<?php if(!empty($alerts)): ?>

<div style="margin-top:10px;color:#c62828;font-size:13px;">

<strong>⚠ Abnormal Consumption Detected</strong>

<ul>

<?php foreach($alerts as $a): ?>

<li>
<?= htmlspecialchars($a['date']) ?> :
<?= number_format($a['value'],2) ?>
</li>

<?php endforeach; ?>

</ul>

</div>

<?php endif; ?>

</div>



<div class="stat-card">

<h3>Recent Readings</h3>

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

<tr>
<th>Date</th>
<th>Reading</th>
</tr>

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

<tr>

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

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

</tr>

<?php endforeach; ?>

</table>

</div>



<div class="stat-card">

<h3>Recent Invoices</h3>

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

<tr>
<th>Invoice</th>
<th>Date</th>
<th>Total</th>
</tr>

<?php foreach ($invoices as $i): ?>

<tr>

<td><?= htmlspecialchars($i['invoice_number']) ?></td>

<td><?= htmlspecialchars($i['invoice_date']) ?></td>

<td>R <?= number_format($i['total'],2) ?></td>

</tr>

<?php endforeach; ?>

</table>

</div>

</div>


<script>

const labels = <?= json_encode($labels) ?>;
const data = <?= json_encode($data) ?>;

const ctx = document.getElementById('usageChart');

if(ctx){

new Chart(ctx, {

type: 'line',

data: {

labels: labels,

datasets: [{
label: 'Consumption',
data: data,
borderColor: '#f2531e',
backgroundColor: 'rgba(242,83,30,0.1)',
tension: 0.3,
fill: true
}]

},

options: {

responsive: true,

scales: {
y: {
beginAtZero: true
}
}

}

});

}

</script>

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