<?php


namespace App\Models\Traits;

use Illuminate\Support\Str;

trait HasSlug{

    public static function findByIdOrSlug($value){
        return ( (int) $value == 0 )
                ? self::findBySlug($value)
                : self::findOrFail($value);
    }

    public static function findBySlug($value){
        return self::where("slug",$value)->firstOrFail();
    }

//    public function slug(){
//        return $this->morphOne(Slug::class, Slug::MORPH_FUNCTION_NAME,
//            Slug::MORPH_TYPE_COLUMN,Slug::MORPH_ID_COLUMN);
//    }


//    public function getSlugValAttribute(){
//        return $this->slug->value;
//    }

    public function getRouteKeyName(){
        return $this->slug;
    }

    public function slugify(){
        $instance = get_class($this);
        $value = "";
        $model = $this;
        $slugAttributs = (array) $instance::SLUG_ATTRIBUTS; // ['name',"surname"]
        foreach ($slugAttributs as $slugAttribut) {
            $value .= " ".$model->{$slugAttribut} ?? "";
        }

        if (!empty($value)){
          //  $slug = $this->slug;
            $value =  Str::slug($value);

            $instance::withoutEvents(function () use($model,$value){
                $model->update(['slug' => $value]);
            });
            //if ($slug){
              //  $slug->update(['value' => $newVal]);
             //   $slug->update(['slug' => $newVal]);
          //  }else{
            //    $this->slug()->create(['value' => $newVal]);
           // }
        }
    }

    public function unslugify(){
        $slug = $this->slug;
        if ($slug){
          //  $slug->forceDelete();
        }
    }


}
