<?php

namespace App\Controller;

use App\Entity\Image;
use App\Service\ImageService;
use Doctrine\ORM\EntityManagerInterface;
use Dom\Entity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class ImageController extends AbstractController
{
    private EntityManagerInterface $entityManager;
    private ImageService $imageService;

    public function __construct(EntityManagerInterface $entityManager, ImageService $imageService)
    {
        $this->entityManager = $entityManager;
        $this->imageService = $imageService;
    }
    #[Route('/admin/image', name: 'admin_image_index')]
    public function index(): Response
    {
        $images = $this->entityManager->getRepository(Image::class)->findAll();

        return $this->render('image/index.html.twig', [
            'images' => $images,
        ]);
    }

    #[Route('/admin/image/add', name: 'admin_image_add')]
    public function add(): Response
    {
        return $this->render('image/add.html.twig');
    }

    #[Route('/admin/image/upload', name: 'admin_image_upload', methods: ['POST'])]
    public function upload(Request $request): JsonResponse
    {
        $files = $request->files->get('file-upload', []);

        foreach ($files as $file) {
            if ($file && $file->isValid()) {
                $originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                $extension = $file->getClientOriginalExtension();

                $filename = strtolower($originalName . '-' . uniqid() . '.' . $extension);
                $stream = fopen($file->getPathname(), 'rb');

                // Upload vers MinIO
                $result = $this->imageService->upload($filename, $stream);

                if ($result === true) {
                    $image = new Image();
                    $image->setName($filename);
                    $image->setUrl($this->getParameter('minio_endpoint') . '/' . $this->getParameter('minio_bucket') . '/' . $filename);
                    $image->setSize($file->getSize());
                    $this->entityManager->persist($image);
                }
            }
        }
        $this->entityManager->flush();

        return new JsonResponse([
            'success' => true,
        ]);
    }

    #[Route('/admin/image/delete/{id}', name: 'admin_image_delete', methods: ['GET', 'POST'])]
    public function delete(Request $request, Image $image, EntityManagerInterface $em): Response
    {
        $submittedToken = $request->request->get('_token');
        if ($this->isCsrfTokenValid('delete_image' . $image->getId(), $submittedToken)) {
            $result = $this->imageService->delete($image);
            if ($result === true) {
                $em->remove($image);
                $em->flush();
            } else {
                $this->addFlash('error', 'L\'image est utilisée et ne peut pas être supprimée.');
            }
        }

        return $this->redirectToRoute('admin_image_index');
    }
}
