<?php

namespace Edulab\College\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Edulab\College\Events\TeacherWorkflow as TeacherWorkflowEvent;
use Edulab\College\Notifications\TeacherWorkflow as TeacherWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class TeacherWorkflow
{
    use AsAction;

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

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

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

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

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

    /**
     * Handles the $teacher workflow event as a listener.
     *
     * @param TeacherWorkflowEvent $event The event object.
     * @return void
     */
    public function asListener(TeacherWorkflowEvent $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);
        }
    }
}