<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Province;
use App\Models\City;
use App\Models\District;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RegionApiController extends Controller
{
    /**
     * AMBIL DAFTAR PROVINSI
     */
    public function getProvinces()
    {
        try {
            $data = Province::orderBy('name', 'asc')->get();
            
            return response()->json([
                'success' => true, 
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("Get Provinces Error: " . $e->getMessage());
            return response()->json([
                'success' => false, 
                'message' => 'Terjadi kesalahan saat memuat data provinsi.'
            ], 500);
        }
    }

    /**
     * AMBIL DAFTAR KOTA/KABUPATEN BERDASARKAN PROVINSI
     */
    public function getCities($provinceId)
    {
        try {
            $data = City::where('province_id', $provinceId)
                ->orderBy('name', 'asc')
                ->get();
                
            return response()->json([
                'success' => true, 
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("Get Cities Error: " . $e->getMessage());
            return response()->json([
                'success' => false, 
                'message' => 'Terjadi kesalahan saat memuat data kota/kabupaten.'
            ], 500);
        }
    }

    /**
     * AMBIL DAFTAR KECAMATAN BERDASARKAN KOTA/KABUPATEN
     */
    public function getDistricts($cityId)
    {
        try {
            $data = District::where('city_id', $cityId)
                ->orderBy('name', 'asc')
                ->get();
                
            return response()->json([
                'success' => true, 
                'data' => $data
            ]);
        } catch (\Exception $e) {
            Log::error("Get Districts Error: " . $e->getMessage());
            return response()->json([
                'success' => false, 
                'message' => 'Terjadi kesalahan saat memuat data kecamatan.'
            ], 500);
        }
    }
}