<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Uom extends Model
{
    use LogsActivity;

    protected $table = 'uoms';

    protected $fillable = [
        'code',
        'name',
        'factor_to_base',
        'is_active',
    ];

    protected $casts = [
        'factor_to_base' => 'decimal:6',
        'is_active' => 'boolean',
    ];

    // Relationships
    public function items(): HasMany
    {
        return $this->hasMany(Item::class);
    }

    public function purchaseRequestItems(): HasMany
    {
        return $this->hasMany(PurchaseRequestItem::class);
    }

    public function purchaseOrderItems(): HasMany
    {
        return $this->hasMany(PurchaseOrderItem::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByCode($query, $code)
    {
        return $query->where('code', $code);
    }

    // Helper methods
    public function getFormattedFactorAttribute()
    {
        return number_format($this->factor_to_base, 6);
    }

    public function getStatusBadgeAttribute()
    {
        $class = $this->is_active ? 'success' : 'danger';
        $label = $this->is_active ? 'Active' : 'Inactive';
        return '<span class="badge bg-' . $class . '">' . $label . '</span>';
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('uom')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
