<?php

namespace App\Models;

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

class SupportTicketReply extends Model
{
    use HasFactory;

    protected $table = 'support_ticket_replies';

    protected $fillable = [
        'support_ticket_id',
        'user_id',
        'worker_id',
        'message',
        'is_developer_response',
    ];

    public function ticket()
    {
        return $this->belongsTo(SupportTicket::class, 'support_ticket_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function worker()
    {
        return $this->belongsTo(Worker::class, 'worker_id');
    }

    /**
     * Get the sender name of the reply.
     */
    public function getSenderNameAttribute()
    {
        if ($this->user_id) {
            $user = $this->user;
            if ($user) {
                if ($user->role === 'admin') {
                    return $this->is_developer_response ? 'Senior Software Developer (AI Support)' : 'Support Admin';
                }
                return $user->name . ' (Employer)';
            }
        }
        if ($this->worker_id) {
            return ($this->worker->name ?? 'Worker') . ' (Worker)';
        }
        return 'System';
    }
}
