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

$panchayatid = currentPanchayatId();

try {
    $dailylabels = [];
    $dailycounts = [];

    $stmt = $pdo->prepare("SELECT DATE(createdat) d, COUNT(*) c FROM villager
        WHERE isdeleted = 0 AND panchayatid = ? AND createdat >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
        GROUP BY DATE(createdat)");
    $stmt->execute([$panchayatid]);
    $regmap = [];
    foreach ($stmt->fetchAll() as $r) { $regmap[$r['d']] = (int)$r['c']; }

    for ($i = 29; $i >= 0; $i--) {
        $day = date('Y-m-d', strtotime("-{$i} days"));
        $dailylabels[] = date('d-M', strtotime($day));
        $dailycounts[] = $regmap[$day] ?? 0;
    }

    $stmt = $pdo->prepare("SELECT status, COUNT(*) c FROM villager WHERE isdeleted = 0 AND panchayatid = ? GROUP BY status");
    $stmt->execute([$panchayatid]);
    $statuslabels = [];
    $statuscounts = [];
    foreach ($stmt->fetchAll() as $r) {
        $statuslabels[] = $r['status'];
        $statuscounts[] = (int)$r['c'];
    }

    jsonOut(true, '', [
        'dailylabels' => $dailylabels,
        'dailycounts' => $dailycounts,
        'statuslabels' => $statuslabels,
        'statuscounts' => $statuscounts,
    ]);
} catch (Exception $e) {
    logDebug('[ajax_panchayat_reportdata] ' . $e->getMessage());
    jsonOut(false, 'Failed to load report data');
}
