<?php

namespace App\Modules\Miscellaneous\StateCity;
use Illuminate\Support\Facades\Log;
use App\Models\State as StateModel;


class State{
    public function fetchState($payload){
       return StateModel::select('name')
       ->distinct()
       ->where('name', 'LIKE', $payload->state . '%')
       ->limit(20)
       ->get();
    }

    public function fetchCity($payload){
        $state = $payload->state;
        $city = $payload->city;

        return StateModel::select('city as name')
       ->distinct()
       ->where('states.name', 'LIKE', $state . '%')
       ->when(!empty($city), function ($query) use ($city) {
            return $query->where('states.city', 'LIKE', $city . '%');
        })
       ->limit(20)
       ->get();
    }

    public function validateState($payload){
        $state = $payload->state;

        $stateRes = StateModel::where('states.name', $state)->first();
        Log::info(json_encode($stateRes));
        return $stateRes;
    }

    public function validateCity($payload){
        $state = $payload->state;
        $city = $payload->city;

        $cityRes = StateModel::where('states.name', $state)->where('states.city', $city)->get();
        Log::info(json_encode($cityRes));
        return $cityRes;
    }
}