<?php

namespace Modules\Notice\Models;

use Illuminate\Support\Carbon;

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

use App\Notifications\NoticesMailerNotification;
use Modules\Notice\Models\Notice;
use Modules\Bot\Http\Controllers\BotNotificationSender;

use App\Models\User;

use Illuminate\Support\Facades\Log;


class NoticesMailer
{
    use Notifiable;

    private $user;
    private $notices;
    private $messages;

    public function __construct()
    {
        $date = Carbon::now();
        //$date->subDays(1);
        $date = $date->toDateTimeString();
        $latest_notice = Notice::where('created_at', '<=', $date)
            ->whereNull('sended_to_email_at')
            ->whereNull('read_at')
            ->orderBy('created_at', 'desc');
        if ($latest_notice = $latest_notice->first()) {
            $this->user = User::findOrFail($latest_notice->user_id);
            $this->notices = Notice::where('user_id', $this->user->id)
                ->whereNull('sended_to_email_at')
                ->whereNull('read_at')
                ->orderBy('object_name')
                ->orderBy('created_at')->get();
        };
        return;        
    }

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

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

          
        $notification = new NoticesMailerNotification($this->notices);

        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();
        };
    }
}
