<?php

namespace MoneyTransfer\AuditLog\Listeners;

use MoneyTransfer\AuditLog\AuditLog;
use MoneyTransfer\AuditLog\Events\AuditHandlerEvent;
use App\Events\CreatedContentEvent;
use Exception;
use Illuminate\Support\Str;

class CreatedContentListener
{
    public function handle(CreatedContentEvent $event): void
    {
        try {
            if ($event->data->getKey()) {
                $model = $event->screen;

                if ($model === 'form') {
                    $model = strtolower(Str::afterLast(get_class($event->data), '\\'));
                }

                event(new AuditHandlerEvent(
                    $model,
                    'created',
                    $event->data->getKey(),
                    AuditLog::getReferenceName($model, $event->data),
                    'info'
                ));
            }
        } catch (Exception $exception) {
            logError($exception);
        }
    }
}
