<?php

namespace Sitecake\Event;

/**
 * Trait EventDispatcherTrait — replaces Cake\Event\EventDispatcherTrait.
 *
 * Provides per-instance EventManager support, falling back to the global singleton.
 */
trait EventDispatcherTrait
{
    /** @var EventManager|null Per-instance event manager */
    protected ?EventManager $_localEventManager = null;

    public function getEventManager(): EventManager
    {
        return $this->_localEventManager ?? EventManager::instance();
    }

    public function setEventManager(EventManager $eventManager): self
    {
        $this->_localEventManager = $eventManager;
        return $this;
    }

    /**
     * Dispatch an event on the local event manager.
     *
     * @param string     $name    Event name
     * @param array|null $data    Event data payload
     * @param mixed|null $subject Subject (defaults to $this)
     */
    public function dispatchEvent(string $name, $data = null, $subject = null): Event
    {
        return $this->getEventManager()->dispatch(
            $name,
            (array)($data ?? []),
            $subject ?? $this
        );
    }
}
