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

$panchayatid = currentPanchayatId();

try {
    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ?");
    $stmt->execute([$panchayatid]);
    $total = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? AND status = 'pending'");
    $stmt->execute([$panchayatid]);
    $pending = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? AND status = 'approved'");
    $stmt->execute([$panchayatid]);
    $approved = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? AND status = 'rejected'");
    $stmt->execute([$panchayatid]);
    $rejected = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? AND passactive = 1");
    $stmt->execute([$panchayatid]);
    $active = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? AND passactive = 1
        AND passenddate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)");
    $stmt->execute([$panchayatid]);
    $expiring = $stmt->fetch()['c'];

    $stmt = $pdo->prepare("SELECT id, fullname, phone, createdat FROM villager
        WHERE isdeleted = 0 AND panchayatid = ? AND status = 'pending' ORDER BY createdat ASC LIMIT 10");
    $stmt->execute([$panchayatid]);
    $pendingrows = $stmt->fetchAll();

    jsonOut(true, '', [
        'total' => (int)$total,
        'pending' => (int)$pending,
        'approved' => (int)$approved,
        'rejected' => (int)$rejected,
        'active' => (int)$active,
        'expiring' => (int)$expiring,
        'pendingrows' => $pendingrows,
    ]);
} catch (Exception $e) {
    logDebug('[ajax_panchayat_dashboardstats] ' . $e->getMessage());
    jsonOut(false, 'Failed to load dashboard stats');
}
