<?php

namespace Inside\DESK\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Inside\Content\Models\Contents\Alerts;
use Inside\Content\Models\Contents\Users;
use Inside\DESK\Mail\Alert;
use Inside\DESK\Models\AlertStatistic;

/**
 * Class PublishContent
 *
 * @category Class
 * @package  Inside\DESK\Jobs\SendAlertMail
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class SendAlert implements ShouldQueue
{
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var Users
     */
    protected $user;

    /**
     * @var Alerts
     */
    protected $content;

    /**
     * PublishContent constructor.
     *
     * @param Users $user
     * @param Alerts $content
     */
    public function __construct(Users $user, Alerts $content)
    {
        $this->user = $user;
        $this->content = $content;
    }

    /**
     *
     */
    public function handle(): void
    {
        if (DB::table('desk_alerts_sent')->where('uuid', $this->content->uuid)->where('user_uuid', $this->user->uuid)->exists()) {
            return;
        }

        Mail::to($this->user->email)->send(new Alert($this->content, $this->user->uuid, $this->user->langcode));

        DB::table('desk_alerts_sent')->insert([
            'uuid' => $this->content->uuid,
            'user_uuid' => $this->user->uuid,
        ]);

        AlertStatistic::firstOrCreate([
            'alert_uuid' => $this->content->uuid,
            'user_uuid' => $this->user->uuid,
            'statistic_type' => 'sent'
        ]);
    }
}
