<?php

# src/Twig/Base64Extension.php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class Base64Extension extends AbstractExtension
{
    public function __construct(private ParameterBagInterface $params)
    {
        
    }
    
    public function getFilters(): array
    {
        return [
            new TwigFilter('base64img', [$this, 'convertToBase64']),
        ];
    }

    public function convertToBase64(string $path): string
    {
        $absolutePath = $this->params->get('upload_images_directory') . $path;

        if (!file_exists($absolutePath)) {
            dump($absolutePath);
            return '';
        }

        // convert WebP → JPEG avant d'encoder
        $info = pathinfo($absolutePath);
        $ext = strtolower($info['extension']);

        if ($ext === 'webp') {
            $image = imagecreatefromwebp($absolutePath);
            ob_start();
            imagejpeg($image, null, 85); // qualité 85%
            $jpegData = ob_get_clean();
            imagedestroy($image);
            $data = $jpegData;
            $mime = 'image/jpeg';
        } else {
            $data = file_get_contents($absolutePath);
            $mime = mime_content_type($absolutePath);
        }

        return 'data:' . $mime . ';base64,' . base64_encode($data);
    }
}