<?php

namespace App\Controller;

use App\Entity\ScanSession;
use App\Entity\User;
use App\Repository\ScanSessionRepository;
use App\Security\Voter\ScanVoter;
use App\Service\ConcessionsProvider;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_USER')]
final class PageController extends AbstractController
{
    #[Route('/', name: 'app_home', methods: ['GET'])]
    public function home(ScanSessionRepository $repo, ConcessionsProvider $provider): Response
    {
        /** @var User $user */
        $user = $this->getUser();
        $scope = $user->scopeConcessions();
        $year = (int) date('Y');

        $stats = $repo->statsForScope($scope, $year);
        $byStatus = $repo->countByStatusForScope($scope, $year);
        $byMonth = $repo->countByMonthForScope($scope, $year);
        $byMonthStatus = $repo->countByMonthAndStatusForScope($scope, $year);

        // Concessions stockées par ID → résolues en nom pour le graphe.
        $topConcessions = [];
        foreach ($repo->topConcessionsForScope($scope, $year, 8) as $id => $n) {
            $label = $provider->label((string) $id);
            $topConcessions[$label] = ($topConcessions[$label] ?? 0) + $n;
        }
        $recent = $repo->findRecentForScope($scope, 5);

        return $this->render('page/home.html.twig', [
            'year' => $year,
            'stats' => $stats,
            'byStatus' => $byStatus,
            'byMonth' => array_values($byMonth),
            'byMonthStatus' => array_map('array_values', $byMonthStatus),
            'topConcessions' => $topConcessions,
            'monthsLabels' => ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'],
            'recent' => array_map(static fn (ScanSession $s) => [
                'id' => $s->getId(),
                'createdAt' => $s->getCreatedAt(),
                'label' => $s->getLabel(),
                'count' => $s->getCount(),
                'status' => $s->getStatus(),
                'locationNote' => $s->getLocationNote(),
                'userEmail' => $s->getUserEmail(),
                'concessions' => $s->getConcessions(),
            ], $recent),
        ]);
    }

    // Réservé aux groupes qui peuvent créer un scan (LECTEUR exclu).
    #[IsGranted('SCAN_CREATE')]
    #[Route('/scan', name: 'app_scan', methods: ['GET'])]
    public function scan(ConcessionsProvider $provider, \App\Service\S3Settings $s3): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        // La liste proposée au scan = uniquement les concessions du profil de l'utilisateur
        // (paramètre du compte), pour tous les groupes. Map id => nom (le picker affiche le
        // nom, la valeur envoyée est l'ID).
        $concessions = $provider->labels($user->getConcessions());

        return $this->render('page/scan.html.twig', [
            'concessions' => $concessions,
            'selectedConcessions' => $user->getConcessions(),
            // True → le navigateur téléverse les photos directement sur S3 pendant le scan.
            's3Storage' => $s3->isStorageEnabled(),
        ]);
    }

    #[Route('/historique', name: 'app_history', methods: ['GET'])]
    public function history(ScanSessionRepository $repo): Response
    {
        /** @var User $user */
        $user = $this->getUser();
        // Historique = jeu de travail personnel (scans créés par l'utilisateur).
        $sessions = $repo->findRecentByEmail($user->getUserIdentifier(), 100);

        return $this->render('page/history.html.twig', [
            'sessions' => array_map(fn (ScanSession $s) => [
                'id' => $s->getId(),
                'createdAt' => $s->getCreatedAt(),
                'label' => $s->getLabel(),
                'count' => $s->getCount(),
                'totalFiles' => $s->getTotalFiles(),
                'status' => $s->getStatus(),
                'locationNote' => $s->getLocationNote(),
                // Permissions par session pour afficher les bons boutons de statut.
                'canSubmit' => $this->isGranted(ScanVoter::SUBMIT, $s),
                'canChangeStatus' => $this->isGranted(ScanVoter::CHANGE_STATUS, $s),
                'canDelete' => $this->isGranted(ScanVoter::DELETE, $s),
            ], $sessions),
        ]);
    }

    #[Route('/concessions', name: 'app_concessions_page', methods: ['GET'])]
    public function concessions(ConcessionsProvider $provider): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        return $this->render('page/concessions.html.twig', [
            'concessions' => $provider->all(),
            'selectedConcessions' => $user->getConcessions(),
        ]);
    }

    #[Route('/aide', name: 'app_help', methods: ['GET'])]
    public function help(): Response
    {
        return $this->render('page/aide.html.twig', [
            'helpEmail' => 'eric.masse@emilfrey.fr',
        ]);
    }
}
