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

try {
    // Daily registrations + revenue for last 30 days
    $dailylabels = [];
    $dailycounts = [];
    $dailyrevenue = [];

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

    $revrows = $pdo->query("SELECT DATE(paidat) d, COALESCE(SUM(amount),0) s FROM paymentorder
        WHERE isdeleted = 0 AND status = 'paid' AND paidat >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
        GROUP BY DATE(paidat)")->fetchAll();
    $revmap = [];
    foreach ($revrows as $r) { $revmap[$r['d']] = moneyStr($r['s']); }

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

    // Panchayat-wise
    $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();
    $panchayatlabels = [];
    $panchayatcounts = [];
    foreach ($panchayatrows as $r) {
        $panchayatlabels[] = $r['name'];
        $panchayatcounts[] = (int)$r['c'];
    }

    // Status-wise
    $statusrows = $pdo->query("SELECT status, COUNT(*) c FROM villager WHERE isdeleted = 0 GROUP BY status")->fetchAll();
    $statuslabels = [];
    $statuscounts = [];
    foreach ($statusrows as $r) {
        $statuslabels[] = $r['status'];
        $statuscounts[] = (int)$r['c'];
    }

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