<?php

namespace Bixo\CrossTrade\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\CrossTrade\Events\OrderVehicleWorkflow as OrderVehicleWorkflowEvent;
use Bixo\CrossTrade\Notifications\OrderVehicleWorkflow as OrderVehicleWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class OrderVehicleWorkflow
{
    use AsAction;

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

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

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

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

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

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