<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    use \App\Models\Concerns\BelongsToHotel;

    protected $guarded = [];

    public function thread()
    {
        return $this->belongsTo(MessageThread::class, 'message_thread_id');
    }

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

    public function senderCustomer()
    {
        return $this->belongsTo(Customer::class, 'sender_customer_id');
    }

    public function displayName(): string
    {
        return $this->sender_name
            ?: ($this->senderUser?->name
                ?: ($this->senderCustomer?->name ?: 'Guest'));
    }

    public function isFromStaff(): bool
    {
        return ! is_null($this->sender_user_id);
    }

    public function initials(): string
    {
        $parts = preg_split('/\s+/', trim($this->displayName()));

        return strtoupper(substr($parts[0] ?? 'U', 0, 1) . substr($parts[1] ?? '', 0, 1));
    }
}
