<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['super_admin']);

$db = getDBConnection();

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    if (validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $db->prepare("DELETE FROM consumers WHERE id=?")->execute([(int)$_POST['delete_id']]);
    }
    header('Location: consumers.php'); exit;
}

// Handle toggle active
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_id'])) {
    if (validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $tid = (int)$_POST['toggle_id'];
        $cur = (int)dbVal($db, "SELECT is_active FROM consumers WHERE id=?", [$tid]);
        $db->prepare("UPDATE consumers SET is_active=? WHERE id=?")->execute([$cur?0:1, $tid]);
    }
    header('Location: consumers.php'); exit;
}

// ── Filters ───────────────────────────────────────────────────
$search   = trim($_GET['q']        ?? '');
$filterDiv= trim($_GET['division'] ?? '');
$filterSt = trim($_GET['status']   ?? '');
$perPage  = in_array((int)($_GET['per'] ?? 25), [25,50,100,200]) ? (int)($_GET['per'] ?? 25) : 25;
$page     = max(1, (int)($_GET['page'] ?? 1));
$offset   = ($page - 1) * $perPage;

$where  = "WHERE 1=1";
$params = [];
if ($search)    { $where .= " AND (consumer_name LIKE ? OR meter_number LIKE ? OR connection_number LIKE ? OR phone LIKE ?)"; $params = array_merge($params, ["%{$search}%","%{$search}%","%{$search}%","%{$search}%"]); }
if ($filterDiv) { $where .= " AND division = ?";   $params[] = $filterDiv; }
if ($filterSt !== '') { $where .= " AND is_active = ?"; $params[] = (int)$filterSt; }

$total      = (int)dbVal($db, "SELECT COUNT(*) FROM consumers {$where}", $params);
$totalPages = $total > 0 ? max(1, (int)ceil($total / $perPage)) : 1;
$page       = min($page, $totalPages);
$offset     = ($page - 1) * $perPage;
$consumers  = dbRows($db, "SELECT * FROM consumers {$where} ORDER BY consumer_name LIMIT {$perPage} OFFSET {$offset}", $params);

// Division list for filter dropdown
$divisions = dbRows($db, "SELECT DISTINCT division FROM consumers WHERE division IS NOT NULL AND division != '' ORDER BY division");

// Stats
$totalActive   = (int)safeDbVal($db, "SELECT COUNT(*) FROM consumers WHERE is_active=1");
$totalInactive = (int)safeDbVal($db, "SELECT COUNT(*) FROM consumers WHERE is_active=0");
$totalAll      = $totalActive + $totalInactive;

$pageTitle = 'Manage Consumers';
include __DIR__ . '/../../includes/header.php';

// Build base URL for pagination (preserve all filters)
$baseQ = http_build_query(array_filter(['q'=>$search,'division'=>$filterDiv,'status'=>$filterSt,'per'=>$perPage]));
$baseUrl = 'consumers.php?' . ($baseQ ? $baseQ . '&' : '');
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-person-badge-fill me-2"></i>Consumers</h1>
        <p class="text-muted mb-0" style="font-size:.82rem;">Total: <strong><?= number_format($totalAll) ?></strong> consumers</p>
    </div>
    <a href="<?= BASE_URL ?>/modules/admin/consumer_form.php" class="btn btn-erp">
        <i class="bi bi-plus-circle-fill me-2"></i>Add Consumer
    </a>
</div>

<!-- ── Stats ─────────────────────────────────────────────────── -->
<div class="row g-3 mb-3">
    <div class="col-4">
        <div class="stat-card">
            <div class="stat-card-icon blue"><i class="bi bi-people-fill"></i></div>
            <div><h3>Total</h3><p><?= number_format($totalAll) ?></p></div>
        </div>
    </div>
    <div class="col-4">
        <div class="stat-card">
            <div class="stat-card-icon green"><i class="bi bi-person-check-fill"></i></div>
            <div><h3>Active</h3><p><?= number_format($totalActive) ?></p></div>
        </div>
    </div>
    <div class="col-4">
        <div class="stat-card">
            <div class="stat-card-icon orange"><i class="bi bi-person-dash-fill"></i></div>
            <div><h3>Inactive</h3><p><?= number_format($totalInactive) ?></p></div>
        </div>
    </div>
</div>

<!-- ── Filters ───────────────────────────────────────────────── -->
<div class="erp-card mb-3">
    <form method="GET" class="row g-2 align-items-end">
        <div class="col-12 col-md-4">
            <label class="form-label" style="font-size:.82rem;">Search</label>
            <input type="text" name="q" class="form-control" placeholder="Name, meter, connection, phone..."
                   value="<?= h($search) ?>">
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">Division</label>
            <select name="division" class="form-select">
                <option value="">All Divisions</option>
                <?php foreach ($divisions as $d): ?>
                <option value="<?= h($d['division']) ?>" <?= $filterDiv===$d['division']?'selected':'' ?>><?= h($d['division']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">Status</label>
            <select name="status" class="form-select">
                <option value="">All Status</option>
                <option value="1" <?= $filterSt==='1'?'selected':'' ?>>Active</option>
                <option value="0" <?= $filterSt==='0'?'selected':'' ?>>Inactive</option>
            </select>
        </div>
        <div class="col-6 col-md-2">
            <label class="form-label" style="font-size:.82rem;">Per Page</label>
            <select name="per" class="form-select">
                <?php foreach ([25,50,100,200] as $n): ?>
                <option value="<?= $n ?>" <?= $perPage==$n?'selected':'' ?>><?= $n ?> rows</option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-6 col-md-2 d-flex gap-2">
            <button type="submit" class="btn btn-erp flex-fill"><i class="bi bi-funnel me-1"></i>Filter</button>
            <a href="consumers.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        </div>
    </form>
</div>

<!-- ── Table ─────────────────────────────────────────────────── -->
<div class="erp-card">

    <!-- Top bar: count + page jump -->
    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
        <span class="text-muted" style="font-size:.82rem;">
            Showing <strong><?= $total > 0 ? $offset+1 : 0 ?>–<?= min($offset+$perPage,$total) ?></strong>
            of <strong><?= number_format($total) ?></strong> consumers
            <?= ($search||$filterDiv||$filterSt!=='') ? '<span class="badge bg-info ms-1">Filtered</span>' : '' ?>
        </span>
        <?php if ($totalPages > 1): ?>
        <form method="GET" class="d-flex align-items-center gap-2">
            <?php if ($search)    echo '<input type="hidden" name="q" value="'.h($search).'">'; ?>
            <?php if ($filterDiv) echo '<input type="hidden" name="division" value="'.h($filterDiv).'">'; ?>
            <?php if ($filterSt!=='') echo '<input type="hidden" name="status" value="'.h($filterSt).'">'; ?>
            <input type="hidden" name="per" value="<?= $perPage ?>">
            <label class="text-muted mb-0" style="font-size:.82rem;white-space:nowrap;">Go to page:</label>
            <input type="number" name="page" class="form-control form-control-sm" style="width:70px;"
                   min="1" max="<?= $totalPages ?>" value="<?= $page ?>">
            <button type="submit" class="btn btn-sm btn-outline-secondary">Go</button>
        </form>
        <?php endif; ?>
    </div>

    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.84rem;">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th>Consumer Name</th>
                    <th>Meter No</th>
                    <th>Connection No</th>
                    <th>Division</th>
                    <th>Phone</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($consumers)): ?>
                <tr><td colspan="8" class="text-center text-muted py-5">
                    <i class="bi bi-search" style="font-size:2rem;opacity:.3;display:block;margin-bottom:8px;"></i>
                    No consumers found.
                    <?php if ($search||$filterDiv||$filterSt!==''): ?>
                    <br><a href="consumers.php" class="btn btn-sm btn-outline-secondary mt-2">Clear Filters</a>
                    <?php endif; ?>
                </td></tr>
                <?php endif; ?>
                <?php foreach ($consumers as $i => $c): ?>
                <tr>
                    <td class="text-muted" style="font-size:.76rem;"><?= $offset+$i+1 ?></td>
                    <td>
                        <div class="fw-semibold"><?= h($c['consumer_name']) ?></div>
                        <?php if (!empty($c['address'])): ?>
                        <small class="text-muted" style="font-size:.74rem;"><?= h(mb_strimwidth($c['address'], 0, 40, '…')) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><code style="font-size:.78rem;"><?= h($c['meter_number']) ?></code></td>
                    <td><code style="font-size:.78rem;"><?= h($c['connection_number']) ?></code></td>
                    <td class="text-muted" style="font-size:.8rem;"><?= h($c['division'] ?? '—') ?></td>
                    <td class="text-muted" style="font-size:.8rem;"><?= h($c['phone'] ?? '—') ?></td>
                    <td>
                        <span class="badge bg-<?= $c['is_active']?'success':'secondary' ?>">
                            <?= $c['is_active']?'Active':'Inactive' ?>
                        </span>
                    </td>
                    <td>
                        <div class="d-flex gap-1">
                            <a href="<?= BASE_URL ?>/modules/admin/consumer_form.php?id=<?= $c['id'] ?>"
                               class="btn btn-sm btn-outline-primary" title="Edit">
                                <i class="bi bi-pencil-fill"></i>
                            </a>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                                <input type="hidden" name="toggle_id" value="<?= $c['id'] ?>">
                                <button type="submit" title="<?= $c['is_active']?'Deactivate':'Activate' ?>"
                                        class="btn btn-sm <?= $c['is_active']?'btn-outline-warning':'btn-outline-success' ?>">
                                    <i class="bi <?= $c['is_active']?'bi-toggle-on':'bi-toggle-off' ?>"></i>
                                </button>
                            </form>
                            <form method="POST" class="d-inline"
                                  onsubmit="return confirm('Delete <?= h(addslashes($c['consumer_name'])) ?>?')">
                                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                                <input type="hidden" name="delete_id" value="<?= $c['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                    <i class="bi bi-trash-fill"></i>
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- ── Pagination ─────────────────────────────────────────── -->
    <?php if ($totalPages > 1): ?>
    <div class="d-flex align-items-center justify-content-between mt-3 flex-wrap gap-2">
        <span class="text-muted" style="font-size:.8rem;">
            Page <strong><?= $page ?></strong> of <strong><?= $totalPages ?></strong>
        </span>
        <nav>
            <ul class="pagination pagination-sm mb-0">
                <!-- First -->
                <li class="page-item <?= $page<=1?'disabled':'' ?>">
                    <a class="page-link" href="<?= $baseUrl ?>page=1" title="First"><i class="bi bi-chevron-double-left"></i></a>
                </li>
                <!-- Prev -->
                <li class="page-item <?= $page<=1?'disabled':'' ?>">
                    <a class="page-link" href="<?= $baseUrl ?>page=<?= $page-1 ?>"><i class="bi bi-chevron-left"></i></a>
                </li>

                <?php
                $start = max(1, $page - 2);
                $end   = min($totalPages, $page + 2);
                if ($start > 1): ?>
                <li class="page-item"><a class="page-link" href="<?= $baseUrl ?>page=1">1</a></li>
                <?php if ($start > 2): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
                <?php endif; ?>

                <?php for ($p = $start; $p <= $end; $p++): ?>
                <li class="page-item <?= $p==$page?'active':'' ?>">
                    <a class="page-link" href="<?= $baseUrl ?>page=<?= $p ?>"><?= $p ?></a>
                </li>
                <?php endfor; ?>

                <?php if ($end < $totalPages): ?>
                <?php if ($end < $totalPages - 1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?>
                <li class="page-item"><a class="page-link" href="<?= $baseUrl ?>page=<?= $totalPages ?>"><?= $totalPages ?></a></li>
                <?php endif; ?>

                <!-- Next -->
                <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                    <a class="page-link" href="<?= $baseUrl ?>page=<?= $page+1 ?>"><i class="bi bi-chevron-right"></i></a>
                </li>
                <!-- Last -->
                <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                    <a class="page-link" href="<?= $baseUrl ?>page=<?= $totalPages ?>" title="Last"><i class="bi bi-chevron-double-right"></i></a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>

</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
