<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\LiveChatConversations;

class LiveChatCustomers extends Model
{
    use HasFactory;

    protected $fillable = [
        'cust_unique_id',
        'username',
        'email',
        'chat_flow_messages',
        'engage_conversation',
        'file_upload_permission',
        'mobile_number',
        'country',
        'state',
        'mark_as_unread',
        'city',
        'full_address',
        'full_address',
        'timezone',
        'userType',
        'status',
        'verified',
        'login_at',
        'login_ip',
        'browser_info',
    ];

    protected $dates = ['login_at'];

    public function livechatconversation()
    {
        return $this->hasMany(LiveChatConversations::class, 'livechat_cust_id');
    }

    public function latestConversation()
    {
        return $this->hasOne(LiveChatConversations::class, 'livechat_cust_id')
            ->latest('created_at');
    }

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

        static::updating(function ($model) {
            if ($model['profileimage']) {
                unset($model['profileimage']);
            }
            if ($model['agentsNames']) {
                unset($model['agentsNames']);
            }
            if ($model['engage_conversation']) {
                json_encode($model['engage_conversation']);
            }
            return;
        });
        static::retrieved(function ($model) {
            $model->parseengage_conversation();
        });
    }

    // Define a method to set the "image" attribute
    protected function parseengage_conversation()
    {
        if ($this->engage_conversation && !is_array($this->engage_conversation)) {
            $this->engage_conversation = json_decode($this->engage_conversation, true);
            if (count($this->engage_conversation) > 2) {
                $namesArray = array_map(function ($item) {
                    return $item['firstname'] . ' ' . $item['lastname'];
                }, $this->engage_conversation);
                // Exclude the first two names
                $excludedNames = array_slice($namesArray, 2);
                $this->agentsNames = implode(', ', $excludedNames);
            }
        }

        if ($this->image) {
            $storage_disk = $this->storage_disk ?? 'public';
            $provider = existprovider($storage_disk)->provider;
            $imageUrl = $provider::getprofile($this->image);
            // Only set the "image" attribute if it's not already set
            if ($this['profileimage'] !== $imageUrl) {
                $this['profileimage'] = $imageUrl;
            }
        } else {
            $this['profileimage'] = asset('uploads/profile/user-profile.png');
        }
    }
}
