﻿<?php

namespace App\Models;

use App\Traits\Scopes\ScopeActive;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Scopes\OrganisationScope;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

/**
 * Attribute
 */
class Attribute extends Model
{
    use HasFactory, ScopeActive;

    /**
     * fillable
     *
     * @var array
     */
    protected $fillable = [
        'organisation_id',
        'name',
        'status',
        'created_by',
        'updated_by'
    ];

    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('Attribute')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => "{$this->name} Attributes has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }
    protected static function booted()
    {
        static::addGlobalScope(new OrganisationScope);

        // Automatically set the organisation_id before creating the model
        static::creating(function ($model) {
            if (auth()->check()) {
                $model->organisation_id = auth()->user()->organisation_id;
            }
        });
    }

    // CONST
    public const STATUS_ACTIVE = 'active';
    public const STATUS_INACTIVE = 'inactive';

    /**
     * items
     *
     * @return void
     */
    public function items()
    {
        return $this->hasMany(AttributeItem::class, 'attribute_id');
    }