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

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

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

/* ======================
PAGINATION
====================== */
$limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if($page < 1) $page = 1;

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

/* ======================
FILTERS
====================== */
$search = $_GET['search'] ?? '';
$municipality = $_GET['municipality'] ?? '';

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

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

/* MUNICIPALITY FILTER */
if($municipality !== ''){
    $where[] = "municipality_name = ?";
    $params[] = $municipality;
}

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

/* ======================
TOTAL COUNT
====================== */
$totalStmt = $pdo->prepare("
SELECT COUNT(*) 
FROM billing_accounts
$whereSQL
");
$totalStmt->execute($params);
$totalRows = $totalStmt->fetchColumn();
$totalPages = ceil($totalRows / $limit);

/* ======================
LOAD ACCOUNTS
====================== */
$stmt = $pdo->prepare("
SELECT id, account_name, municipality_name
FROM billing_accounts
$whereSQL
ORDER BY account_name
LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ======================
LOAD MUNICIPALITIES (FILTER DROPDOWN)
====================== */
$municipalities = $pdo->query("
SELECT DISTINCT municipality_name 
FROM billing_accounts 
ORDER BY municipality_name
")->fetchAll(PDO::FETCH_COLUMN);

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

<div class="container">

<div class="page-header">
<h2>Account Management</h2>
<p class="page-subtitle">
Manage account-level billing charges (applied once per account).
</p>
</div>

<div class="stat-card">

<!-- 🔍 FILTER BAR -->
<form method="GET" style="margin-bottom:15px; display:flex; gap:10px; flex-wrap:wrap;">

<input type="text" name="search"
       value="<?= htmlspecialchars($search) ?>"
       placeholder="Search account or municipality..."
       style="flex:1;min-width:220px;padding:10px;border:1px solid #d1d5db;border-radius:10px;">

<select name="municipality"
        style="min-width:200px;padding:10px;border:1px solid #d1d5db;border-radius:10px;">

<option value="">All Municipalities</option>

<?php foreach($municipalities as $m): ?>
<option value="<?= $m ?>" <?= $municipality == $m ? 'selected' : '' ?>>
<?= htmlspecialchars($m) ?>
</option>
<?php endforeach; ?>

</select>

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

</form>

<!-- TABLE -->
<table width="100%">
<tr>
<th>Account</th>
<th>Municipality</th>
<th>Actions</th>
</tr>

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

<?php foreach($accounts as $a): ?>
<tr>

<td><?= htmlspecialchars($a['account_name']) ?></td>
<td><?= htmlspecialchars($a['municipality_name']) ?></td>

<td>
<a href="manage_charges.php?account_id=<?= $a['id'] ?>" class="btn btn-primary">
Manage Charges
</a>
</td>

</tr>
<?php endforeach; ?>

</table>

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

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

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

<?php if($page < $totalPages): ?>
<a href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&municipality=<?= urlencode($municipality) ?>" class="btn">Next</a>
<?php endif; ?>

</div>

</div>

</div>

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