<?php

namespace Inside\IBCA\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Inside\Content\Events\ContentUpdatedEvent;
use Inside\Notify\Listeners\BaseNotificationListener;
use Inside\Notify\Models\NotificationType;

/**
 * Content updated listener
 *
 * @category Class
 * @package  Inside\Notify\Listeners\ContentUpdatedListener
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class NewsletterUpdatedListener extends BaseNotificationListener implements ShouldQueue
{
    public function handle(ContentUpdatedEvent $event): void
    {
        $model = $event->model;

        /** @var Collection<NotificationType> $types */
        $types = NotificationType::where('model', get_class($model))->where(function ($query) {
            $query->where('action', 'newsletter');
        })->get();

        foreach ($types as $type) {
            if ($type->action === 'newsletter') {
                $sent = DB::table('inside_newsletters_sent')->where('uuid', $model->uuid)->first();

                if (!empty($sent)) {
                    return;
                }
            }

            $type->subscribers->each(function ($subscriber) use ($type, $model) {
                if ($subscriber->uuid === $model->author) {
                    return;
                }

                $this->when  = $this->getInterval($type, $model);
                $this->route = $subscriber;

                if (!$this->checkConditions($type, $model, $subscriber) || !$this->checkUniqueness($type, $model, $subscriber)) {
                    return;
                }



                DB::table('inside_newsletters_sent')->insert(['uuid' => $model->uuid]);
                $this->notify($type, $subscriber, $model, ['from' => $model->author]);
            });
        }
    }
}
