<?php
// ============================================================
// FILE: wilayah.php — Proxy API Wilayah Indonesia
// Fetch dari emsifa.com (primary) atau ibnux (backup)
// Cache di session 1 jam untuk hemat request
// GET ?type=provinsi
// GET ?type=kabupaten&id=32
// GET ?type=kecamatan&id=3204
// GET ?type=kelurahan&id=320401
// ============================================================
require_once __DIR__ . '/includes/config.php';

header('Content-Type: application/json');
header('Cache-Control: public, max-age=3600');

$type = $_GET['type'] ?? '';
$id   = preg_replace('/[^0-9]/', '', $_GET['id'] ?? '');

// ── Caching di file ──────────────────────────────────────────
$cacheDir  = sys_get_temp_dir() . '/budijaya_wilayah/';
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0755, true);

$cacheKey  = md5($type . $id);
$cacheFile = $cacheDir . $cacheKey . '.json';
$cacheTTL  = 86400; // 24 jam

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL) {
    echo file_get_contents($cacheFile);
    exit;
}

// ── URL API primary & backup ──────────────────────────────────
function getApiUrl(string $type, string $id, string $source = 'primary'): string {
    if ($source === 'primary') {
        $base = 'https://www.emsifa.com/api-wilayah-indonesia/api';
        return match($type) {
            'provinsi'   => "$base/provinces.json",
            'kabupaten'  => "$base/regencies/$id.json",
            'kecamatan'  => "$base/districts/$id.json",
            'kelurahan'  => "$base/villages/$id.json",
            default      => '',
        };
    } else {
        $base = 'https://ibnux.github.io/data-indonesia';
        return match($type) {
            'provinsi'   => "$base/provinsi.json",
            'kabupaten'  => "$base/kabupaten/$id.json",
            'kecamatan'  => "$base/kecamatan/$id.json",
            'kelurahan'  => "$base/kelurahan/$id.json",
            default      => '',
        };
    }
}

// ── Normalize response dari dua sumber ───────────────────────
function normalizeData(array $data, string $type, string $source): array {
    if ($source === 'primary') {
        // emsifa: [{id, name}] atau [{id, province_id, name}]
        return array_map(fn($r) => [
            'id'   => $r['id']   ?? '',
            'nama' => $r['name'] ?? '',
        ], $data);
    } else {
        // ibnux: [{id, nama}]
        return array_map(fn($r) => [
            'id'   => $r['id']   ?? '',
            'nama' => $r['nama'] ?? $r['name'] ?? '',
        ], $data);
    }
}

// ── Fetch dengan cURL ─────────────────────────────────────────
function fetchJson(string $url): array|false {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT      => 'BudiJaya-Ecommerce/1.0',
        CURLOPT_FOLLOWLOCATION => true,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err || $code !== 200 || !$resp) return false;
    $data = json_decode($resp, true);
    return is_array($data) ? $data : false;
}

// ── Main logic ────────────────────────────────────────────────
if (!$type || ($type !== 'provinsi' && !$id)) {
    echo json_encode(['error' => 'Parameter tidak lengkap']);
    exit;
}

$result = null;

// Coba primary dulu
$url  = getApiUrl($type, $id, 'primary');
$data = $url ? fetchJson($url) : false;
if ($data !== false) {
    $result = normalizeData($data, $type, 'primary');
}

// Fallback ke backup
if ($result === null) {
    $url  = getApiUrl($type, $id, 'backup');
    $data = $url ? fetchJson($url) : false;
    if ($data !== false) {
        $result = normalizeData($data, $type, 'backup');
    }
}

if ($result === null) {
    http_response_code(503);
    echo json_encode(['error' => 'Data wilayah tidak tersedia. Coba lagi.']);
    exit;
}

$json = json_encode($result);

// Simpan cache
@file_put_contents($cacheFile, $json);

echo $json;