<?php
require_once 'db_pdo.php';
require_once 'auth.php';
require_once 'penduduk_feature_helper.php';
require_admin_login(true);
header('Content-Type: application/json');

try {
    ensurePendudukFeatureSchema($pdo);
    refreshAllPriorityScores($pdo);

    $stats = [];
    
    $ri = $pdo->query("SELECT COUNT(*) as total FROM rumah_ibadah")->fetch();
    $stats['total_rumah_ibadah'] = $ri['total'];

    $pm = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin")->fetch();
    $stats['total_penduduk'] = $pm['total'];

    $pm_sudah = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE status_bantuan = 'Sudah dibantu'")->fetch();
    $stats['sudah_dibantu'] = $pm_sudah['total'];

    $pm_belum = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE status_bantuan = 'Belum dibantu'")->fetch();
    $stats['belum_dibantu'] = $pm_belum['total'];
    
    $pm_tunggu = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE status_bantuan = 'Menunggu verifikasi'")->fetch();
    $stats['menunggu_verifikasi'] = $pm_tunggu['total'];

    $blank = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE is_blank_spot = 1")->fetch();
    $stats['luar_radius'] = $blank['total'];

    $prioritas = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE skor_prioritas >= 70")->fetch();
    $stats['prioritas_tinggi'] = $prioritas['total'];

    $survei = $pdo->query("SELECT COUNT(*) as total FROM penduduk_miskin WHERE tindak_lanjut IN ('Sudah disurvei', 'Sudah diverifikasi')")->fetch();
    $stats['sudah_survei'] = $survei['total'];

    $stats['top_prioritas'] = $pdo->query("
        SELECT id, kk_nama, kategori_kebutuhan, tindak_lanjut, skor_prioritas
        FROM penduduk_miskin
        ORDER BY skor_prioritas DESC, id DESC
        LIMIT 5
    ")->fetchAll();

    $stats['kebutuhan_terbanyak'] = $pdo->query("
        SELECT COALESCE(NULLIF(kategori_kebutuhan, ''), 'Belum diisi') AS kategori, COUNT(*) AS total
        FROM penduduk_miskin
        GROUP BY COALESCE(NULLIF(kategori_kebutuhan, ''), 'Belum diisi')
        ORDER BY total DESC
        LIMIT 5
    ")->fetchAll();

    echo json_encode([
        'success' => true,
        'data' => $stats
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
