<?php

namespace App\Models;

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

class AgentConversation extends Model
{
    use HasFactory;

    protected $table = 'agent_conversations';

    protected $fillable  = [
        'unique_id',
        'sender_user_id',
        'receiver_user_id',
        'message',
        'message_type',
        "mark_as_unread",
        "delete_status",
    ];

    
    protected static function booted()
    {
        // Use retrieved event to automatically set the "image" attribute when loading an existing model

        static::updating(function ($model) {
            if ($model['agentsNames']) {
                unset($model['agentsNames']);
            }
            if ($model['receiver_user_id']) {
                json_encode($model['receiver_user_id']);
            }
            if ($model['mark_as_unread']) {
                json_encode($model['mark_as_unread']);
            }
            return;
        });
        static::retrieved(function ($model) {
            $model->parsereceiver_user_id();
        });
    }

    // Define a method to set the "image" attribute
    protected function parsereceiver_user_id()
    {
        if ($this->mark_as_unread && !is_array($this->mark_as_unread)) {
            $this->mark_as_unread = json_decode($this->mark_as_unread, true);
        }
        if ($this->receiver_user_id && !is_array($this->receiver_user_id)) {
            $this->receiver_user_id = json_decode($this->receiver_user_id, true);
            if (is_array($this->receiver_user_id) && count($this->receiver_user_id) > 2) {
                $namesArray = array_map(function ($item) {
                    return User::find($item)->name;
                }, $this->receiver_user_id);
                // Exclude the first two names
                $excludedNames = array_slice($namesArray, 2);
                $this->agentsNames = implode(', ', $excludedNames);
            }
        }
    }
}
