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

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

$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");
$totalConsumers = (int)safeDbVal($db, "SELECT COUNT(*) FROM consumers WHERE is_active=1");
$totalUsers     = (int)safeDbVal($db, "SELECT COUNT(*) FROM users WHERE is_active=1");
$totalMRs       = (int)safeDbVal($db, "SELECT COUNT(*) FROM users WHERE role='mr' AND is_active=1");
$todayReadings  = (int)safeDbVal($db, "SELECT COUNT(*) FROM readings WHERE reading_date=?", [$today]);
$todayBills     = (int)safeDbVal($db, "SELECT COUNT(*) FROM bills WHERE DATE(created_at)=?", [$today]);

// MR performance last 7 days
$mrPerformance = dbRows($db,
    "SELECT u.full_name,
            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,
            COUNT(r.id) AS total_readings
     FROM users u
     LEFT JOIN readings r ON r.user_id=u.id AND r.reading_date >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
     WHERE u.role='mr' AND u.is_active=1
     GROUP BY u.id ORDER BY total_readings DESC LIMIT 10");

// Recent readings
$recent = dbRows($db,
    "SELECT r.*, c.consumer_name, c.meter_number, u.full_name AS mr_name_full
     FROM readings r
     JOIN consumers c ON c.id=r.consumer_id
     JOIN users u ON u.id=r.user_id
     ORDER BY r.created_at DESC LIMIT 8");

$pageTitle = 'Admin Dashboard';
include __DIR__ . '/../../includes/header.php';
?>

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

<!-- ── System 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>Solar Total</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>KCC Total</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>Bills Total</h3><p><?= $totalBills ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon purple"><i class="bi bi-people-fill"></i></div>
        <div><h3>Consumers</h3><p><?= $totalConsumers ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon teal"><i class="bi bi-person-fill-check"></i></div>
        <div><h3>Users</h3><p><?= $totalUsers ?></p></div>
    </div>
    <div class="stat-card">
        <div class="stat-card-icon green"><i class="bi bi-calendar-check"></i></div>
        <div><h3>Today Readings</h3><p><?= $todayReadings ?></p></div>
    </div>
</div>

<!-- ── Quick Admin Actions ────────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/modules/admin/users.php" class="erp-action-card text-decoration-none p-3 flex-column text-center">
            <i class="bi bi-people-fill mb-2" style="font-size:1.8rem;color:var(--erp-primary);"></i>
            <span class="fw-semibold" style="font-size:.9rem;">Manage Users</span>
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/modules/admin/consumers.php" class="erp-action-card text-decoration-none p-3 flex-column text-center">
            <i class="bi bi-person-badge-fill mb-2" style="font-size:1.8rem;color:var(--erp-accent);"></i>
            <span class="fw-semibold" style="font-size:.9rem;">Consumers</span>
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/modules/reports/index.php?type=solar" class="erp-action-card text-decoration-none p-3 flex-column text-center">
            <i class="bi bi-file-earmark-bar-graph mb-2" style="font-size:1.8rem;color:#e65100;"></i>
            <span class="fw-semibold" style="font-size:.9rem;">Reports</span>
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/modules/admin/user_form.php" class="erp-action-card text-decoration-none p-3 flex-column text-center">
            <i class="bi bi-person-plus-fill mb-2" style="font-size:1.8rem;color:#2e7d32;"></i>
            <span class="fw-semibold" style="font-size:.9rem;">Add User</span>
        </a>
    </div>
</div>

<!-- ── MR Performance (7 days) ────────────────────────────────── -->
<?php if (!empty($mrPerformance)): ?>
<div class="erp-card mb-4">
    <h6 class="fw-bold mb-3">MR Performance (Last 7 Days)</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 class="text-center">Solar</th>
                    <th class="text-center">KCC</th>
                    <th class="text-center">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($mrPerformance as $i => $m): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td class="fw-semibold"><?= h($m['full_name']) ?></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['total_readings'] ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ── Recent Readings ─────────────────────────────────────────── -->
<div class="erp-card">
    <div class="d-flex align-items-center justify-content-between mb-3">
        <h6 class="fw-bold mb-0">Recent Readings</h6>
        <a href="<?= BASE_URL ?>/modules/reports/index.php" class="btn btn-sm btn-outline-secondary" style="font-size:.78rem;">View All</a>
    </div>
    <?php if (!empty($recent)): ?>
    <div class="table-responsive">
        <table class="table table-hover mb-0" style="font-size:.83rem;">
            <thead class="table-light">
                <tr><th>Consumer</th><th>MR</th><th>Type</th><th>Status</th><th>Photo</th><th>Date</th></tr>
            </thead>
            <tbody>
                <?php foreach ($recent as $r): ?>
                <tr>
                    <td>
                        <div class="fw-semibold"><?= h($r['consumer_name']) ?></div>
                        <small class="text-muted"><?= h($r['meter_number']) ?></small>
                    </td>
                    <td><?= h($r['mr_name_full']) ?></td>
                    <td><?= typeBadge($r['reading_type']) ?></td>
                    <td><?= statusBadge($r['status']) ?></td>
                    <td>
                        <?php if ($r['image_path']): ?>
                        <a href="<?= imgUrl($r['image_path']) ?>" target="_blank">
                            <img src="<?= imgUrl($r['image_path']) ?>" style="width:40px;height:40px;object-fit:cover;border-radius:4px;">
                        </a>
                        <?php else: ?>
                        <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-muted" style="font-size:.76rem;"><?= formatDt($r['created_at']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <p class="text-muted text-center py-3">No readings yet.</p>
    <?php endif; ?>
</div>

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