<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Laravolt\Indonesia\Facade as Indonesia;

class AddressController extends Controller
{
    public function provinces()
    {
        $provinces = Indonesia::allProvinces();
        
        return response()->json([
            'data' => $provinces->map(function ($item) {
                return [
                    'id' => $item->id,
                    'code' => $item->code,
                    'name' => $item->name
                ];
            })
        ]);
    }

    public function cities(Request $request)
    {
        $provinceId = $request->query('province_id');
        
        $province = Indonesia::findProvince($provinceId, ['cities']);
        $cities = $province->cities ?? collect([]);
        
        return response()->json([
            'data' => $cities->map(function ($item) {
                return [
                    'id' => $item->id,
                    'code' => $item->code,
                    'province_id' => $item->province_id,
                    'name' => $item->name
                ];
            })
        ]);
    }

    public function districts(Request $request)
    {
        $cityId = $request->query('city_id');
        
        $city = Indonesia::findCity($cityId, ['districts']);
        $districts = $city->districts ?? collect([]);
        
        return response()->json([
            'data' => $districts->map(function ($item) {
                return [
                    'id' => $item->id,
                    'code' => $item->code,
                    'city_id' => $item->city_id,
                    'name' => $item->name
                ];
            })
        ]);
    }

    public function villages(Request $request)
    {
        $districtId = $request->query('district_id');
        
        $district = Indonesia::findDistrict($districtId, ['villages']);
        $villages = $district->villages ?? collect([]);
        
        return response()->json([
            'data' => $villages->map(function ($item) {
                return [
                    'id' => $item->id,
                    'code' => $item->code,
                    'district_id' => $item->district_id,
                    'name' => $item->name
                ];
            })
        ]);
    }
    
}