<?php

namespace App\Models\SM;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Fnction extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'code', 'desc', 'app_code', 'created_by', 'status'];
    protected $casts = [
        'created_at' => 'date:d/m/Y'
    ];

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, FnctionPermission::class, 'fnction_id', 'permission_id')->withPivot('id');
    }

    protected function code(): Attribute
    {
        return Attribute::make(
            get:fn(string $value) => strtoupper($value),
            set:fn(string $value) => strtoupper($value)
        );
    }

    public static function boot()
    {
        Parent::boot();
        static::creating(function ($model) {
            $model->created_by = auth()->id();
        });
    }
}
