<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/maps')]
final class MapsController extends AbstractController
{
    #[Route('', name: 'app_maps')]
    public function index(): Response
    {
        $mapsDir = $this->getParameter('kernel.project_dir') . '/public/uploads/maps';

        // Créer le répertoire s'il n'existe pas
        if (!is_dir($mapsDir)) {
            mkdir($mapsDir, 0755, true);
        }

        // Récupérer la liste des fichiers
        $files = [];
        if (is_dir($mapsDir)) {
            $scandir = scandir($mapsDir);
            foreach ($scandir as $file) {
                if ($file !== '.' && $file !== '..' && is_file($mapsDir . '/' . $file)) {
                    $filePath = $mapsDir . '/' . $file;
                    $files[] = [
                        'filename' => $file,
                        'display' => pathinfo($file, PATHINFO_FILENAME),
                        'size' => filesize($filePath)
                    ];
                }
            }
        }
        usort($files, fn($a, $b) => strcmp($a['filename'], $b['filename']));

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

    #[Route('/download/{filename}', name: 'app_maps_download')]
    public function download(string $filename): Response
    {
        $mapsDir = $this->getParameter('kernel.project_dir') . '/public/uploads/maps';
        $filePath = $mapsDir . '/' . $filename;

        // Vérifier que le fichier existe et est dans le bon répertoire
        if (!file_exists($filePath) || !is_file($filePath) || realpath($filePath) === false) {
            throw $this->createNotFoundException('Le fichier n\'existe pas.');
        }

        // Vérifier que le chemin réel est bien dans le répertoire uploads/maps
        if (strpos(realpath($filePath), realpath($mapsDir)) !== 0) {
            throw $this->createAccessDeniedException('Accès refusé.');
        }

        return $this->file($filePath);
    }
}
