<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

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

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

$meterId = $_GET['id'] ?? 0;

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

/* ===============================
LOAD METER
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM operational_meters
WHERE id = ?
");

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

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

/* ===============================
LOAD COMPANY
================================ */

$stmt = $pdo->prepare("
SELECT company_name
FROM companies
WHERE id = ?
");

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

/* ===============================
LOAD TARIFF
================================ */

$stmt = $pdo->prepare("
SELECT tariff_name
FROM tariffs
WHERE id = ?
");

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

/* ===============================
LOAD CHARGES
================================ */

$stmt = $pdo->prepare("
SELECT bc.charge_name
FROM meter_charges mc
JOIN billing_charges bc ON bc.id = mc.charge_id
WHERE mc.meter_id = ?
");

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

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

<div class="container">

<div class="page-header">
<h2>Meter Profile</h2>
</div>

<div class="stat-card">

<h3>Meter Information</h3>

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

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

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

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

</div>


<div class="stat-card">

<h3>Charges</h3>

<?php if($charges): ?>

<ul>

<?php foreach($charges as $c): ?>

<li><?= htmlspecialchars($c['charge_name']) ?></li>

<?php endforeach; ?>

</ul>

<?php else: ?>

<p>No charges assigned</p>

<?php endif; ?>

</div>


<div class="stat-card">

<h3>Billing</h3>

<a href="/core/modules/billing/invoices/index.php?meter_id=<?= $meterId ?>">
View Invoices
</a>

</div>

</div>

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