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

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

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

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

if(!$meterId){
    die("Invalid meter");
}

/* ===============================
GET METER
================================ */

$stmt = $pdo->prepare("
SELECT meter_number, unit_name
FROM operational_meters
WHERE id = ?
");
$stmt->execute([$meterId]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* ===============================
GET TENANT HISTORY
================================ */

$stmt = $pdo->prepare("
SELECT 
tenant_name,
tenant_phone,
tenant_email,
start_date,
end_date,
active
FROM meter_tenants
WHERE meter_id = ?
ORDER BY start_date DESC
");
$stmt->execute([$meterId]);
$tenants = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="container">

<div class="page-header">
<h2>Tenant History</h2>
<p class="page-subtitle">
Meter: <?= htmlspecialchars($meter['meter_number']) ?> — <?= htmlspecialchars($meter['unit_name'] ?? '') ?>
</p>
</div>

<div class="stat-card">

<table style="width:100%;border-collapse:collapse;" border="1">
<thead style="background:#f2f2f2;">
<tr>
<th>Tenant</th>
<th>Phone</th>
<th>Email</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>

<tbody>

<?php if(empty($tenants)): ?>
<tr>
<td colspan="6" style="text-align:center;color:#999;">
No tenant history found
</td>
</tr>
<?php endif; ?>

<?php foreach($tenants as $t): ?>
<tr>

<td><?= htmlspecialchars($t['tenant_name'] ?? '') ?></td>
<td><?= htmlspecialchars($t['tenant_phone'] ?? '') ?></td>
<td><?= htmlspecialchars($t['tenant_email'] ?? '') ?></td>

<td><?= htmlspecialchars($t['start_date'] ?? '') ?></td>

<td>
<?php if($t['end_date']): ?>
<?= htmlspecialchars($t['end_date']) ?>
<?php else: ?>
<span style="color:green;">Active</span>
<?php endif; ?>
</td>

<td>
<?php if($t['active']): ?>
<span style="color:green;font-weight:bold;">ACTIVE</span>
<?php else: ?>
<span style="color:#999;">HISTORY</span>
<?php endif; ?>
</td>

</tr>
<?php endforeach; ?>

</tbody>
</table>

</div>

<br>

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

</div>

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