<?php

namespace App\Controller\Admin\Quittances;

use App\Entity\Security\User;
use App\Entity\Acteurs\Locataires;
use App\Managers\ManagersInterface;
use App\Entity\Parametres\Parametres;
use App\Entity\Quittances\Quittances;
use App\Entity\Parametres\Etats\Etats;
use App\Form\Quittances\QuittancesType;
use Doctrine\ORM\EntityManagerInterface;
use App\Interfaces\NotificationsInterface;
use Doctrine\ORM\NonUniqueResultException;
use App\Entity\Quittances\SearchQuittances;
use App\Form\Quittances\SearchQuittancesType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\Acteurs\LocatairesRepository;
use App\Repository\Parametres\ParametresRepository;
use App\Repository\Quittances\QuittancesRepository;
use App\Repository\Parametres\Etats\EtatsRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security as Security;

#[Route('/admin/quittances/loyers')]
#[Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_ADMIN')")]
class AdminQuittancesController extends AbstractController
{
    public function __construct(
        private NotificationsInterface $notifications,
        private ParametresRepository $parametresRepository,
        private EtatsRepository $etatsRepository,
        private LocatairesRepository $locatairesRepository,
        private QuittancesRepository $repository,
        private ManagersInterface $managers,
        private readonly EntityManagerInterface $entityManager,
    ) {}

    /**
     * @throws NonUniqueResultException
     */
    #[Route('/', name: 'admin.quittances.index')]
    // public function index(Request $request, ContainerInterface $container): Response
    // {
    //     $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

    //     /** @var User $user */
    //     $user = $this->getUser();

    //     $quittance = new Quittances($user);
    //     $form = $this->createForm(QuittancesType::class, $quittance, ['quittance' => $quittance]);
    //     $form->handleRequest($request);
    //     $referer = $request->headers->get('referer');

    //     if ($form->isSubmitted() && $form->isValid()) {
    //         $locataire = $this->locatairesRepository->find(intval($request->request->all('quittances')['locataires']));
    //         if ($this->checkQuittance($quittance) === true) {
    //             $this->addFlash('danger', 'Quittance déjà ajoutée.');
    //             return new RedirectResponse($referer ?? $this->generateUrl('admin.quittances.index'));
    //         }

    //         /** @var Parametres $app */
    //         $app = $this->parametresRepository->find($container->getParameter('company_id'));

    //         /** @var Etats $etat */
    //         // $etat = $this->etatsRepository->find($app->getAppEtatPayer());
    //         // dd($etat);

    //         // // Assure-toi que $etat existe en base
    //         // if ($etat) {
    //         //     $quittance->setEtats($etat);
    //         //     $quittance->setIsPayer($quittance->getEtats() === $etat);
    //         // }

    //         $etat = $this->etatsRepository->find($app->getAppEtatPayer());
    //         if (!$etat) {
    //             throw new \LogicException("Etat par défaut introuvable !");
    //         }
    //         $quittance->setEtats($etat);



    //         // if ($quittance->getEtats() === $etat) {
    //         //     $quittance->setIsPayer(true);
    //         // } else {
    //         //     $quittance->setIsPayer(false);
    //         // }
    //         $quittance->setLocataires($locataire);
    //         $quittance->setCompanyId($user->getCompanyId());
    //         // $this->managers->setEntity($quittance, 'new');
    //         $em = $this->getDoctrine()->getManager(); // ou $this->em si injecté
    //         $em->persist($quittance);
    //         $em->flush();

    //         $this->notifications->save(
    //             "Nouvelle quittance #{$quittance->getCode()}",
    //             "Création",
    //             $quittance,
    //             "plus",
    //             "green"
    //         );

    //         $this->addFlash('success', 'Quittance ajoutée avec succès.');
    //         return new RedirectResponse($referer ?? $this->generateUrl('admin.quittances.index'));
    //     }

    //     $search = new SearchQuittances();
    //     $form_quittance = $this->createForm(SearchQuittancesType::class, $search);
    //     $form_quittance->handleRequest($request);
    //     $quittances = $this->repository->getQuittances($search);

    //     if ($form_quittance->isSubmitted() && $form_quittance->isValid()) {
    //         $quittances = $this->repository->getQuittances($search);
    //     }

    //     return $this->render('admin/quittances/index.html.twig', [
    //         'title' => 'Quittances des loyers',
    //         'quittance' => $quittance,
    //         'search' => $search,
    //         'quittances' => $quittances,
    //         'form' => $form->createView(),
    //         'form_quittance' => $form_quittance->createView(),
    //         'current_page' => 'quittances',
    //         'current_global' => 'quittances',
    //     ]);
    // }




    public function index(Request $request, ContainerInterface $container): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        /** @var User $user */
        $user = $this->getUser();

        // // AJOUTE ÇA POUR VÉRIFIER
        // $test = $this->repository->findAll();
        // dd($test);

        $quittance = new Quittances($user);
        $form = $this->createForm(QuittancesType::class, $quittance, [
            'quittance' => $quittance,
            'user'      => $user,
        ]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // 1. Le locataire est déjà hydraté automatiquement → plus rien à faire !
            if (!$quittance->getLocataires() instanceof Locataires) {
                $this->addFlash('danger', 'Veuillez sélectionner un locataire valide.');
                return $this->redirectToRefererOrRoute($request, 'admin.quittances.index');
            }

            // 2. Vérification doublon
            if ($this->checkQuittance($quittance)) {
                $this->addFlash('danger', 'Cette quittance existe déjà.');
                return $this->redirectToRefererOrRoute($request, 'admin.quittances.index');
            }

            // 3. État par défaut "Payé"
            // $app = $this->parametresRepository->find(
            //     $container->getParameter('company_id')
            // );

            $etat = $quittance->getEtats();

            if (!$etat instanceof Etats) {
                // État par défaut depuis les paramètres
                $app = $this->parametresRepository->find($container->getParameter('company_id'));
                $etat = $this->etatsRepository->find($app?->getAppEtatPayer());

                if (!$etat instanceof Etats) {
                    throw new \LogicException("État de paiement par défaut non configuré.");
                }

                $quittance->setEtats($etat);
                $quittance->setIsPayer(true);
            } else {
                // On garde l'état choisi par l'utilisateur
                $quittance->setIsPayer(in_array($etat->getName(), ['Payé', 'En attente', 'Annuler']));
            }

            // 4. Persistance
            $this->entityManager->persist($quittance);
            $this->entityManager->flush();


            // 5. Notification + flash + redirect
            $this->notifications->save(
                "Nouvelle quittance #{$quittance->getCode()}",
                "Création",
                $quittance,
                "plus",
                "green",
                $quittance->getCompanyId()
            );

            $this->addFlash('success', 'Quittance ajoutée avec succès.');

            return $this->redirectToRefererOrRoute($request, 'admin.quittances.index');
        }

        // ──────────────────────────────────────────────────────────────
        // Partie recherche / listing
        // ──────────────────────────────────────────────────────────────
        // $search = new SearchQuittances();
        // $searchForm = $this->createForm(SearchQuittancesType::class, $search);
        // $searchForm->handleRequest($request);

        // $quittances = $this->repository->getQuittances($search);

        // ──────────────────────────────────────────────────────────────
        // RECHERCHE – VERSION QUI MARCHE TOUJOURS
        // ──────────────────────────────────────────────────────────────
        $searchForm = $this->createForm(SearchQuittancesType::class, null, [
            'method' => 'GET',
            'csrf_protection' => false,
        ]);
        $searchForm->handleRequest($request);

        // On crée un objet vide par défaut (pour le twig)
        $search = new SearchQuittances();

        if ($searchForm->isSubmitted() && $searchForm->isValid()) {
            $search = $searchForm->getData();
            $quittances = $this->repository->getQuittances($search);
        } else {
            // Premier affichage → on affiche les 100 dernières quittances de la compagnie
            $quittances = $this->repository->findBy(
                [],
                ['createdAt' => 'DESC'],
                100
            );
        }

        return $this->render('admin/quittances/index.html.twig', [
            'title'          => 'Quittances des loyers',
            'quittance'      => $quittance,
            'search'         => $search,
            'quittances'     => $quittances,
            'form'           => $form->createView(),
            'form_quittance' => $searchForm->createView(),
            'current_page'   => 'quittances',
            'current_global' => 'quittances',
        ]);
    }

    /**
     * Petit helper privé pour éviter la répétition du redirect
     */
    private function redirectToRefererOrRoute(Request $request, string $route): RedirectResponse
    {
        $referer = $request->headers->get('referer');

        return new RedirectResponse($referer ?: $this->generateUrl($route));
    }



    #[Route('/{id<\d+>}/edit', name: "admin.quittances.edit", methods: ['GET', 'POST'])]
    /**
     * @param Request $request
     * @param Quittances $quittance
     * @param ContainerInterface $container
     * @return Response
     */
    public function edit(Request $request, Quittances $quittance, ContainerInterface $container): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $form = $this->createForm(QuittancesType::class, $quittance, ['quittance' => $quittance]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Parametres $app */
            $app = $this->parametresRepository->find($container->getParameter('company_id'));

            /** @var Etats $etat */
            $etat = $this->etatsRepository->find($app->getAppEtatPayer());

            if ($quittance->getEtats() === $etat) {
                $quittance->setIsPayer(true);
            }

            if ($quittance->isIsPenalite()) {
                $quittance->setPenalite($quittance->getPenalite());
                $penalite = ($quittance->getTotal() * intval($quittance->getPenalite())) / 100;
                $quittance->setTotal($quittance->getTotal() + $penalite);
            } else {
                $quittance->setPenalite(0);
            }

            $this->managers->setEntity($quittance, 'edit');
            $this->notifications->save(
                "Modification de la quittance #{$quittance->getCode()}",
                "Modification",
                $quittance,
                "pencil5",
                "orange",
                $quittance->getCompanyId()
            );
            $this->addFlash('success', 'Quittance modifié avec succès.');
        }

        return $this->render('admin/quittances/edit.html.twig', [
            'quittance' => $quittance,
            'form' => $form->createView(),
            'title' => 'Editer la quittance',
            'libelle_liste' => 'Liste des quittances',
            'current_page' => 'quittances',
            'current_global' => 'quittances'
        ]);
    }

    #[Route('/{id<\d+>}/show', name: "admin.quittances.show", methods: ['GET'])]
    /**
     * @param Quittances $quittance
     * @return Response
     */
    public function show(Quittances $quittance): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        return $this->render('admin/quittances/invoice.html.twig', [
            'quittance' => $quittance,
            'title' => 'Détails de la quittance',
            'libelle_liste' => 'Liste des quittances',
            'current_page' => 'quittances',
            'current_global' => 'quittances'
        ]);
    }

    #[Route('/{id<\d+>}', name: "admin.quittances.delete", methods: ['DELETE'])]
    /**
     * @param Request $request
     * @param Quittances $quittance
     * @return Response
     */
    public function delete(Request $request, Quittances $quittance): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        if ($this->isCsrfTokenValid('delete' . $quittance->getId(), $request->request->get('_token'))) {
            $this->notifications->save(
                "Suppression de la quittance #{$quittance->getCode()}",
                "Suppression",
                $quittance,
                "trash",
                "red",
                $quittance->getCompanyId()
            );
            $this->managers->setEntity($quittance, 'delete');
            $this->addFlash('success', 'Quittance supprimé avec succès.');
        }

        $referer = $request->headers->get('referer');
        return new RedirectResponse($referer ?? $this->generateUrl('admin.quittances.index'));
    }

    /**
     * @param Quittances $quittance
     * @return bool
     * @throws NonUniqueResultException
     */
    private function checkQuittance(Quittances $quittance): bool
    {
        return (bool)$this->repository->checkQuittance($quittance);
    }
}
