MessagesRequests.php 1.54 KB
<?php

namespace App\Models;

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

class MessagesRequests extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'job_titles',
        'text',
        'is_rejected',
        'is_sent'
    ];

    public function getJobsAttribute()
    {
        $job_titles_ids = json_decode($this->attributes['job_titles'], true);
        return Job_title::whereIn('id', $job_titles_ids)->get();
    }

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

    public static function send_message($message_request_id)
    {
        $message_request = MessagesRequests::find($message_request_id);
        $job_ids = json_decode($message_request->job_titles);

        if (!empty($job_ids)){
            $title_workers = Title_worker::select('worker_id')
                ->with('worker')
                ->whereIN('job_title_id', $job_ids)
                ->groupBy('worker_id')
                ->get()
            ;



            if ($title_workers->count()){
                $message_params = [
                    'text' => $message_request->text
                ];
                foreach ($title_workers as $title_worker){
                    Message::add_message(null, $message_request->user_id, $title_worker->worker->user_id, $message_params, file_store_path : '/', is_admin_chat: true);
                }
            }
        }

        $message_request->update(['is_sent' => now()]);

        return true;
    }
}