<?php

namespace Crm\Category\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Crm\Category\Events\CategoryWorkflow as CategoryWorkflowEvent;
use Crm\Category\Notifications\CategoryWorkflow as CategoryWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class CategoryWorkflow
{
    use AsAction;

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

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

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

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

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

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