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

// ── Division filter for non-super_admin ──────────────────────
$role   = getSession('role');
$rawDiv = getSession('division') ?? '';
$divWhere  = '';
$divParams = [];
if ($role !== 'super_admin' && $rawDiv && $rawDiv !== 'All') {
    $decoded  = json_decode($rawDiv, true);
    $assigned = is_array($decoded) ? array_filter($decoded) : [trim($rawDiv)];
    if (!empty($assigned)) {
        $ph        = implode(',', array_fill(0, count($assigned), '?'));
        $divWhere  = " AND division IN ({$ph})";
        $divParams = array_values($assigned);
    }
}

// ── 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; }
$where  .= $divWhere;
$params  = array_merge($params, $divParams);

$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);

$divisions = dbRows($db, "SELECT DISTINCT division FROM consumers WHERE division IS NOT NULL AND division != '' {$divWhere} ORDER BY division", $divParams);

$totalActive   = (int)safeDbVal($db, "SELECT COUNT(*) FROM consumers WHERE is_active=1{$divWhere}", $divParams);
$totalInactive = (int)safeDbVal($db, "SELECT COUNT(*) FROM consumers WHERE is_active=0{$divWhere}", $divParams);
$totalAll      = $totalActive + $totalInactive;

$pageTitle = 'Manage Consumers';
include __DIR__ . '/../../includes/header.php';

$baseQ   = http_build_query(array_filter(['q'=>$search,'division'=>$filterDiv,'status'=>$filterSt,'per'=>$perPage]));
$baseUrl = 'consumers.php?' . ($baseQ ? $baseQ . '&' : '');
?>

<!-- ── Stats ─────────────────────────────────────────────────── -->
<div class="row g-2 mb-3">
    <div class="col-4">
        <div class="erp-card text-center py-2 px-1" style="border-top:3px solid #6366f1;">
            <div style="font-size:clamp(1.1rem,4vw,1.6rem);font-weight:800;color:#6366f1;line-height:1.1;"><?= number_format($totalAll) ?></div>
            <div style="font-size:.68rem;color:#9ca3af;margin-top:3px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;">Total</div>
        </div>
    </div>
    <div class="col-4">
        <div class="erp-card text-center py-2 px-1" style="border-top:3px solid #22c55e;">
            <div style="font-size:clamp(1.1rem,4vw,1.6rem);font-weight:800;color:#22c55e;line-height:1.1;"><?= number_format($totalActive) ?></div>
            <div style="font-size:.68rem;color:#9ca3af;margin-top:3px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;">Active</div>
        </div>
    </div>
    <div class="col-4">
        <div class="erp-card text-center py-2 px-1" style="border-top:3px solid #f59e0b;">
            <div style="font-size:clamp(1.1rem,4vw,1.6rem);font-weight:800;color:#f59e0b;line-height:1.1;"><?= number_format($totalInactive) ?></div>
            <div style="font-size:.68rem;color:#9ca3af;margin-top:3px;font-weight:600;text-transform:uppercase;letter-spacing:.4px;">Inactive</div>
        </div>
    </div>
</div>

<!-- ── Filters ───────────────────────────────────────────────── -->
<div class="erp-card mb-3">
    <form method="GET">
        <div class="mb-2">
            <input type="text" name="q" class="form-control" placeholder="Search name, meter, connection, phone…"
                   value="<?= h($search) ?>">
        </div>
        <div class="row g-2">
            <div class="col-6">
                <select name="division" class="form-select" style="font-size:.82rem;">
                    <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">
                <select name="status" class="form-select" style="font-size:.82rem;">
                    <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">
                <select name="per" class="form-select" style="font-size:.82rem;">
                    <?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 d-flex gap-2">
                <button type="submit" class="btn btn-erp flex-fill" style="font-size:.85rem;"><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>
        </div>
    </form>
</div>

<!-- ── Count + Add button ─────────────────────────────────────── -->
<div class="d-flex align-items-center justify-content-between mb-2">
    <span class="text-muted" style="font-size:.82rem;">
        <strong><?= $total > 0 ? $offset+1 : 0 ?>–<?= min($offset+$perPage,$total) ?></strong>
        of <strong><?= number_format($total) ?></strong>
        <?= ($search||$filterDiv||$filterSt!=='') ? '<span class="badge bg-info ms-1">Filtered</span>' : '' ?>
    </span>
    <a href="<?= BASE_URL ?>/modules/admin/consumer_form.php" class="btn btn-erp btn-sm">
        <i class="bi bi-plus-circle-fill me-1"></i>Add
    </a>
</div>

<!-- ── Mobile Cards (< 768px) ────────────────────────────────── -->
<div class="d-md-none">
    <?php if (empty($consumers)): ?>
    <div class="erp-card text-center py-5 text-muted">
        <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; ?>
    </div>
    <?php endif; ?>

    <?php foreach ($consumers as $i => $c): ?>
    <div class="erp-card mb-2" style="padding:12px;">
        <!-- Name + status -->
        <div class="d-flex align-items-start justify-content-between gap-2 mb-2">
            <div style="flex:1;min-width:0;">
                <div class="fw-bold" style="font-size:.92rem;line-height:1.3;"><?= h($c['consumer_name']) ?></div>
                <?php if (!empty($c['address'])): ?>
                <div class="text-muted" style="font-size:.74rem;"><?= h(mb_strimwidth($c['address'], 0, 50, '…')) ?></div>
                <?php endif; ?>
            </div>
            <span class="badge bg-<?= $c['is_active']?'success':'secondary' ?> flex-shrink-0">
                <?= $c['is_active']?'Active':'Inactive' ?>
            </span>
        </div>
        <!-- Details -->
        <div class="mb-2" style="font-size:.8rem;color:var(--erp-text-muted);display:grid;grid-template-columns:1fr 1fr;gap:2px 8px;">
            <div><i class="bi bi-upc me-1"></i><code style="font-size:.78rem;"><?= h($c['meter_number']) ?></code></div>
            <div><i class="bi bi-hash me-1"></i><code style="font-size:.78rem;"><?= h($c['connection_number']) ?></code></div>
            <?php if (!empty($c['division'])): ?>
            <div><i class="bi bi-diagram-3 me-1"></i><?= h($c['division']) ?></div>
            <?php endif; ?>
            <?php if (!empty($c['phone'])): ?>
            <div><i class="bi bi-telephone me-1"></i><?= h($c['phone']) ?></div>
            <?php endif; ?>
        </div>
        <!-- Actions -->
        <div class="d-flex gap-2">
            <a href="<?= BASE_URL ?>/modules/admin/consumer_form.php?id=<?= $c['id'] ?>"
               class="btn btn-sm btn-outline-primary flex-fill">
                <i class="bi bi-pencil-fill me-1"></i>Edit
            </a>
            <form method="POST" class="flex-fill">
                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                <input type="hidden" name="toggle_id" value="<?= $c['id'] ?>">
                <button type="submit" class="btn btn-sm w-100 <?= $c['is_active']?'btn-outline-warning':'btn-outline-success' ?>">
                    <i class="bi <?= $c['is_active']?'bi-toggle-on':'bi-toggle-off' ?> me-1"></i><?= $c['is_active']?'Disable':'Enable' ?>
                </button>
            </form>
            <form method="POST" 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">
                    <i class="bi bi-trash-fill"></i>
                </button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ── Desktop Table (>= 768px) ──────────────────────────────── -->
<div class="erp-card d-none d-md-block">
    <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>
</div>

<!-- ── Pagination ─────────────────────────────────────────────── -->
<?php if ($totalPages > 1): ?>
<div class="d-flex align-items-center justify-content-between mt-3 gap-2">
    <span class="text-muted" style="font-size:.78rem;">Page <strong><?= $page ?></strong> / <strong><?= $totalPages ?></strong></span>
    <nav>
        <ul class="pagination pagination-sm mb-0">
            <!-- 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>
            <!-- Page numbers: desktop only -->
            <?php
            $start = max(1, $page-2); $end = min($totalPages, $page+2);
            if ($start > 1): ?>
            <li class="page-item d-none d-md-block"><a class="page-link" href="<?= $baseUrl ?>page=1">1</a></li>
            <?php if($start>2): ?><li class="page-item disabled d-none d-md-block"><span class="page-link">…</span></li><?php endif;
            endif;
            for ($p=$start; $p<=$end; $p++): ?>
            <li class="page-item <?= $p==$page?'active':'' ?> d-none d-md-block">
                <a class="page-link" href="<?= $baseUrl ?>page=<?= $p ?>"><?= $p ?></a>
            </li>
            <?php endfor;
            if ($end < $totalPages):
                if($end<$totalPages-1): ?><li class="page-item disabled d-none d-md-block"><span class="page-link">…</span></li><?php endif; ?>
                <li class="page-item d-none d-md-block"><a class="page-link" href="<?= $baseUrl ?>page=<?= $totalPages ?>"><?= $totalPages ?></a></li>
            <?php endif; ?>
            <!-- Mobile: current page indicator -->
            <li class="page-item active d-md-none">
                <span class="page-link" style="min-width:60px;text-align:center;"><?= $page ?> / <?= $totalPages ?></span>
            </li>
            <!-- 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>
        </ul>
    </nav>
</div>
<?php endif; ?>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
