<?php

namespace Bixo\Account\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Account\Events\InvoiceDetailWorkflow as InvoiceDetailWorkflowEvent;
use Bixo\Account\Notifications\InvoiceDetailWorkflow as InvoiceDetailWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class InvoiceDetailWorkflow
{
    use AsAction;

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

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

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

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

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

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