<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class DeviationType extends Model
{
    use SoftDeletes;

    protected $table = 'deviation_type';

    protected $fillable = [
        'name',
        'category',
        'approver_user_ids',
        'is_active',
        'created_by'
    ];

    protected $dates = ['deleted_at'];

    protected $appends = ['approver_names_string'];

    // Relationship: One deviation type can be used in many applications
    public function applicationDeviations()
    {
        return $this->hasMany(ApplicationDeviation::class, 'deviation_type_id');
    }

    public function getApproverNamesStringAttribute()
    {
        if (empty($this->approver_user_ids)) {
            return '';
        }

        $ids = is_string($this->approver_user_ids) 
            ? json_decode($this->approver_user_ids, true) 
            : $this->approver_user_ids;

        if (empty($ids) || !is_array($ids)) {
            return '';
        }

        // Fetch names of these users
        return \App\User::whereIn('id', $ids)->pluck('name')->implode(', ');
    }
}