<?php

namespace Litecms\Currency\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Litecms\Currency\Events\CurrencyWorkflow as CurrencyWorkflowEvent;
use Litecms\Currency\Notifications\CurrencyWorkflow as CurrencyWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class CurrencyWorkflow
{
    use AsAction;

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

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

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

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

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

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