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

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

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

/* ======================
PAGINATION SETUP
====================== */
$limit = 10; // rows per page

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$search  = $_GET['search'] ?? '';
$account = $_GET['account'] ?? '';

if($page < 1) $page = 1;

$offset = ($page - 1) * $limit;

/* ======================
LOAD ACCOUNTS FOR FILTER
====================== */
$accountsList = $pdo->query("
SELECT id, account_name 
FROM billing_accounts 
ORDER BY account_name
")->fetchAll(PDO::FETCH_ASSOC);

$where = [];
$params = [];

/* SEARCH */
if($search !== ''){
    $where[] = "(om.unit_name LIKE ? OR a.account_name LIKE ? OR om.account_id LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

/* ACCOUNT FILTER */
if($account !== ''){
    $where[] = "a.account_name = ?";
    $params[] = $account;
}

/* FINAL WHERE */
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/* ======================
TOTAL COUNT (FOR PAGINATION)
====================== */

$totalStmt = $pdo->prepare("
SELECT COUNT(*) FROM (
    SELECT om.account_id, om.unit_name
    FROM operational_meters om
    LEFT JOIN billing_accounts a ON a.id = om.account_id
    $whereSQL
    GROUP BY om.account_id, om.unit_name
) t
");

$totalStmt->execute($params);

$totalRows = $totalStmt->fetchColumn();
$totalPages = ceil($totalRows / $limit);

/* LOAD UNITS (REAL SOURCE) */

$stmt = $pdo->prepare("
SELECT 
    om.account_id,
    a.account_name,
    om.unit_name,
    COUNT(*) AS total_meters
FROM operational_meters om
LEFT JOIN billing_accounts a ON a.id = om.account_id
$whereSQL
GROUP BY om.account_id, om.unit_name
ORDER BY om.account_id, om.unit_name
LIMIT $limit OFFSET $offset
");

$stmt->execute($params);
$units = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="container">

<div class="page-header">
<h2>Unit Management</h2>

<p class="page-subtitle">View and manage units by account, including billing structure and linked charges.</p>

</div>

<div class="stat-card">

<div style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap;">

    <!-- SEARCH -->
    <form method="GET" style="display:flex; gap:10px; flex-wrap:wrap;">

<input type="text" name="search"
       value="<?= htmlspecialchars($search) ?>"
       placeholder="Search account, unit..."
       style="flex:1;min-width:220px;padding:10px;border:1px solid #d1d5db;border-radius:10px;">
   
    <!-- ACCOUNT FILTER -->
 <select name="account"
        style="min-width:200px;padding:10px;border:1px solid #d1d5db;border-radius:10px;">
<option value="">All Accounts</option>

<?php foreach($accountsList as $acc): ?>
<option value="<?= $acc['account_name'] ?>"
<?= $account == $acc['account_name'] ? 'selected' : '' ?>>
<?= htmlspecialchars($acc['account_name']) ?>
</option>
<?php endforeach; ?>

</select>

<button type="submit" class="btn btn-primary">Apply</button>

</form>

</div>

<table width="100%">
<tr>

<th>Account ID</th>
<th>Account Name</th> <!-- 👈 ADD -->
<th>Unit</th>
<th>Meters</th>
<th>Action</th>

</tr>

<?php foreach($units as $u): ?>

<tr class="unit-row" data-account="<?= strtolower($u['account_name'] ?? '') ?>">

<td data-search="<?= htmlspecialchars(strtolower((string)$u['account_id'])) ?>">
    <?= $u['account_id'] ?>
</td>

<td data-search="<?= htmlspecialchars(strtolower($u['account_name'] ?? 'n/a')) ?>">
    <?= htmlspecialchars($u['account_name'] ?? 'N/A') ?>
</td>

<td data-search="<?= htmlspecialchars(strtolower($u['unit_name'])) ?>">
    <?= htmlspecialchars($u['unit_name']) ?>
</td>

<td><?= $u['total_meters'] ?></td>

<td>
<a href="manage.php?account_id=<?= $u['account_id'] ?>&unit_name=<?= urlencode($u['unit_name']) ?>" 
class="btn btn-primary">
Manage Charges
</a>
</td>

</tr>
<?php endforeach; ?>

</table>

<div style="margin-top:20px; display:flex; gap:5px; flex-wrap:wrap;">

<?php if($page > 1): ?>
<a href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>" class="btn">Prev</a>

<?php endif; ?>

<?php for($i=1; $i <= $totalPages; $i++): ?>
<a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>" 
   class="btn <?= $i == $page ? 'btn-primary' : '' ?>">
   <?= $i ?>
</a>
<?php endfor; ?>

<?php if($page < $totalPages): ?>

<a href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&account=<?= urlencode($account) ?>" class="btn">Next</a>

<?php endif; ?>

</div>

</div>

</div>


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