MessageObserver.php 1.9 KB
<?php

namespace App\Observers;

use App\Models\Chat;
use App\Models\Employer;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;

class MessageObserver
{
    public function created(Message $message): void
    {
        /** @var User $user */
        $user = User::find($message->to_user_id);

        if ($user === null || !$user->autoresponder) {
            return;
        }

        $recentAutoresponderMessage = Message::query()
            ->where('user_id', $message->to_user_id)
            ->where('to_user_id', $message->user_id)
            ->where('text', $user->autoresponder_message)
            ->where('created_at', '>', now()->subDays(4))
            ->orderBy('id', 'desc')
            ->first();

        if ($recentAutoresponderMessage !== null) {
            return;
        }

        Message::add_message(
            request: new Request(),
            user_id: $message->to_user_id,
            to_user_id: $message->user_id,
            message_params: [
                'text' => $user->autoresponder_message,
                'flag_new' => 1
            ]
        );
    }

    /**
     * Handle the Message "updated" event.
     *
     * @param  \App\Models\Message  $message
     * @return void
     */
    public function updated(Message $message)
    {
        //
    }

    /**
     * Handle the Message "deleted" event.
     *
     * @param  \App\Models\Message  $message
     * @return void
     */
    public function deleted(Message $message)
    {
        //
    }

    /**
     * Handle the Message "restored" event.
     *
     * @param  \App\Models\Message  $message
     * @return void
     */
    public function restored(Message $message)
    {
        //
    }

    /**
     * Handle the Message "force deleted" event.
     *
     * @param  \App\Models\Message  $message
     * @return void
     */
    public function forceDeleted(Message $message)
    {
        //
    }
}