<?php
// app/Models/AttachmentType.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AttachmentType extends Model
{
    use HasFactory;

    protected $table = 'attachment_types';

    protected $fillable = [
        'name',
        'description',
        'created_by',
        'updated_by',
        'active'
    ];

    protected $casts = [
        'active' => 'boolean',
    ];

    /**
     * Get the attachments of this type
     */
    public function attachments(): HasMany
    {
        return $this->hasMany(FileAttachment::class, 'attachment_type_id');
    }

    /**
     * Get the user who created this type
     */
    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who last updated this type
     */
    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Get the count of attachments of this type
     */
    public function getAttachmentsCountAttribute(): int
    {
        return $this->attachments()->count();
    }

    /**
     * Scope a query to only include active types
     */
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    /**
     * Scope a query to order by name
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('name');
    }
}