<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(["status" => "error", "pesan" => "Akses ditolak. Silakan login."]);
    exit;
}

header('Content-Type: application/json');

// KONEKSI DATABASE MENGGUNAKAN STANDAR PDO
$host = 'localhost';
$dbname = 'webgis_baru'; // Sesuaikan jika nama databasemu berbeda
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(json_encode(["error" => "Koneksi PDO Gagal: " . $e->getMessage()]));
}

$aksi = $_GET['aksi'] ?? 'global';

if ($aksi == 'global') {
    // 1. PERBAIKAN: Menambahkan WHERE status = 'berhasil' agar donasi pending tidak ikut terhitung di index.php
    $stmtMasuk = $pdo->query("SELECT SUM(nominal) AS total_masuk, COUNT(id) AS jml_donatur FROM donasi_digital WHERE status = 'berhasil'");
    $dataMasuk = $stmtMasuk->fetch(PDO::FETCH_ASSOC);
    $total_donasi = $dataMasuk['total_masuk'] ?? 0;
    $jml_donatur = $dataMasuk['jml_donatur'] ?? 0;

    // 2. Tarik Semua Log Distribusi ke Warga Miskin
    $stmtDistribusi = $pdo->query("
        SELECT 
            h.id, h.jenis_id, h.tanggal_distribusi, h.nama_penyalur, h.jumlah, h.satuan_custom, h.catatan, 
            w.nama_kk, w.lat, w.lng 
        FROM histori_bantuan h
        JOIN warga_miskin w ON h.warga_id = w.id
        ORDER BY h.tanggal_distribusi DESC
    ");
    $log_distribusi = $stmtDistribusi->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "total_donasi" => $total_donasi,
        "jumlah_donatur" => $jml_donatur,
        "log_distribusi" => $log_distribusi
    ]);
}
?>