<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ChatMessage extends Model
{
    protected $fillable = [
        'sender_id', 'receiver_id', 'body', 'attachment', 'attachment_name', 'read_at',
    ];

    protected $casts = ['read_at' => 'datetime'];

    public function sender(): BelongsTo
    {
        return $this->belongsTo(User::class, 'sender_id');
    }

    public function receiver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'receiver_id');
    }

    /**
     * پیام‌های بین دو کاربر.
     */
    public function scopeBetween(Builder $q, int $a, int $b): Builder
    {
        return $q->where(function (Builder $w) use ($a, $b) {
            $w->where('sender_id', $a)->where('receiver_id', $b);
        })->orWhere(function (Builder $w) use ($a, $b) {
            $w->where('sender_id', $b)->where('receiver_id', $a);
        });
    }
}
