<?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';

/* ===============================
LOAD ALL ACTIVE TENANTS
================================ */

$tenants = $pdo->query("
SELECT 
mt.id,
mt.tenant_name,
mt.tenant_phone,
mt.start_date,
m.meter_number,
m.unit_name,
a.account_name
FROM meter_tenants mt
LEFT JOIN operational_meters m ON mt.meter_id = m.id
LEFT JOIN billing_accounts a ON m.account_id = a.id
WHERE mt.active = 1
ORDER BY mt.start_date DESC
")->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="container">

<div class="page-header">
<h2>Tenant Management</h2>
<p class="page-subtitle">All active tenants</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>Meter</th>
<th>Unit</th>
<th>Property</th>
<th>Start Date</th>
</tr>
</thead>

<tbody>

<?php if(empty($tenants)): ?>
<tr>
<td colspan="6" style="text-align:center;color:#999;">
No active tenants
</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['meter_number'] ?? '') ?></td>
<td><?= htmlspecialchars($t['unit_name'] ?? '') ?></td>
<td><?= htmlspecialchars($t['account_name'] ?? '') ?></td>
<td><?= htmlspecialchars($t['start_date'] ?? '') ?></td>
</tr>
<?php endforeach; ?>

</tbody>

</table>

</div>

</div>

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