<?php

namespace App\Http\Controllers;

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

class Country extends Controller
{
    public function index(){
        $country = AreaModel::whereNull('parent_id')->get();
        $data = compact('country');
        return view('country/index')->with($data);
    }
    
    public function addCountry(Request $req){
        return view('country/add');
    }
     
    public function countryCreate(Request $req){
        $req->validate(
            [
                'name' => 'required',
            ]
        ); 
        
        $country = new AreaModel; 
        $country->name = $req['name'];
        $country->save();

        return redirect('/country')->with('success', 'Country Added Successfully!');
    }
    
    public function editCountry($id){
        $country = AreaModel::find($id);
        if(is_null($country)){
            return redirect('/country');
        }else{
            $data = compact('country');
           return view('country/edit')->with($data);
        }
    }
    
     public function updatecountry($id, Request $req){
        $country = AreaModel::find($id);
        $req->validate(
            [
                'name' => 'required',
            ]
        );
        $country->name = $req['name'];
        $country ->save();
        return redirect('/country')->with('success', 'Country Updated Successfully!');
    }
    
    
    
    public function ajaxNoOfState(Request $req){
        $country_id = $req['country_id'];
        $state = AreaModel::where('parent_id', $country_id)->get();
        $str = '<select name="state_id" class="form-select" id="state_id">';
        $str .= '<option value="">Select State</option>';
        foreach($state as $s){
            $str .= '<option value="'.$s->area_id.'">'.$s->name.'</option>';
        }
        $str .= '</select>';
        
        echo $str;
    }
    
    public function ajaxNoOfCity(Request $req){
        $state_id = $req['state_id'];
        $city = AreaModel::where('parent_id', $state_id)->get();
        $str = '<select name="city_id" class="form-select" id="city_id">';
        $str .= '<option value="">Select City</option>';
        foreach($city as $c){
            $str .= '<option value="'.$c->area_id.'">'.$c->name.'</option>';
        }
        $str .= '</select>';
        
        echo $str;
    }
    
}
