<?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);

    // Join with rumah_ibadah to get name
    $stmt = $pdo->query("
        SELECT p.*, r.nama as rumah_ibadah_nama 
        FROM penduduk_miskin p
        LEFT JOIN rumah_ibadah r ON p.ibadah_id = r.id
        ORDER BY p.skor_prioritas DESC, p.id DESC
    ");
    $data = $stmt->fetchAll();

    // Get all anggota
    $stmtAnggota = $pdo->query("SELECT * FROM anggota_keluarga");
    $anggota = $stmtAnggota->fetchAll();
    
    // Map anggota to penduduk
    $anggotaByPenduduk = [];
    foreach ($anggota as $a) {
        $anggotaByPenduduk[$a['penduduk_id']][] = $a;
    }

    $stmtRiwayat = $pdo->query("SELECT * FROM riwayat_bantuan ORDER BY tanggal_bantuan DESC, id DESC");
    $riwayat = $stmtRiwayat->fetchAll();
    $riwayatByPenduduk = [];
    foreach ($riwayat as $r) {
        $riwayatByPenduduk[$r['penduduk_id']][] = $r;
    }

    foreach ($data as &$d) {
        $d['anggota'] = $anggotaByPenduduk[$d['id']] ?? [];
        $d['riwayat_bantuan'] = $riwayatByPenduduk[$d['id']] ?? [];
        $d['label_prioritas'] = getPriorityLabel((int)($d['skor_prioritas'] ?? 0));
    }

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