<?php
class EventDispatcher {
    private $subscribers = [];
    private $config;
    private $db;

    public function __construct($config, $db) {
        $this->config = $config;
        $this->db = $db;
    }

    /**
     * @throws Exception
     */
    public function subscribe($event, $subscriberClass, $method = 'handle', $priority = 0): void
    {
        if (!class_exists($subscriberClass)) {
            throw new Exception("Subscriber class $subscriberClass does not exist");
        }

        $subscriber = new $subscriberClass($this->config, $this->db);

        if (!method_exists($subscriber, $method)) {
            throw new Exception("Method $method does not exist in class $subscriberClass");
        }

        $this->subscribers[$event][$priority][] = [$subscriber, $method];
       // krsort($this->subscribers[$event]);
    }

    public function dispatch($event, $data = null, $meta = []) {
        if (!isset($this->subscribers[$event])) return [];

        $meta = array_merge($meta, ["config" => $this->config, "db" => $this->db]);
        $results = [];

        foreach ($this->subscribers[$event] as $priority => $callbacks) {
            foreach ($callbacks as $callback) {
                $results = call_user_func($callback, $data, $meta);
            }
        }

        return $results;
    }
}
