<?php
if (!defined('BASE_URL')) { die('Direct access not permitted.'); }

$db    = getDBConnection();
$today = date('Y-m-d');

// Summary counts
$totalSolar = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='solar'");
$totalKcc   = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='kcc'");
$totalBills = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills");
$todaySolar = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='solar' AND reading_date=?", [$today]);
$todayKcc   = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_type='kcc' AND reading_date=?", [$today]);
$todayBills = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills WHERE DATE(created_at)=?", [$today]);
$totalMRs   = (int)safeDbVal($db, "SELECT COUNT(*) FROM users WHERE role='mr' AND is_active=1");

// MR performance today
$mrStats = dbRows($db,
    "SELECT u.full_name, u.division,
            SUM(CASE WHEN r.reading_type='solar' THEN 1 ELSE 0 END) AS solar,
            SUM(CASE WHEN r.reading_type='kcc' THEN 1 ELSE 0 END) AS kcc
     FROM users u
     LEFT JOIN readings r ON r.user_id=u.id AND r.reading_date=?
     WHERE u.role='mr' AND u.is_active=1
     GROUP BY u.id
     ORDER BY (SUM(CASE WHEN r.reading_type='solar' THEN 1 ELSE 0 END) + SUM(CASE WHEN r.reading_type='kcc' THEN 1 ELSE 0 END)) DESC
     LIMIT 10", [$today]);

$pageTitle = 'Dashboard';
include __DIR__ . '/../../includes/header.php';
$role = getSession('role');
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-speedometer2 me-2 text-primary"></i>Dashboard</h1>
        <p class="text-muted mb-0" style="font-size:.85rem;">
            Welcome, <strong><?= h(getSession('full_name')) ?></strong> &mdash; <?= roleBadge($role) ?>
        </p>
    </div>
    <div class="text-muted small"><?= date('l, d M Y') ?></div>
</div>

<!-- ── Summary Stats ──────────────────────────────────────── -->
<div class="stats-grid mb-4">
    <div class="stat-card">
        <div class="stat-card-icon orange"><i class="bi bi-sun-fill"></i></div>
        <div><h3>Total Solar</h3><p><?= $totalSolar ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon blue"><i class="bi bi-lightning-fill"></i></div>
        <div><h3>Total KCC</h3><p><?= $totalKcc ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon green"><i class="bi bi-receipt"></i></div>
        <div><h3>Total Bills</h3><p><?= $totalBills ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon teal"><i class="bi bi-people-fill"></i></div>
        <div><h3>Active MRs</h3><p><?= $totalMRs ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon orange"><i class="bi bi-calendar-check"></i></div>
        <div><h3>Today Solar</h3><p><?= $todaySolar ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon blue"><i class="bi bi-calendar-check"></i></div>
        <div><h3>Today KCC</h3><p><?= $todayKcc ?></p></div>
    </div>
</div>

<!-- ── Quick Links ──────────────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-12 col-md-4">
        <a href="<?= BASE_URL ?>/modules/reports/index.php?type=solar" class="erp-action-card text-decoration-none">
            <div class="erp-action-icon" style="background:#fff3cd;color:#e65100;"><i class="bi bi-sun-fill"></i></div>
            <div class="erp-action-body"><h3>Solar Reports</h3><p>View &amp; export readings</p></div>
            <i class="bi bi-chevron-right erp-action-arrow"></i>
        </a>
    </div>
    <div class="col-12 col-md-4">
        <a href="<?= BASE_URL ?>/modules/reports/index.php?type=kcc" class="erp-action-card text-decoration-none">
            <div class="erp-action-icon" style="background:#e3f2fd;color:#1565c0;"><i class="bi bi-lightning-fill"></i></div>
            <div class="erp-action-body"><h3>KCC Reports</h3><p>View &amp; export readings</p></div>
            <i class="bi bi-chevron-right erp-action-arrow"></i>
        </a>
    </div>
    <div class="col-12 col-md-4">
        <a href="<?= BASE_URL ?>/modules/reports/index.php?type=bills" class="erp-action-card text-decoration-none">
            <div class="erp-action-icon" style="background:#e8f5e9;color:#2e7d32;"><i class="bi bi-receipt-cutoff"></i></div>
            <div class="erp-action-body"><h3>Bill Reports</h3><p>View &amp; export bills</p></div>
            <i class="bi bi-chevron-right erp-action-arrow"></i>
        </a>
    </div>
</div>

<!-- ── MR Performance Today ─────────────────────────────────── -->
<?php if (!empty($mrStats)): ?>
<div class="erp-card">
    <h6 class="fw-bold mb-3">MR Performance — Today (<?= date('d M Y') ?>)</h6>
    <div class="table-responsive">
        <table class="table table-hover mb-0" style="font-size:.84rem;">
            <thead class="table-light">
                <tr>
                    <th>#</th>
                    <th>Meter Reader</th>
                    <th>Division</th>
                    <th class="text-center">Solar</th>
                    <th class="text-center">KCC</th>
                    <th class="text-center">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($mrStats as $i => $m): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td class="fw-semibold"><?= h($m['full_name']) ?></td>
                    <td class="text-muted"><?= h($m['division'] ?? '—') ?></td>
                    <td class="text-center">
                        <span class="badge bg-warning text-dark"><?= (int)$m['solar'] ?></span>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-primary"><?= (int)$m['kcc'] ?></span>
                    </td>
                    <td class="text-center fw-bold"><?= (int)$m['solar']+(int)$m['kcc'] ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

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