<?php


namespace App\Models\Traits;

use App\Models\SettingManagement\Status;

trait HasStatuses{

    /** retourne les status utilisables sur un model
     * @return mixed
     */
    public static function statuses(){
        return Status::where("model",(new static)->getMorphClass())->get();
    }

    public function status(){
        return $this->belongsTo(Status::class,Status::FK_ID);
    }

    public function statuffy($event = "created"){
        $statusColumn = Status::FK_ID; // "status_code"
        $datas = [$statusColumn => $this->{$statusColumn} ];
        $datas["created_at"] = now();
        $datas["created_by"] =  auth(activeGuard())->id() ?? null;

        //si c'est un update
        if ($event == "updated"){
            $changes = $this->changes ?? [] ;

            if ($changes){
                //si le statut a été modifié
                if (isset($changes[$statusColumn])){
                    $this->statusChanges()->create($datas);
                }
            }
        }else{
            $this->statusChanges()->create($datas);
        }
    }

    public function setStatusTo($id){
        return $this->update([Status::FK_ID => $id]);
    }


    public function isActive(){
        return ($this->{Status::FK_ID} == Status::ACTIVE);
    }
    public function getisActiveAttribute(){
        return $this->isActive();
    }
}
