<?php
namespace App\Core;

final class WorkflowNotificationBus
{
    public static function fire(
        string $event,
        array $ctx=[]
    ): void {

        try{

            $notifier=
            new NotificationService();

            $mailer=
            new ConferenceMailer();

            $uid=
            (int)($ctx['user_id']??0);

            $conf=
            (int)($ctx['conference_id']??0);

            $sub=
            (int)($ctx['submission_id']??0);

            $title=
            trim((string)($ctx['title']??'Notification'));

            $body=
            trim((string)($ctx['body']??''));

            if(
                $uid>0
            ){
                $notifier->create([
                    'user_id'=>$uid,
                    'conference_id'=>$conf,
                    'submission_id'=>$sub,
                    'notification_type'=>$event,
                    'event_key'=>$event,
                    'title'=>$title,
                    'body'=>$body,
                    'link_url'=>$ctx['url']??null
                ]);
            }

            if(
                !empty($ctx['email'])
            ){
                $mailer->queueAndSend(
                    $conf,
                    $ctx['email'],
                    $title,
                    $body
                );
            }

            error_log(
                "NOTIFY OK ".$event
            );

        }catch(\Throwable $e){

            error_log(
                "NOTIFY FAIL ".
                $event.
                " ".
                $e->getMessage()
            );

        }
    }
}
