<?php

namespace Edulab\Standard\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Edulab\Standard\Events\TimetableWorkflow as TimetableWorkflowEvent;
use Edulab\Standard\Notifications\TimetableWorkflow as TimetableWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class TimetableWorkflow
{
    use AsAction;

    private $allowedTransitions = [
        'before' => [],
        'after' => ['publish', 'submit', 'approve'],
    ];

    public function handle(TimetableWorkflowEvent $event)
    {
        $function = Str::camel($event->transition);
        return $this->$function($event);
    }

    /**
     * Sends a notification to the client when the $timetable is submitted.
     *
     * @param TimetableWorkflowEvent $event The event object.
     * @return void
     */
    public function submit(TimetableWorkflowEvent $event)
    {
        $client = $event->timetable->client;
        Notification::send($client, new TimetableWorkflowNotification($event));
    }

    /**
     * Sends a notification to the client when the $timetable is published.
     *
     * @param TimetableWorkflowEvent $event The event object.
     * @return void
     */
    public function publish(TimetableWorkflowEvent $event)
    {
        $client = $event->timetable->client;
        Notification::send($client, new TimetableWorkflowNotification($event));
    }

    /**
     * Sends a notification to the client when the $timetable is approved.
     *
     * @param TimetableWorkflowEvent $event The event object.
     * @return void
     */
    public function approve(TimetableWorkflowEvent $event)
    {
        $client = $event->timetable->client;
        Notification::send($client, new TimetableWorkflowNotification($event));
    }

    /**
     * Handles the $timetable workflow event as a listener.
     *
     * @param TimetableWorkflowEvent $event The event object.
     * @return void
     */
    public function asListener(TimetableWorkflowEvent $event)
    {
        if (($event->when == 'before' &&
            in_array($event->transition, $this->allowedTransitions['before']) ||
            $event->when == 'after' &&
            in_array($event->transition, $this->allowedTransitions['after']))
        ) {
            return $this->handle($event);
        }
    }
}