<?php
header('Content-Type: application/json');
require_once 'config.php';

try {
    $db = getDB();

    // Derive province totals from seeded need-point names.
    // The peta seed data stores the region name inside need_points.name, so we
    // map those region labels back to provinces and rank them by count.
    $provinceMap = [
        'DKI Jakarta' => ['Jakarta'],
        'Jawa Barat' => ['Bandung', 'Bekasi'],
        'Jawa Tengah' => ['Semarang'],
        'DI Yogyakarta' => ['Yogyakarta'],
        'Jawa Timur' => ['Surabaya', 'Malang'],
        'Sumatera Utara' => ['Medan'],
        'Sumatera Selatan' => ['Palembang'],
        'Riau' => ['Pekanbaru'],
        'Jambi' => ['Jambi'],
        'Sumatera Barat' => ['Padang'],
        'Sulawesi Selatan' => ['Makassar'],
        'Sulawesi Utara' => ['Manado'],
        'Sulawesi Tenggara' => ['Kendari'],
        'Sulawesi Tengah' => ['Palu'],
        'Kalimantan Selatan' => ['Banjarmasin'],
        'Kalimantan Barat' => ['Pontianak'],
        'Kalimantan Timur' => ['Samarinda'],
        'Kalimantan Tengah' => ['Palangkaraya'],
        'Papua' => ['Jayapura'],
        'Nusa Tenggara Barat' => ['Mataram'],
        'Nusa Tenggara Timur' => ['Kupang'],
        'Maluku' => ['Ambon'],
        'Bali' => ['Denpasar']
    ];

    $needPoints = $db->query('SELECT name FROM need_points')->fetchAll(PDO::FETCH_COLUMN);
    $provinceCounts = [];

    foreach ($provinceMap as $province => $regions) {
        $provinceCounts[$province] = 0;
        foreach ($needPoints as $pointName) {
            foreach ($regions as $region) {
                if (stripos($pointName, $region) !== false) {
                    $provinceCounts[$province]++;
                    break;
                }
            }
        }
    }

    arsort($provinceCounts);
    $topProvinces = array_slice($provinceCounts, 0, 5, true);

    $areaStats = [];
    foreach ($topProvinces as $provinceName => $count) {
        $areaStats[] = [
            'id' => null,
            'area_name' => $provinceName,
            'area_type' => 'province',
            'household_count' => (int)$count,
            'avg_poverty_score' => 0,
            'verified_count' => 0,
            'assisted_count' => 0
        ];
    }

    $response = [
        'success' => true,
        'areas' => $areaStats
    ];

    http_response_code(200);
    die(json_encode($response));

} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode(['error' => 'Database error: ' . $e->getMessage()]));
}
