<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\City;

class CityController extends Controller
{
    public function index(Request $request){
        try {
           // return response()->json($request->query('id'));

            $data = City::orderBy('city_name')->get();
            $responseData = [ 'records' => $data ];
            return response()->json($responseData);
            
        } catch (QueryException $e) {
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }

    public function byState(Request $request, $id){
        try {
           // return response()->json($request->query('id'));

            $data = City::where('state_id', $id)->orderBy('city_name')->get();
            $responseData = [ 'records' => $data ];
            return response()->json($responseData);
            
        } catch (QueryException $e) {
            return response()->json(['message' => 'Database error: ' . $e->getMessage()], 500);
        } catch (\Exception $e) {
            return response()->json(['message' => 'An unexpected error occurred: ' . $e->getMessage()], 500);
        }
    }
}
