<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\City;
use App\State;
use App\District;

class DataController extends Controller
{
    public function getCity(Request $request)
    {
		
		$search = $request['searchTerm'];
		$datas = City::where('name','like','%'.$search.'%')->get();
		foreach($datas as $data){
			$result[] = array("id" => $data['id'],
				"text" => $data['name']);
		}
		return response()
            ->json($result);
    }
	
	public function getStateFromCity(Request $request)
    {
		
		$city = $request['city'];
		$citydata = City::where('id','=',$city)->first();
		$statedata = State::where('state_id','=',$citydata['state_id'])->first();
		$districtData = District::where('districtid','=',$citydata['districtid'])->first();

		return response()->json(['state'=>$statedata,'district'=>$districtData]);
    }
	
	public function addCity(Request $request,$city="" ,$state_title = ""){	

		if($city){	
			$last_state = State::latest('id')->first();
			$state  = new State(['state_id' => $last_state['state_id']+1,'state_title' => $state_title,'state_description' =>96,'status'=>'Active']);
			$state->save();
			$city = new City([
				'name' => $city,
				'state_id' => $state->state_id,
				]);
				$city->save();
				$data = array(['city'=>$city->id , 'state'=>$state->state_id ]);
			return $data;
		}else{
			$city = new City([
				'name' => $request->city,
				'state_id' => $request->state_id,
				]);
				$city->save();
			if($city){
				return response()->json(['message'=>"City Added!",'status'=>true]);
			}else{
				return response()->json(['message'=>"City not Added!",'status'=>false]);
			}
		}
	}

	public function getCityState(Request $request)
    {
		
		$search = $request['searchTerm'];
		$datas = State::where('state_title','like','%'.$search.'%')->get();
		foreach($datas as $data){
			$result[] = array("id" => $data['state_id'],
				"text" => $data['state_title']);
		}
		return response()
            ->json($result);
    }

}
