<?php


namespace Mehrab\City\Repositories;


use Illuminate\Support\Str;
use Mehrab\City\Models\City;

class CityRepo
{


    public function all()
    {
        return City::query()
        ->withCount('regions')
        ->paginate(35);
    }

    public function all_with_regions()
    {
        return City::with('regions')->get();
    }

    public function store($request)
    {
        $data = [
            'name' => $request->name,
            'slug' => Str::slug($request->slug),
            'priority' =>  $request->priority ?? null,
        ];
        return City::query()->create($data);
    }

    public function findById($cityID)
    {
        return City::query()->findOrFail($cityID);
    }

    public function update($request, $id)
    {
       $city = $this->findById($id);
      return  $city->update([
          'name' => $request->name,
          'slug' => $request->slug,
          'priority' => $request->priority ?? null,
      ]);
    }

    public function findBySlug($slug){
        return City::query()->where('name',$slug)->first();
    }

    public function status($id)
    {
        $city = $this->findById($id);
        if ($city->status == City::ACTIVE){
            $city->status = City::INACTIVE;
        }elseif ($city->status == City::INACTIVE){
            $city->status = City::ACTIVE;
        }
        $city->save();
        return $city->status;
    }

    public function createRegions(array $regions,$id){

       $city =  $this->findById($id);
       return $city->regions()->create($regions);
    }


}
