<?php

namespace App\Controller;

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

/**
 * Liste filtrable des inventaires de l'utilisateur (recherche plaque/VIN/concession + filtres statut/créateur).
 */
#[IsGranted('ROLE_USER')]
final class InventairesController extends AbstractController
{
    private const PER_PAGE = 25;

    #[Route('/inventaires', name: 'app_inventaires', methods: ['GET'])]
    public function index(Request $request, ScanSessionRepository $repo, ConcessionsProvider $concessions): Response
    {
        /** @var User $user */
        $user = $this->getUser();
        $scope = $user->scopeConcessions();

        $q = trim((string) $request->query->get('q', ''));
        $status = $request->query->get('status');
        $status = \is_string($status) && \in_array($status, ScanSession::ALL_STATUSES, true) ? $status : null;
        $concession = trim((string) $request->query->get('concession', '')) ?: null;
        $creator = trim((string) $request->query->get('creator', '')) ?: null;
        $archived = (string) $request->query->get('archived', 'active');
        $archived = \in_array($archived, ['active', 'archived', 'all'], true) ? $archived : 'active';
        $page = max(1, (int) $request->query->get('page', 1));

        $result = $repo->search($scope, $q ?: null, $status, $concession, $page, self::PER_PAGE, $archived, $creator);
        $sessions = $result['items'];
        $total = $result['total'];
        $totalPages = max(1, (int) ceil($total / self::PER_PAGE));

        // Concessions proposées au filtre (map id => nom) : limitées au périmètre pour les rôles restreints.
        $filterConcessions = null === $scope ? $concessions->all() : $concessions->labels($scope);

        return $this->render('page/inventaires.html.twig', [
            'sessions' => $sessions,
            'total' => $total,
            'page' => $page,
            'totalPages' => $totalPages,
            'q' => $q,
            'currentStatus' => $status,
            'currentConcession' => $concession,
            'currentCreator' => $creator,
            'currentArchived' => $archived,
            'allStatuses' => ScanSession::ALL_STATUSES,
            'statusLabels' => [
                ScanSession::STATUS_EN_COURS => 'En cours',
                ScanSession::STATUS_A_VALIDER => 'À valider',
                ScanSession::STATUS_VALIDE => 'Validés',
                ScanSession::STATUS_ANNULE => 'Annulés',
            ],
            'allConcessions' => $filterConcessions,
            'allCreators' => $repo->distinctCreatorsForScope($scope),
        ]);
    }
}
