<?php

declare(strict_types=1);

namespace App\Module\Widget\Service;

use App\Entity\Tenant\WidgetPlacement;
use App\Entity\Tenant\WidgetZone;
use App\Module\Widget\Service\WidgetRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Twig\Environment;

class WidgetRenderer
{
    public function __construct(
        private readonly WidgetRegistry $widgetRegistry,
        private readonly Environment $twig,
    ) {}

    public function renderZone(string $zoneSlug, EntityManagerInterface $em): string
    {
        $zone = $em->getRepository(WidgetZone::class)->findOneBy([
            'slug' => $zoneSlug,
            'isActive' => true,
        ]);

        if (!$zone) {
            return '';
        }

        $placements = $em->getRepository(WidgetPlacement::class)->findBy(
            ['zone' => $zone, 'isActive' => true],
            ['position' => 'ASC']
        );

        $html = '';

        foreach ($placements as $placement) {
            $html .= $this->renderWidget($placement);
        }

        return $html;
    }

    public function renderWidget(WidgetPlacement $placement): string
    {
        $widgetType = $this->widgetRegistry->getWidgetType($placement->getWidgetType());

        if (!$widgetType) {
            return '';
        }

        $config = $placement->getConfig() ?? [];
        $data = $widgetType->getData($config);

        try {
            return $this->twig->render($widgetType->getTemplate(), [
                'placement' => $placement,
                'config' => $config,
                'data' => $data,
            ]);
        } catch (\Throwable $e) {
            return '';
        }
    }
}
