<?php

namespace App\Models;

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

class SafetyDataSheet extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'image',
        'title',
        'customer_id',
        'workspace_id',
        'created_by',
        'date',
        'revision_date',
        'expiry_date',
        'del',
    ];

    // Auto-append the name to model JSON/array output
    protected $appends = ['creator_name'];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

    public function customer()
    {
        return $this->belongsTo(User::class, 'customer_id', 'id')->select('id','name');
    }

    public function employee()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'created_by', 'emp_id')
            ->selectRaw('emp_id, first_name, middle_name, last_name, TRIM(CONCAT(COALESCE(first_name,""), " ", COALESCE(middle_name,""), " ", COALESCE(last_name,""))) as name');
    }

    // 👇 Custom accessor to dynamically return the name
    public function getCreatorNameAttribute()
    {
        // If created_by matches the customer account, use the customer's name
        if (!empty($this->customer_id) && (int) $this->customer_id === (int) $this->created_by) {
            if ($this->relationLoaded('customer') && $this->customer) {
                return $this->customer->name;
            }

            return optional($this->customer()->select('name')->first())->name ?? 'N/A';
        }

        // Otherwise, fall back to the employee details (first + middle + last)
        if ($this->relationLoaded('employee') && $this->employee) {
            return trim(collect([
                $this->employee->first_name,
                $this->employee->middle_name,
                $this->employee->last_name,
            ])->filter()->implode(' '));
        }

        $employee = $this->employee()
            ->select('first_name', 'middle_name', 'last_name')
            ->first();

        if ($employee) {
            return trim(collect([
                $employee->first_name,
                $employee->middle_name,
                $employee->last_name,
            ])->filter()->implode(' '));
        }

        return 'N/A';
    }
}
