<?php

namespace Modules\Notice\Models;

use Illuminate\Support\Carbon;

use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Notification;

use App\Notifications\NewChatMessageNoticesMailerNotification;
use Modules\Notice\Models\Notice;
use Modules\Chat\Models\Chat;
use Modules\Chat\Models\ChatMessage;
use Modules\Chat\Models\ChatMessageRead;
use App\Models\User;
use Modules\Bot\Http\Controllers\BotNotificationSender;

class UnreadMessagesMailer
{
    use Notifiable;

    private $user;
    private $notices;
    private $senders;

    public function __construct()
    {
        $newChatNotice = Notice::whereNull('sended_to_email_at')
            ->whereNull('read_at')
            ->where('object_name', 'Chat')
            ->orderBy('created_at');
        if ($newChatNotice = $newChatNotice->first()) {
            $this->user = User::findOrFail($newChatNotice->user_id);
            $this->notices = Notice::where('user_id', $this->user->id)
                ->whereNull('sended_to_email_at')
                ->whereNull('read_at')
                ->where('object_name', 'Chat')
                ->orderBy('created_at')->get();
            //$this->senders = ChatMessageRead::where('receiver_id', $this->user->id)->where('message.sender_id');
        };
        return;        
    }


    public function run()
    {
        if (!$this->user) {
            //Log::error('Has no notices for mailing');
            return;
        }; 

        if ($this->notices->count() == 0) {
            return false;
        };

        $notification = new NewChatMessageNoticesMailerNotification();

        Notification::route('mail', $this->user->email)
            ->notify($notification);

        $botMessage = $notification->buildBotMessage();
        BotNotificationSender::routeMessage($this->user->id, $botMessage);
        
        foreach ($this->notices as $notice) {
            $notice->sended_to_email_at = now();
            $notice->save();
        };
    }
}
