<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Repository\EmployeeRepository;
use App\Service\Leave\LeaveRecapRowBuilder;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Dompdf\Options;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;

class LeaveRecapPrintProvider implements ProviderInterface
{
    public function __construct(
        private Environment $twig,
        private EmployeeRepository $employeeRepository,
        private LeaveRecapRowBuilder $rowBuilder,
        private EntityManagerInterface $entityManager,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
    {
        $today     = new DateTimeImmutable('today');
        $employees = $this->employeeRepository->findForPrintBySiteIds([]);

        $siteGroups = [];

        foreach ($employees as $employee) {
            if (!$employee->getHasActiveContract()) {
                continue;
            }

            $site   = $employee->getSite();
            $siteId = $site ? $site->getId() : 0;

            if (!isset($siteGroups[$siteId])) {
                $siteGroups[$siteId] = [
                    'name'      => $site ? $site->getName() : 'Sans site',
                    'color'     => $site?->getColor() ?? '#ffd7d7',
                    'employees' => [],
                ];
            }

            $siteGroups[$siteId]['employees'][] = $this->rowBuilder->build($employee);
            $this->entityManager->clear();
        }

        // Re-load Twig environment after clear
        $options = new Options();
        $options->set('isRemoteEnabled', true);

        $dompdf = new Dompdf($options);
        $html   = $this->twig->render('leave-recap/print.html.twig', [
            'today'      => $today,
            'siteGroups' => $siteGroups,
        ]);

        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $filename = sprintf('recap_conges_%s.pdf', $today->format('Y-m-d'));

        return new Response($dompdf->output(), Response::HTTP_OK, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => 'inline; filename="'.$filename.'"',
        ]);
    }
}
