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

$type = $_GET['type'] ?? '';
$id = $_GET['id'] ?? '';

// API endpoints
$base_url = 'https://www.emsifa.com/api-wilayah-indonesia/api/';

try {
    switch ($type) {
        case 'provinces':
            $url = $base_url . 'provinces.json';
            break;
        case 'regencies':
            if (!$id) {
                throw new Exception('Province ID required');
            }
            $url = $base_url . 'regencies/' . $id . '.json';
            break;
        case 'districts':
            if (!$id) {
                throw new Exception('Regency ID required');
            }
            $url = $base_url . 'districts/' . $id . '.json';
            break;
        case 'villages':
            if (!$id) {
                throw new Exception('District ID required');
            }
            $url = $base_url . 'villages/' . $id . '.json';
            break;
        default:
            throw new Exception('Invalid type');
    }

    // Create context with timeout
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'method' => 'GET',
            'header' => "User-Agent: Mozilla/5.0\r\n"
        ]
    ]);

    $response = file_get_contents($url, false, $context);

    if ($response === FALSE) {
        throw new Exception('Failed to fetch data from API');
    }

    $data = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON response');
    }

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