<?php

namespace App\Entities\Chat;

use App\Entities\Usuarios\UserEntity;
use App\Models\Chat\ChatModel;
use App\Models\ChatNotification;
use App\Models\Usuarios\UserModel;
use CodeIgniter\Entity\Entity;
use CodeIgniter\I18n\Time;

class ChatMessageEntity extends Entity
{
    protected $attributes = [
        "id" => null,
        "message" => null,
        "chat_id" => null,
        "sender_id" => null,
        "receiver_id" => null,
        "viewed" => null,
    ];


    protected $casts = [
        "message" => "string",
        "chat_id" => "integer",
        "sender_id" => "?integer",
        "receiver_id" => "?integer",
        "viewed" => "boolean",
    ];
    protected $dates   = [];

    public function chat() : ?ChatEntity
    {
        $m = model(ChatModel::class);
        return $m->find($this->attributes['chat_id']);

    }
    /**
     * Notifications related with this chat entity.
     *
     * @return array<ChatNotificationEntity>
     */
    public function notifications() : array
    { 
        $m = model(ChatNotification::class);
        return $m->asArray()->where('chat_id',$this->attributes['chat_id'])->findAll() ?? [];
    }
    public function sentBy() : ?UserEntity 
    {
        $m = model(UserModel::class);
        return $m->find($this->attributes["sender_id"])->withAvatar();
        
    }
    public function withUser() : self 
    {
        $this->attributes["user"] = $this->sentBy();
        return $this;
    }
    public function getCreatedAt()
    {
        return Time::createFromFormat("Y-m-d H:i:s",$this->attributes['created_at'])->format('d/m/Y H:i');
            
    }
}
