<?php

namespace App\Http\Controllers;

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


class CityController extends Controller
{
   public function index($id){
        $city = AreaModel::where('parent_id', $id)->get();
        $stateId = $id;
        $data = compact('city', 'stateId');
        return view('city/index')->with($data);
    }
    
    public function addCity($id, Request $req){
        $stateId = $id;
        $data = compact('stateId');
        return view('city/add')->with($data);
    }
     
    public function cityCreate($id, Request $req){
        $req->validate(
            [
                'name' => 'required',
            ]
        ); 
        
        $city = new AreaModel; 
        $city->parent_id = $id;
        $city->name = $req['name'];
        $city->save();

        return redirect('/city/'.$id)->with('success', 'City Added Successfully!');
    }
    
    public function editCity($id){
        $city = AreaModel::find($id);
        if(is_null($city)){
            return redirect('/city/'.$city->parent_id);
        }else{
            $data = compact('city');
           return view('city/edit')->with($data);
        }
    }
    
     public function updatecity($id, Request $req){
        $city = AreaModel::find($id);
        $req->validate(
            [
                'name' => 'required',
            ]
        );
        $city->name = $req['name'];
        $city ->save();
        return redirect('/city/'.$city->parent_id)->with('success', 'City Updated Successfully!');
    }
    
}

