<?php

namespace Easymailing\App\Controller;

use Easymailing\App\Api\Client;
use Easymailing\App\Core\Container;
use Easymailing\App\Core\Http\Request;
use Easymailing\App\Core\Transient\FlashBag;
use Easymailing\App\Model\Config;
use Easymailing\App\Model\SynchronizationConfig;


class BaseController
{
	protected $container;

	public function setContainer(Container $container)
	{
		$this->container = $container;
	}

	public function getContainer(): Container
	{
		return $this->container;
	}

	public function getRequest(): Request
	{
		return $this->getContainer()->get('request');
	}


	public function render($template, $parameters = []): void
	{
		echo '<div class="easymailing-css">';
		echo $this->getContainer()->get('templating')->render($template, $parameters);
		echo '</div>';
		wp_die();
	}

	public function translate($msg): ?string
	{
		return __($msg, $this->getContainer()->get('parameter_bag')->get('plugin_slug'));
	}

	public function getParameter($name): ?string
	{
		$parameterBag = $this->getContainer()->get('parameter_bag');

		return $parameterBag->get($name);
	}

	public function forward($class, $method, $parameters = []): void
	{
		if (!$this->getContainer()->has($class)) {
			throw new \Exception(sprintf("Controller with class %s not found", $class));
		}

		$controller = $this->getContainer()->get($class);

		if (!method_exists($controller, $method)) {
			throw new \Exception(sprintf("Method %s does not exist in class %s", $method, $class));
		}

		// Usar reflexión para alinear parámetros con la firma del método
		$reflection = new \ReflectionMethod($controller, $method);
		$args = [];

		foreach ($reflection->getParameters() as $parameter) {
			$name = $parameter->getName();
			$args[] = $parameters[$name] ?? $parameter->getDefaultValue();
		}

		$reflection->invokeArgs($controller, $args);

		wp_die();
	}

	public function redirect($url): void
	{
		wp_redirect($url);
		wp_die();
	}

	public function redirectToMenuPage(string $menuSlug): void
	{
		$url = menu_page_url($menuSlug, false);
		$this->redirect($url);
	}

	public function addFlash($type, $message): void
	{
		$this->getContainer()->get('flashbag')->add($type, $message);
	}

	public function getConfig(): ?Config
	{
		return $this->getContainer()->get('config_repository')->getConfig();
	}

	public function getApiClient(): Client
	{
		return $this->getContainer()->get('api_client');
	}

	public function getFlashBag(): FlashBag
	{
		return $this->getContainer()->get('flashbag');
	}





}
