<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Fungsi untuk mengambil data dari API wilayah.id dengan curl
function fetchFromAPI($url) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Untuk development saja
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        return ['error' => true, 'message' => 'CURL Error: ' . $error];
    }
    
    curl_close($ch);
    
    if ($http_code !== 200) {
        return ['error' => true, 'message' => 'HTTP Error: ' . $http_code];
    }
    
    return json_decode($response, true);
}

// Tentukan endpoint berdasarkan parameter
$endpoint = isset($_GET['endpoint']) ? $_GET['endpoint'] : '';
$province_code = isset($_GET['province_code']) ? $_GET['province_code'] : '';

if ($endpoint === 'provinces') {
    $data = fetchFromAPI('https://wilayah.id/api/provinces.json');
    echo json_encode($data);
    
} elseif ($endpoint === 'regencies' && $province_code) {
    $data = fetchFromAPI("https://wilayah.id/api/regencies/{$province_code}.json");
    echo json_encode($data);
    
} else {
    echo json_encode(['error' => true, 'message' => 'Invalid endpoint']);
}
?>