<?php
require_once __DIR__ . '/../../includes/init.php';
middleware();

$db   = getDBConnection();
$role = getSession('role');
$uid  = (int)getSession('user_id');
$isMR = ($role === 'mr');

// ── Division Hierarchy ────────────────────────────────────────
// Parent Division => Sub-Divisions (as stored in consumers.division)
$divisionMap = array(
    'Roorkee Urban' => array(
        'ROORKEE_SD-I',
        'ROORKEE_SD-II',
        'EDSD DHANORI',
    ),
    'Ramnagar' => array(
        'EDSD-I RAMNAGAR ROORKEE',
        'EDSD-II RAMNAGAR ROORKEE',
        'EDSD HIMALAYAN',
    ),
    'Roorkee Rural' => array(
        'MANGLORE',
        'EDSD JHEBREDA',
        'LANDHAURA',
    ),
);

// Reverse map: subDiv => parent
$subToParent = array();
foreach ($divisionMap as $parent => $subs) {
    foreach ($subs as $sub) { $subToParent[$sub] = $parent; }
}

// ── Month selector ────────────────────────────────────────────
$monthParam = trim($_GET['month'] ?? date('Y-m'));
if (!preg_match('/^\d{4}-\d{2}$/', $monthParam)) $monthParam = date('Y-m');
$parts     = explode('-', $monthParam);
$selYear   = (int)$parts[0];
$selMonth  = (int)$parts[1];
$monthLabel = date('F Y', mktime(0, 0, 0, $selMonth, 1, $selYear));

$monthOptions = array();
for ($i = 0; $i < 12; $i++) {
    $ts = mktime(0, 0, 0, (int)date('n') - $i, 1, (int)date('Y'));
    $monthOptions[] = array('value' => date('Y-m', $ts), 'label' => date('F Y', $ts));
}

// ── Navigation levels ─────────────────────────────────────────
// Level 1 (default admin) : parent division summary
// Level 2 (?parent=X)     : sub-division breakdown inside parent
// Level 3 (?div=X)        : consumer list for a sub-division
$parentView   = trim($_GET['parent'] ?? '');
$divView      = trim($_GET['div']    ?? '');
$statusFilter = in_array($_GET['status'] ?? '', array('pending','done')) ? $_GET['status'] : 'all';

// ── URL builder ───────────────────────────────────────────────
function tUrl($params) {
    $base = array(
        'month'  => $_GET['month']  ?? date('Y-m'),
        'parent' => $_GET['parent'] ?? '',
        'div'    => $_GET['div']    ?? '',
        'status' => $_GET['status'] ?? 'all',
    );
    $q = array_filter(array_merge($base, $params), function($v){ return $v !== ''; });
    return BASE_URL . '/modules/tracking/index.php?' . http_build_query($q);
}

// ── Reading status helper (returns consumers with read_count) ─
function fetchConsumers($db, $selYear, $selMonth, $whereClause, $whereParams) {
    // year/month go FIRST (used in the LEFT JOIN subquery), whereParams go AFTER
    $params = array_merge(array($selYear, $selMonth), $whereParams);
    return dbRows($db,
        "SELECT c.id, c.consumer_name, c.meter_number, c.connection_number,
                c.type, c.division,
                COALESCE(m.cnt, 0) AS read_count,
                (SELECT MAX(r2.reading_date) FROM readings r2
                 WHERE r2.consumer_id = c.id) AS last_read_date
         FROM consumers c
         LEFT JOIN (
             SELECT consumer_id, COUNT(*) AS cnt
             FROM readings
             WHERE YEAR(reading_date) = ? AND MONTH(reading_date) = ?
             GROUP BY consumer_id
         ) m ON m.consumer_id = c.id
         WHERE c.is_active = 1 $whereClause
         ORDER BY read_count ASC, c.consumer_name",
        $params
    );
}

// ── Sub-division stats (filtered list) ───────────────────────
function subDivStats($db, $selYear, $selMonth, $subDivs) {
    if (empty($subDivs)) return array();
    $phs    = implode(',', array_fill(0, count($subDivs), '?'));
    // year/month FIRST (subquery), then division names for IN clause
    $params = array_merge(array($selYear, $selMonth), $subDivs);
    return dbRows($db,
        "SELECT c.division AS sub_div,
                COUNT(DISTINCT c.id) AS total,
                COUNT(DISTINCT CASE WHEN COALESCE(m.cnt,0) > 0 THEN c.id END) AS done,
                COUNT(DISTINCT CASE WHEN COALESCE(m.cnt,0) = 0 THEN c.id END) AS pending
         FROM consumers c
         LEFT JOIN (
             SELECT consumer_id, COUNT(*) AS cnt
             FROM readings
             WHERE YEAR(reading_date) = ? AND MONTH(reading_date) = ?
             GROUP BY consumer_id
         ) m ON m.consumer_id = c.id
         WHERE c.is_active = 1 AND c.division IN ($phs)
         GROUP BY c.division",
        $params
    );
}

// ── ALL division stats — no filter, every active consumer ─────
function allDivStats($db, $selYear, $selMonth) {
    return dbRows($db,
        "SELECT COALESCE(c.division,'') AS sub_div,
                COUNT(DISTINCT c.id) AS total,
                COUNT(DISTINCT CASE WHEN COALESCE(m.cnt,0) > 0 THEN c.id END) AS done,
                COUNT(DISTINCT CASE WHEN COALESCE(m.cnt,0) = 0 THEN c.id END) AS pending
         FROM consumers c
         LEFT JOIN (
             SELECT consumer_id, COUNT(*) AS cnt
             FROM readings
             WHERE YEAR(reading_date) = ? AND MONTH(reading_date) = ?
             GROUP BY consumer_id
         ) m ON m.consumer_id = c.id
         WHERE c.is_active = 1
         GROUP BY c.division",
        array($selYear, $selMonth)
    );
}

// ── MR: get assigned sub-divisions — always fresh from DB ─────
$mrSubDivs   = array();
$mrDivFilter = '';
$mrDivParams = array();
if ($isMR) {
    // Fetch from DB directly so admin changes apply immediately (no re-login needed)
    $freshUser = dbRow($db, "SELECT division FROM users WHERE id=?", array($uid));
    $rawDiv    = $freshUser['division'] ?? '';

    // Also sync session so other pages stay consistent
    if ($rawDiv !== (getSession('division') ?? '')) {
        setSession('division', $rawDiv);
    }

    if ($rawDiv && $rawDiv !== 'All') {
        $decoded   = json_decode($rawDiv, true);
        $mrSubDivs = is_array($decoded) ? array_values(array_filter($decoded)) : array(trim($rawDiv));
    }
    if (!empty($mrSubDivs)) {
        $phs = implode(',', array_fill(0, count($mrSubDivs), '?'));
        $mrDivFilter = "AND c.division IN ($phs)";
        $mrDivParams = $mrSubDivs;
    }
}

// ─────────────────────────────────────────────────────────────
// Determine what to display
// ─────────────────────────────────────────────────────────────

if ($isMR) {
    // ── MR: consumer list for their sub-divisions ─────────────
    $mrFallback = false;
    $consumers  = fetchConsumers($db, $selYear, $selMonth, $mrDivFilter, $mrDivParams);

    // If MR has a division set but 0 consumers match → show all with a note
    if (count($consumers) === 0 && $mrDivFilter !== '') {
        $consumers  = fetchConsumers($db, $selYear, $selMonth, '', array());
        $mrFallback = true;
    }

    $total    = count($consumers);
    $done     = count(array_filter($consumers, function($c){ return $c['read_count'] > 0; }));
    $pending  = $total - $done;
    $pct      = $total > 0 ? round($done / $total * 100) : 0;
    $viewMode = 'consumer_list';

    $displayed = array_filter($consumers, function($c) use ($statusFilter) {
        if ($statusFilter === 'pending') return $c['read_count'] == 0;
        if ($statusFilter === 'done')    return $c['read_count'] >  0;
        return true;
    });

    // ── MR Analytics ──────────────────────────────────────────
    $mrToday      = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND reading_date=?", array($uid, date('Y-m-d')));
    $mrTodayBills = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills WHERE user_id=? AND DATE(created_at)=?", array($uid, date('Y-m-d')));
    $mrMonthReads = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE user_id=? AND YEAR(reading_date)=? AND MONTH(reading_date)=?", array($uid, $selYear, $selMonth));
    $mrMonthBills = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills WHERE user_id=? AND YEAR(created_at)=? AND MONTH(created_at)=?", array($uid, $selYear, $selMonth));

    // Last 7 days bar data
    $l7Rows = dbRows($db, "SELECT DATE(reading_date) AS d, COUNT(*) AS cnt FROM readings WHERE user_id=? AND reading_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) GROUP BY DATE(reading_date)", array($uid));
    $l7Map  = array();
    for ($i = 6; $i >= 0; $i--) { $d = date('Y-m-d', strtotime("-{$i} days")); $l7Map[$d] = 0; }
    foreach ($l7Rows as $r) { if (isset($l7Map[$r['d']])) $l7Map[$r['d']] = (int)$r['cnt']; }
    $l7Max = max(array_values($l7Map)) ?: 1;

} elseif ($divView !== '') {
    // ── Level 3: consumer list for a specific sub-division ────
    $consumers = fetchConsumers($db, $selYear, $selMonth, "AND c.division = ?", array($divView));
    $total     = count($consumers);
    $done      = count(array_filter($consumers, function($c){ return $c['read_count'] > 0; }));
    $pending   = $total - $done;
    $pct       = $total > 0 ? round($done / $total * 100) : 0;
    $viewMode  = 'consumer_list';

    $displayed = array_filter($consumers, function($c) use ($statusFilter) {
        if ($statusFilter === 'pending') return $c['read_count'] == 0;
        if ($statusFilter === 'done')    return $c['read_count'] >  0;
        return true;
    });

} elseif ($parentView !== '' && isset($divisionMap[$parentView])) {
    // ── Level 2: sub-division breakdown for a parent ──────────
    $subDivs     = $divisionMap[$parentView];
    $subStats    = subDivStats($db, $selYear, $selMonth, $subDivs);
    $subStatMap  = array();
    foreach ($subStats as $s) { $subStatMap[$s['sub_div']] = $s; }

    $total = 0; $done = 0; $pending = 0;
    foreach ($subStats as $s) {
        $total   += (int)$s['total'];
        $done    += (int)$s['done'];
        $pending += (int)$s['pending'];
    }
    $pct      = $total > 0 ? round($done / $total * 100) : 0;
    $viewMode = 'sub_list';

} else {
    // ── Level 1: parent division summary ─────────────────────
    // Query EVERY active consumer — no division filter
    $allStats   = allDivStats($db, $selYear, $selMonth);
    $allStatMap = array();
    $grandTotal = 0; $grandDone = 0; $grandPending = 0;
    foreach ($allStats as $s) {
        $allStatMap[$s['sub_div']] = $s;
        $grandTotal   += (int)$s['total'];
        $grandDone    += (int)$s['done'];
        $grandPending += (int)$s['pending'];
    }

    // Build known parent groups
    $parentSummary = array();
    $mappedDivs    = array();
    foreach ($divisionMap as $parentName => $subDivs) {
        $pTotal = 0; $pDone = 0; $pPending = 0;
        foreach ($subDivs as $sub) {
            $mappedDivs[] = $sub;
            if (isset($allStatMap[$sub])) {
                $pTotal   += (int)$allStatMap[$sub]['total'];
                $pDone    += (int)$allStatMap[$sub]['done'];
                $pPending += (int)$allStatMap[$sub]['pending'];
            }
        }
        $parentSummary[] = array(
            'name' => $parentName, 'subs' => $subDivs,
            'total' => $pTotal, 'done' => $pDone, 'pending' => $pPending,
            'is_other' => false,
        );
    }

    // Collect any divisions NOT in the map → "Other"
    $otherSubs = array(); $otherTotal = 0; $otherDone = 0; $otherPending = 0;
    foreach ($allStatMap as $divName => $s) {
        if (!in_array($divName, $mappedDivs)) {
            $otherSubs[]   = $divName;
            $otherTotal   += (int)$s['total'];
            $otherDone    += (int)$s['done'];
            $otherPending += (int)$s['pending'];
        }
    }
    if ($otherTotal > 0) {
        $parentSummary[] = array(
            'name' => 'Other / Unassigned', 'subs' => $otherSubs,
            'total' => $otherTotal, 'done' => $otherDone, 'pending' => $otherPending,
            'is_other' => true,
        );
    }

    $grandPct = $grandTotal > 0 ? round($grandDone / $grandTotal * 100) : 0;
    $viewMode = 'parent_summary';

    // ── Admin Analytics ───────────────────────────────────────
    $topMRs = dbRows($db,
        "SELECT u.full_name, COUNT(r.id) AS cnt
         FROM readings r JOIN users u ON u.id = r.user_id
         WHERE YEAR(r.reading_date)=? AND MONTH(r.reading_date)=?
         GROUP BY r.user_id ORDER BY cnt DESC LIMIT 5",
        array($selYear, $selMonth));

    $dayRows = dbRows($db,
        "SELECT DAY(reading_date) AS d, COUNT(*) AS cnt FROM readings
         WHERE YEAR(reading_date)=? AND MONTH(reading_date)=?
         GROUP BY DAY(reading_date)",
        array($selYear, $selMonth));
    $daysInMonth = (int)date('t', mktime(0, 0, 0, $selMonth, 1, $selYear));
    $dayMap = array();
    for ($d = 1; $d <= $daysInMonth; $d++) { $dayMap[$d] = 0; }
    foreach ($dayRows as $r) { $dayMap[(int)$r['d']] = (int)$r['cnt']; }
    $dayMax = max(array_values($dayMap)) ?: 1;

    $todayTotal = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_date=?", array(date('Y-m-d')));
    $activeMRs  = (int)safeDbVal($db, "SELECT COUNT(DISTINCT user_id) FROM readings WHERE YEAR(reading_date)=? AND MONTH(reading_date)=?", array($selYear, $selMonth));
}

$pageTitle = 'Monthly Tracking';
include __DIR__ . '/../../includes/header.php';

// ── Color helper ──────────────────────────────────────────────
function pctColor($p) { return $p>=80?'#22c55e':($p>=50?'#f59e0b':'#ef4444'); }
?>

<style>
.track-stat { border-radius:14px; padding:16px; text-align:center; }
.track-stat h3 { font-size:.76rem; color:#6b7280; font-weight:600; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.track-stat p  { font-size:1.8rem; font-weight:800; margin:0; line-height:1.1; }
.track-bar-wrap { height:9px; border-radius:9px; background:#e5e7eb; overflow:hidden; }
.track-bar      { height:100%; border-radius:9px; transition:width .6s ease; }
.done-pill    { display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:.74rem;font-weight:600;background:#dcfce7;color:#15803d; }
.pending-pill { display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:.74rem;font-weight:600;background:#fee2e2;color:#dc2626; }
.tab-bar { display:flex;gap:4px;background:rgba(0,0,0,.06);border-radius:10px;padding:3px; }
.tab-bar a { flex:1;text-align:center;padding:6px 4px;border-radius:7px;font-size:.78rem;font-weight:600;color:#6b7280;text-decoration:none; }
.tab-bar a.active { background:#fff;color:#1a237e;box-shadow:0 1px 4px rgba(0,0,0,.12); }
.div-card { border-radius:14px;border:1px solid #e5e7eb;padding:16px;margin-bottom:12px; }
.div-card-header { display:flex;justify-content:space-between;align-items:center;margin-bottom:10px; }
.sub-row { display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid #f3f4f6;font-size:.84rem; }
.sub-row:last-child { border-bottom:none; }
</style>

<!-- ── Page Header ──────────────────────────────────────────── -->
<div class="page-header">
    <div>
        <h1><i class="bi bi-calendar2-check me-2 text-primary"></i>Monthly Tracking</h1>
        <nav aria-label="breadcrumb"><ol class="breadcrumb mb-0" style="font-size:.8rem;">
            <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li>
            <?php if ($divView !== ''): ?>
                <li class="breadcrumb-item"><a href="<?= tUrl(array('parent'=>'','div'=>'','status'=>'all')) ?>">Tracking</a></li>
                <?php if ($parentView !== ''): ?>
                <li class="breadcrumb-item"><a href="<?= tUrl(array('div'=>'','status'=>'all')) ?>"><?= h($parentView) ?></a></li>
                <?php endif; ?>
                <li class="breadcrumb-item active"><?= h($divView) ?></li>
            <?php elseif ($parentView !== ''): ?>
                <li class="breadcrumb-item"><a href="<?= tUrl(array('parent'=>'','div'=>'','status'=>'all')) ?>">Tracking</a></li>
                <li class="breadcrumb-item active"><?= h($parentView) ?></li>
            <?php else: ?>
                <li class="breadcrumb-item active">Monthly Tracking</li>
            <?php endif; ?>
        </ol></nav>
    </div>
    <!-- Month Selector -->
    <form method="GET">
        <?php if ($parentView): ?><input type="hidden" name="parent" value="<?= h($parentView) ?>"><?php endif; ?>
        <?php if ($divView):    ?><input type="hidden" name="div"    value="<?= h($divView) ?>"><?php endif; ?>
        <select name="month" class="form-select form-select-sm" style="min-width:140px;" onchange="this.form.submit()">
            <?php foreach ($monthOptions as $mo): ?>
            <option value="<?= $mo['value'] ?>" <?= $mo['value']===$monthParam?'selected':'' ?>><?= $mo['label'] ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</div>

<!-- ── Quick Consumer Search (all roles) ─────────────────────── -->
<div class="erp-card mb-3">
    <h6 class="fw-bold mb-2" style="font-size:.88rem;">
        <i class="bi bi-search me-2 text-primary"></i>Quick Consumer Search
    </h6>
    <div class="d-flex gap-2">
        <input type="text" id="trkSearch" class="form-control"
               placeholder="Enter meter number or connection number" autocomplete="off"
               inputmode="numeric">
        <button class="btn btn-erp" onclick="trkDoSearch()" id="trkBtn">
            <i class="bi bi-search"></i>
        </button>
    </div>
    <div id="trkResult" class="mt-2"></div>
</div>

<?php if ($viewMode === 'parent_summary'): ?>
<!-- ═══════════════════════════════════════════════════════════
     LEVEL 1: Parent Division Summary (Admin/Staff)
═══════════════════════════════════════════════════════════ -->

<!-- Grand Stats -->
<div class="row g-3 mb-3">
    <div class="col-6 col-md-3">
        <div class="erp-card track-stat" style="border-top:3px solid #6366f1;">
            <h3>Total Consumers</h3><p style="color:#6366f1;"><?= $grandTotal ?></p>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="erp-card track-stat" style="border-top:3px solid #22c55e;">
            <h3>Done</h3><p style="color:#22c55e;"><?= $grandDone ?></p>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="erp-card track-stat" style="border-top:3px solid #ef4444;">
            <h3>Pending</h3><p style="color:#ef4444;"><?= $grandPending ?></p>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="erp-card track-stat" style="border-top:3px solid #f59e0b;">
            <h3>Complete</h3><p style="color:<?= pctColor($grandPct) ?>;"><?= $grandPct ?>%</p>
        </div>
    </div>
</div>

<!-- Overall progress -->
<div class="erp-card mb-3 py-3">
    <div class="d-flex justify-content-between mb-2">
        <span style="font-size:.85rem;font-weight:600;">Overall — <?= $monthLabel ?></span>
        <span style="font-weight:800;color:<?= pctColor($grandPct) ?>;"><?= $grandPct ?>%</span>
    </div>
    <div class="track-bar-wrap"><div class="track-bar" style="width:<?= $grandPct ?>%;background:<?= pctColor($grandPct) ?>;"></div></div>
    <div class="d-flex justify-content-between mt-1" style="font-size:.72rem;color:#9ca3af;">
        <span><?= $grandDone ?> of <?= $grandTotal ?> done</span>
        <span><?= $grandPending ?> pending</span>
    </div>
</div>

<!-- Admin Analytics -->
<div class="row g-3 mb-3">

    <!-- Quick stats -->
    <div class="col-12">
        <div class="erp-card">
            <div class="row g-0 text-center">
                <div class="col-4" style="border-right:1px solid #f0f0f0;">
                    <div style="font-size:1.5rem;font-weight:800;color:#6366f1;"><?= $todayTotal ?></div>
                    <div style="font-size:.72rem;color:#9ca3af;">Today Readings</div>
                </div>
                <div class="col-4" style="border-right:1px solid #f0f0f0;">
                    <div style="font-size:1.5rem;font-weight:800;color:#22c55e;"><?= $grandDone ?></div>
                    <div style="font-size:.72rem;color:#9ca3af;"><?= $monthLabel ?> Done</div>
                </div>
                <div class="col-4">
                    <div style="font-size:1.5rem;font-weight:800;color:#f59e0b;"><?= $activeMRs ?></div>
                    <div style="font-size:.72rem;color:#9ca3af;">Active MRs</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Top MRs -->
    <div class="col-12 col-md-5">
        <div class="erp-card h-100">
            <div class="fw-bold mb-3" style="font-size:.85rem;">
                <i class="bi bi-trophy-fill text-warning me-2"></i>Top MRs — <?= $monthLabel ?>
            </div>
            <?php if (empty($topMRs)): ?>
            <p class="text-muted text-center" style="font-size:.82rem;">No readings this month.</p>
            <?php else: ?>
            <?php foreach ($topMRs as $i => $m):
                $colors = array('#6366f1','#22c55e','#f59e0b','#ef4444','#8b5cf6');
                $col    = $colors[$i] ?? '#9ca3af';
                $barW   = round($m['cnt'] / $topMRs[0]['cnt'] * 100);
            ?>
            <div style="margin-bottom:10px;">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span style="font-size:.8rem;font-weight:600;">
                        <span style="display:inline-flex;width:18px;height:18px;border-radius:50%;background:<?= $col ?>;color:#fff;font-size:.65rem;font-weight:700;align-items:center;justify-content:center;margin-right:6px;"><?= $i+1 ?></span>
                        <?= h($m['full_name']) ?>
                    </span>
                    <span style="font-size:.78rem;font-weight:700;color:<?= $col ?>;"><?= $m['cnt'] ?></span>
                </div>
                <div style="height:5px;background:#f0f0f0;border-radius:5px;overflow:hidden;">
                    <div style="height:100%;width:<?= $barW ?>%;background:<?= $col ?>;border-radius:5px;"></div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Day-wise trend -->
    <div class="col-12 col-md-7">
        <div class="erp-card h-100">
            <div class="fw-bold mb-3" style="font-size:.85rem;">
                <i class="bi bi-bar-chart-fill text-primary me-2"></i>Daily Readings — <?= $monthLabel ?>
            </div>
            <div style="display:flex;align-items:flex-end;gap:2px;height:70px;overflow:hidden;">
                <?php foreach ($dayMap as $d => $cnt):
                    $barH   = $cnt > 0 ? max(4, round($cnt / $dayMax * 62)) : 2;
                    $today  = (int)date('j');
                    $isToday = ($d === $today && $selMonth == date('n') && $selYear == date('Y'));
                ?>
                <div style="flex:1;min-width:0;display:flex;flex-direction:column;align-items:center;gap:1px;">
                    <div style="width:100%;max-width:14px;background:<?= $isToday ? '#6366f1' : ($cnt > 0 ? '#a5b4fc' : '#e5e7eb') ?>;
                         border-radius:2px 2px 0 0;height:<?= $barH ?>px;" title="Day <?= $d ?>: <?= $cnt ?> readings"></div>
                    <?php if ($d % 5 === 1 || $d === $daysInMonth): ?>
                    <span style="font-size:.55rem;color:#9ca3af;"><?= $d ?></span>
                    <?php else: ?><span style="font-size:.55rem;">&nbsp;</span><?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <div class="d-flex justify-content-between mt-2" style="font-size:.7rem;color:#9ca3af;">
                <span>1</span>
                <span style="color:#6366f1;font-weight:600;">Peak: <?= $dayMax ?> readings/day</span>
                <span><?= $daysInMonth ?></span>
            </div>
        </div>
    </div>

</div>

<!-- Parent Division Cards -->
<?php foreach ($parentSummary as $p):
    $ppct = $p['total'] > 0 ? round($p['done']/$p['total']*100) : 0;
    $col  = pctColor($ppct);
?>
<div class="erp-card div-card mb-3">
    <!-- Division header -->
    <div class="div-card-header">
        <div>
            <div class="fw-bold" style="font-size:1rem;"><?= h($p['name']) ?></div>
            <div style="font-size:.76rem;color:#9ca3af;"><?= count($p['subs']) ?> sub-divisions &nbsp;·&nbsp; <?= $p['total'] ?> consumers</div>
        </div>
        <div class="text-end">
            <div style="font-size:1.3rem;font-weight:800;color:<?= $col ?>;"><?= $ppct ?>%</div>
            <?php if (!$p['is_other']): ?>
            <a href="<?= tUrl(array('parent'=>$p['name'],'div'=>'','status'=>'all')) ?>"
               class="btn btn-sm btn-outline-primary mt-1" style="font-size:.74rem;">
                <i class="bi bi-grid me-1"></i>Details
            </a>
            <?php endif; ?>
        </div>
    </div>
    <!-- Progress bar -->
    <div class="track-bar-wrap mb-3">
        <div class="track-bar" style="width:<?= $ppct ?>%;background:<?= $col ?>;"></div>
    </div>
    <!-- Sub-divisions preview -->
    <?php foreach ($p['subs'] as $sub):
        $s = isset($allStatMap[$sub]) ? $allStatMap[$sub] : array('total'=>0,'done'=>0,'pending'=>0);
        $spct = (int)$s['total'] > 0 ? round((int)$s['done']/(int)$s['total']*100) : 0;
    ?>
    <div class="sub-row">
        <div>
            <div style="font-weight:600;font-size:.84rem;"><?= h($sub) ?></div>
            <div style="font-size:.73rem;color:#9ca3af;">
                <?= (int)$s['total'] ?> consumers &nbsp;
                <span class="text-success"><?= (int)$s['done'] ?> done</span> &nbsp;
                <span class="text-danger"><?= (int)$s['pending'] ?> pending</span>
            </div>
        </div>
        <div class="d-flex align-items-center gap-2">
            <div style="width:70px;">
                <div class="track-bar-wrap" style="height:6px;">
                    <div class="track-bar" style="width:<?= $spct ?>%;background:<?= pctColor($spct) ?>;height:6px;"></div>
                </div>
            </div>
            <span style="font-size:.76rem;font-weight:700;color:<?= pctColor($spct) ?>;min-width:30px;"><?= $spct ?>%</span>
            <a href="<?= tUrl(array('div'=>$sub,'parent'=>$p['name'],'status'=>'all')) ?>"
               class="btn btn-sm btn-outline-secondary" style="font-size:.72rem;padding:2px 8px;">
                <i class="bi bi-eye"></i>
            </a>
        </div>
    </div>
    <?php endforeach; ?>
    <!-- Summary footer -->
    <div class="d-flex justify-content-between mt-3 pt-2" style="border-top:1px solid #f0f0f0;font-size:.8rem;">
        <span><span class="done-pill"><i class="bi bi-check-circle-fill"></i><?= $p['done'] ?> Done</span></span>
        <span><span class="pending-pill"><i class="bi bi-clock-fill"></i><?= $p['pending'] ?> Pending</span></span>
        <?php if (!$p['is_other']): ?>
        <a href="<?= tUrl(array('parent'=>$p['name'],'div'=>'','status'=>'pending')) ?>"
           class="btn btn-sm btn-danger" style="font-size:.74rem;padding:3px 10px;">
            <i class="bi bi-list-ul me-1"></i>View Pending
        </a>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>

<?php elseif ($viewMode === 'sub_list'): ?>
<!-- ═══════════════════════════════════════════════════════════
     LEVEL 2: Sub-Division breakdown (Admin drill-down)
═══════════════════════════════════════════════════════════ -->
<a href="<?= tUrl(array('parent'=>'','div'=>'','status'=>'all')) ?>" class="btn btn-outline-secondary btn-sm mb-3">
    <i class="bi bi-arrow-left me-1"></i>All Divisions
</a>

<div class="row g-3 mb-3">
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #6366f1;">
        <h3>Total</h3><p style="color:#6366f1;"><?= $total ?></p></div></div>
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #22c55e;">
        <h3>Done</h3><p style="color:#22c55e;"><?= $done ?></p></div></div>
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #ef4444;">
        <h3>Pending</h3><p style="color:#ef4444;"><?= $pending ?></p></div></div>
</div>

<div class="erp-card mb-3 py-3">
    <div class="d-flex justify-content-between mb-2">
        <span style="font-size:.85rem;font-weight:600;"><?= h($parentView) ?> — <?= $monthLabel ?></span>
        <span style="font-weight:800;color:<?= pctColor($pct) ?>;"><?= $pct ?>%</span>
    </div>
    <div class="track-bar-wrap"><div class="track-bar" style="width:<?= $pct ?>%;background:<?= pctColor($pct) ?>;"></div></div>
</div>

<div class="erp-card">
    <h6 class="fw-bold mb-3">Sub-Divisions in <?= h($parentView) ?></h6>
    <?php foreach ($divisionMap[$parentView] as $sub):
        $s    = isset($subStatMap[$sub]) ? $subStatMap[$sub] : array('total'=>0,'done'=>0,'pending'=>0);
        $spct = (int)$s['total'] > 0 ? round((int)$s['done']/(int)$s['total']*100) : 0;
        $sc   = pctColor($spct);
    ?>
    <div style="padding:14px 0;border-bottom:1px solid #f3f4f6;">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <div>
                <div class="fw-bold" style="font-size:.9rem;"><?= h($sub) ?></div>
                <div style="font-size:.74rem;color:#9ca3af;"><?= (int)$s['total'] ?> consumers</div>
            </div>
            <span style="font-size:1.1rem;font-weight:800;color:<?= $sc ?>;"><?= $spct ?>%</span>
        </div>
        <div class="track-bar-wrap mb-2"><div class="track-bar" style="width:<?= $spct ?>%;background:<?= $sc ?>;"></div></div>
        <div class="d-flex justify-content-between align-items-center">
            <div style="font-size:.77rem;">
                <span class="done-pill me-1"><i class="bi bi-check-circle-fill"></i><?= (int)$s['done'] ?> Done</span>
                <span class="pending-pill"><i class="bi bi-clock-fill"></i><?= (int)$s['pending'] ?> Pending</span>
            </div>
            <div class="d-flex gap-1">
                <a href="<?= tUrl(array('div'=>$sub,'status'=>'all')) ?>" class="btn btn-sm btn-outline-primary" style="font-size:.74rem;padding:3px 10px;">
                    <i class="bi bi-eye me-1"></i>All
                </a>
                <?php if ((int)$s['pending'] > 0): ?>
                <a href="<?= tUrl(array('div'=>$sub,'status'=>'pending')) ?>" class="btn btn-sm btn-danger" style="font-size:.74rem;padding:3px 10px;">
                    <i class="bi bi-clock me-1"></i>Pending
                </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php else: ?>
<!-- ═══════════════════════════════════════════════════════════
     LEVEL 3 / MR: Consumer list
═══════════════════════════════════════════════════════════ -->
<?php if (!$isMR): ?>
<a href="<?= tUrl(array('div'=>'','status'=>'all')) ?>" class="btn btn-outline-secondary btn-sm mb-3">
    <i class="bi bi-arrow-left me-1"></i><?= $parentView ? h($parentView) : 'All Divisions' ?>
</a>
<?php endif; ?>

<!-- Stats -->
<div class="row g-3 mb-3">
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #6366f1;">
        <h3>Total</h3><p style="color:#6366f1;"><?= $total ?></p></div></div>
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #22c55e;">
        <h3>Done</h3><p style="color:#22c55e;"><?= $done ?></p></div></div>
    <div class="col-4"><div class="erp-card track-stat" style="border-top:3px solid #ef4444;">
        <h3>Pending</h3><p style="color:#ef4444;"><?= $pending ?></p></div></div>
</div>

<!-- Progress -->
<div class="erp-card mb-3 py-3">
    <div class="d-flex justify-content-between mb-2">
        <span style="font-size:.85rem;font-weight:600;">
            <?= $isMR ? 'My Division' : h($divView) ?> — <?= $monthLabel ?>
        </span>
        <span style="font-weight:800;color:<?= pctColor($pct) ?>;"><?= $pct ?>%</span>
    </div>
    <div class="track-bar-wrap"><div class="track-bar" style="width:<?= $pct ?>%;background:<?= pctColor($pct) ?>;"></div></div>
    <div class="d-flex justify-content-between mt-1" style="font-size:.72rem;color:#9ca3af;">
        <span><?= $done ?> done</span><span><?= $pending ?> pending</span>
    </div>
</div>

<?php if ($isMR): ?>
<!-- MR Analytics -->
<div class="erp-card mb-3">
    <div class="row g-0 text-center mb-3" style="border-bottom:1px solid #f0f0f0;padding-bottom:12px;">
        <div class="col-3" style="border-right:1px solid #f0f0f0;">
            <div style="font-size:1.5rem;font-weight:800;color:#6366f1;"><?= $mrToday ?></div>
            <div style="font-size:.68rem;color:#9ca3af;">Today Readings</div>
        </div>
        <div class="col-3" style="border-right:1px solid #f0f0f0;">
            <div style="font-size:1.5rem;font-weight:800;color:#22c55e;"><?= $mrMonthReads ?></div>
            <div style="font-size:.68rem;color:#9ca3af;"><?= date('M') ?> Readings</div>
        </div>
        <div class="col-3" style="border-right:1px solid #f0f0f0;">
            <div style="font-size:1.5rem;font-weight:800;color:#f59e0b;"><?= $mrTodayBills ?></div>
            <div style="font-size:.68rem;color:#9ca3af;">Today Bills</div>
        </div>
        <div class="col-3">
            <div style="font-size:1.5rem;font-weight:800;color:#ef4444;"><?= $pending ?></div>
            <div style="font-size:.68rem;color:#9ca3af;">Pending</div>
        </div>
    </div>
    <!-- Last 7 days bar -->
    <div style="font-size:.72rem;color:#9ca3af;margin-bottom:6px;font-weight:600;">Last 7 Days Readings</div>
    <div style="display:flex;align-items:flex-end;gap:4px;height:54px;">
        <?php foreach ($l7Map as $date => $cnt):
            $barH  = $cnt > 0 ? max(5, round($cnt / $l7Max * 46)) : 2;
            $isToday = ($date === date('Y-m-d'));
        ?>
        <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;">
            <?php if ($cnt > 0): ?>
            <span style="font-size:.58rem;color:#6366f1;font-weight:700;"><?= $cnt ?></span>
            <?php else: ?><span style="font-size:.58rem;">&nbsp;</span><?php endif; ?>
            <div style="width:100%;background:<?= $isToday ? '#6366f1' : ($cnt > 0 ? '#a5b4fc' : '#e5e7eb') ?>;
                 border-radius:3px 3px 0 0;height:<?= $barH ?>px;
                 <?= $isToday ? 'box-shadow:0 0 6px rgba(99,102,241,.5);' : '' ?>"></div>
            <span style="font-size:.6rem;color:<?= $isToday ? '#6366f1' : '#9ca3af' ?>;font-weight:<?= $isToday ? '700' : '400' ?>;">
                <?= date('D', strtotime($date)) ?>
            </span>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php if (!empty($mrFallback)): ?>
<div class="alert alert-warning d-flex align-items-center gap-2 mb-3" style="font-size:.83rem;">
    <i class="bi bi-exclamation-triangle-fill flex-shrink-0"></i>
    <span>Your assigned division did not match any consumer records. Showing all consumers. Contact admin to fix your division assignment.</span>
</div>
<?php endif; ?>

<!-- Filter tabs -->
<div class="tab-bar mb-3">
    <a href="<?= tUrl(array('status'=>'all')) ?>"     class="<?= $statusFilter==='all'    ?'active':'' ?>">All (<?= $total ?>)</a>
    <a href="<?= tUrl(array('status'=>'pending')) ?>" class="<?= $statusFilter==='pending'?'active':'' ?>">Pending (<?= $pending ?>)</a>
    <a href="<?= tUrl(array('status'=>'done')) ?>"    class="<?= $statusFilter==='done'   ?'active':'' ?>">Done (<?= $done ?>)</a>
</div>

<!-- Consumer list -->
<div class="erp-card">
<?php if (empty($displayed)): ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-check2-all" style="font-size:2.5rem;color:#22c55e;opacity:.5;"></i>
        <p class="mt-2 fw-semibold"><?= $statusFilter==='pending'?'All consumers done for '.$monthLabel.'!':'No records.' ?></p>
    </div>
<?php else: ?>
    <!-- Mobile -->
    <div class="d-md-none">
        <?php foreach ($displayed as $c):
            $isDone = $c['read_count'] > 0; ?>
        <div style="padding:11px 0;border-bottom:1px solid #f3f4f6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="fw-semibold" style="font-size:.87rem;"><?= h($c['consumer_name']) ?></div>
                    <div style="font-size:.74rem;color:#9ca3af;">
                        Meter: <?= h($c['meter_number']) ?>
                        <?php if ($c['connection_number']): ?> &nbsp;|&nbsp; Conn: <?= h($c['connection_number']) ?><?php endif; ?>
                    </div>
                    <div style="font-size:.73rem;color:#9ca3af;"><?= h($c['division']) ?> &nbsp; <?= typeBadge($c['type']) ?></div>
                </div>
                <span class="<?= $isDone?'done-pill':'pending-pill' ?>">
                    <i class="bi bi-<?= $isDone?'check-circle-fill':'clock-fill' ?>"></i>
                    <?= $isDone?'Done':'Pending' ?>
                </span>
            </div>
            <?php if ($isDone && $c['last_read_date']): ?>
            <div style="font-size:.72rem;color:#22c55e;margin-top:4px;">
                <i class="bi bi-calendar-check me-1"></i>Last read: <?= date('d M Y', strtotime($c['last_read_date'])) ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Desktop -->
    <div class="d-none d-md-block table-responsive">
        <table class="table table-hover mb-0" style="font-size:.83rem;">
            <thead class="table-light">
                <tr><th>#</th><th>Consumer</th><th>Meter No</th><th>Conn No</th><th>Type</th><th>Sub-Division</th><th class="text-center">Status</th><th>Last Reading</th></tr>
            </thead>
            <tbody>
                <?php $n=1; foreach ($displayed as $c): $isDone = $c['read_count'] > 0; ?>
                <tr>
                    <td class="text-muted"><?= $n++ ?></td>
                    <td class="fw-semibold"><?= h($c['consumer_name']) ?></td>
                    <td><?= h($c['meter_number']) ?></td>
                    <td><?= h($c['connection_number'] ?? '—') ?></td>
                    <td><?= typeBadge($c['type']) ?></td>
                    <td style="font-size:.78rem;"><?= h($c['division'] ?? '—') ?></td>
                    <td class="text-center">
                        <span class="<?= $isDone?'done-pill':'pending-pill' ?>">
                            <i class="bi bi-<?= $isDone?'check-circle-fill':'clock-fill' ?>"></i>
                            <?= $isDone?'Done':'Pending' ?>
                        </span>
                    </td>
                    <td class="text-muted" style="font-size:.77rem;">
                        <?= $c['last_read_date'] ? date('d M Y', strtotime($c['last_read_date'])) : '—' ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>
</div>

<?php endif; ?>

<script>
(function() {
    const input = document.getElementById('trkSearch');
    const btn   = document.getElementById('trkBtn');
    const result= document.getElementById('trkResult');
    if (!input) return;

    function doSearch() {
        const q = input.value.trim();
        if (q.length < 2) { result.innerHTML = '<div class="text-muted" style="font-size:.82rem;">Enter at least 2 characters.</div>'; return; }
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
        result.innerHTML = '<div class="d-flex align-items-center gap-2 text-muted py-1" style="font-size:.82rem;"><div class="spinner-border spinner-border-sm"></div>Searching…</div>';

        fetch(BASE_URL + '/modules/readings/search_consumer.php?q=' + encodeURIComponent(q) + '&type=kcc&check_bill=1')
            .then(r => r.json())
            .then(function(data) {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-search"></i>';
                if (data.success && data.consumer) {
                    const c = data.consumer;
                    const billDone = c.bill_this_month;
                    const billBadge = billDone
                        ? '<div class="d-flex align-items-center gap-2 mt-2 p-2" style="background:#fef3c7;border-radius:8px;font-size:.78rem;">' +
                          '<i class="bi bi-exclamation-circle-fill text-warning"></i>' +
                          '<span>Bill already distributed by <strong>' + escHtml(c.bill_mr_name||'') + '</strong> on ' + escHtml(c.bill_date||'') + '</span></div>'
                        : '';

                    result.innerHTML =
                        '<div style="border:1px solid #e5e7eb;border-radius:12px;padding:14px;margin-top:6px;">' +
                            '<div class="d-flex justify-content-between align-items-start">' +
                                '<div>' +
                                    '<div style="font-weight:700;font-size:.92rem;">' + escHtml(c.consumer_name) + '</div>' +
                                    '<div style="font-size:.76rem;color:#9ca3af;margin-top:2px;">' +
                                        'Meter: <strong>' + escHtml(c.meter_number) + '</strong>' +
                                        (c.connection_number ? ' &nbsp;|&nbsp; Conn: ' + escHtml(c.connection_number) : '') +
                                        (c.division ? ' &nbsp;|&nbsp; ' + escHtml(c.division) : '') +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                            billBadge +
                            '<div class="d-flex gap-2 flex-wrap mt-3">' +
                                '<a href="' + BASE_URL + '/modules/readings/add.php?type=solar&meter=' + encodeURIComponent(c.meter_number) + '" ' +
                                   'class="btn btn-sm" style="background:#fff3cd;color:#b45309;border:1px solid #fde68a;font-weight:600;">' +
                                    '<i class="bi bi-sun-fill me-1"></i>Solar Reading' +
                                '</a>' +
                                '<a href="' + BASE_URL + '/modules/readings/add.php?type=kcc&meter=' + encodeURIComponent(c.meter_number) + '" ' +
                                   'class="btn btn-sm" style="background:#dbeafe;color:#1d4ed8;border:1px solid #bfdbfe;font-weight:600;">' +
                                    '<i class="bi bi-lightning-fill me-1"></i>KCC Reading' +
                                '</a>' +
                                (billDone
                                    ? '<button class="btn btn-sm btn-secondary" disabled><i class="bi bi-receipt-cutoff me-1"></i>Bill Done</button>'
                                    : '<a href="' + BASE_URL + '/modules/bills/add.php?meter=' + encodeURIComponent(c.meter_number) + '" ' +
                                      'class="btn btn-sm" style="background:#dcfce7;color:#15803d;border:1px solid #bbf7d0;font-weight:600;">' +
                                        '<i class="bi bi-receipt-cutoff me-1"></i>Bill Distribute' +
                                      '</a>'
                                ) +
                            '</div>' +
                        '</div>';
                } else {
                    result.innerHTML = '<div class="alert alert-warning py-2 mt-2" style="font-size:.82rem;">' +
                        '<i class="bi bi-exclamation-triangle me-1"></i>' +
                        escHtml(data.message || 'Consumer not found.') + '</div>';
                }
            })
            .catch(function() {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-search"></i>';
                result.innerHTML = '<div class="alert alert-danger py-2 mt-2" style="font-size:.82rem;">Search failed. Check connection.</div>';
            });
    }

    window.trkDoSearch = doSearch;
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') { e.preventDefault(); doSearch(); }
    });

    // Auto-search if ?meter= in URL (when redirected from another page)
    const urlMeter = new URLSearchParams(window.location.search).get('meter');
    if (urlMeter) { input.value = urlMeter; doSearch(); }
})();
</script>

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