<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

try {
    $total = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0")->fetch()['c'];
    $pending = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND status = 'pending'")->fetch()['c'];
    $approved = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND status = 'approved'")->fetch()['c'];
    $rejected = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND status = 'rejected'")->fetch()['c'];
    $active = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND passactive = 1")->fetch()['c'];
    $expiring = $pdo->query("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND passactive = 1
        AND passenddate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)")->fetch()['c'];

    $revenuerow = $pdo->query("SELECT COALESCE(SUM(amount),0) s FROM paymentorder WHERE isdeleted = 0 AND status = 'paid'")->fetch();
    $revenue = moneyStr($revenuerow['s']);

    $panchayatrows = $pdo->query("SELECT p.name, COUNT(v.id) c FROM panchayat p
        LEFT JOIN villager v ON v.panchayatid = p.id AND v.isdeleted = 0
        WHERE p.isdeleted = 0 GROUP BY p.id, p.name")->fetchAll();

    $labels = [];
    $counts = [];
    foreach ($panchayatrows as $row) {
        $labels[] = $row['name'];
        $counts[] = (int)$row['c'];
    }

    jsonOut(true, '', [
        'total' => (int)$total,
        'pending' => (int)$pending,
        'approved' => (int)$approved,
        'rejected' => (int)$rejected,
        'active' => (int)$active,
        'expiring' => (int)$expiring,
        'revenueformatted' => formatINR($revenue),
        'panchayatlabels' => $labels,
        'panchayatcounts' => $counts,
    ]);
} catch (Exception $e) {
    logDebug('[ajax_admin_dashboardstats] ' . $e->getMessage());
    jsonOut(false, 'Failed to load dashboard stats');
}
