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

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

    $rows = $pdo->query("SELECT DATE(paidat) d, COUNT(*) c FROM villager
        WHERE isdeleted = 0 AND status = 'approved' AND paymentstatus = 'paid'
        AND paidat >= DATE_SUB(CURDATE(), INTERVAL 29 DAY) GROUP BY DATE(paidat)")->fetchAll();
    $map = [];
    foreach ($rows as $r) { $map[$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[] = $map[$day] ?? 0;
    }

    $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 AND v.status = 'approved' AND v.paymentstatus = 'paid'
        WHERE p.isdeleted = 0 GROUP BY p.id, p.name")->fetchAll();
    $panchayatlabels = [];
    $panchayatcounts = [];
    foreach ($panchayatrows as $r) {
        $panchayatlabels[] = $r['name'];
        $panchayatcounts[] = (int)$r['c'];
    }

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