<?php

namespace Crm\Advertisement\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Crm\Advertisement\Events\AdvertisementWorkflow as AdvertisementWorkflowEvent;
use Crm\Advertisement\Notifications\AdvertisementWorkflow as AdvertisementWorkflowNotification;
use Litepie\Actions\Concerns\AsAction;

class AdvertisementWorkflow
{
    use AsAction;

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

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

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

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

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

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