<?php

namespace App\Controller\Admin;

use App\Entity\FacturePrestataire;
use App\Entity\Prestataire;
use App\Repository\PrestataireRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;


#[Route('/admin/prestataires', name: 'app_admin_prestataires_')]
#[IsGranted('ROLE_ROOT')]
class PrestatairesController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {
    }

    #[Route('', name: 'index')]
    public function index(PrestataireRepository $repo): Response
    {
        $prestataires = $repo->findBy([], ['raisonSociale' => 'ASC']);

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

    #[Route('/create', name: 'create', methods: ['POST'])]
    public function create(Request $request): Response
    {
        $raisonSociale = trim($request->request->getString('raisonSociale'));

        if ('' === $raisonSociale) {
            $this->addFlash('error', 'La raison sociale est obligatoire.');

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

        $prestataire = new Prestataire($raisonSociale);
        $prestataire->setSiret($request->request->getString('siret') ?: null);
        $prestataire->setEmail($request->request->getString('email') ?: null);
        $prestataire->setPhone($request->request->getString('phone') ?: null);
        $prestataire->setAddress($request->request->getString('address') ?: null);
        $prestataire->setZipCode($request->request->getString('zipCode') ?: null);
        $prestataire->setCity($request->request->getString('city') ?: null);

        $this->em->persist($prestataire);
        $this->em->flush();

        $this->addFlash('success', 'Prestataire "'.$raisonSociale.'" cree.');

        return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
    }

    #[Route('/{id}', name: 'show', requirements: ['id' => '\d+'])]
    public function show(Prestataire $prestataire): Response
    {
        return $this->render('admin/prestataires/show.html.twig', [
            'prestataire' => $prestataire,
        ]);
    }

    #[Route('/{id}/edit', name: 'edit', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function edit(Prestataire $prestataire, Request $request): Response
    {
        $raisonSociale = trim($request->request->getString('raisonSociale'));
        if ('' !== $raisonSociale) {
            $prestataire->setRaisonSociale($raisonSociale);
        }

        $prestataire->setSiret($request->request->getString('siret') ?: null);
        $prestataire->setEmail($request->request->getString('email') ?: null);
        $prestataire->setPhone($request->request->getString('phone') ?: null);
        $prestataire->setAddress($request->request->getString('address') ?: null);
        $prestataire->setZipCode($request->request->getString('zipCode') ?: null);
        $prestataire->setCity($request->request->getString('city') ?: null);

        $this->em->flush();
        $this->addFlash('success', 'Prestataire mis a jour.');

        return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
    }

    #[Route('/{id}/delete', name: 'delete', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function delete(Prestataire $prestataire): Response
    {
        $name = $prestataire->getRaisonSociale();
        $this->em->remove($prestataire);
        $this->em->flush();
        $this->addFlash('success', 'Prestataire "'.$name.'" supprime.');

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

    #[Route('/entreprise-search', name: 'entreprise_search', methods: ['GET'])]
    public function entrepriseSearch(Request $request, \App\Service\EntrepriseSearchService $searchService): JsonResponse
    {
        return $searchService->search(trim($request->query->getString('q')), 5);
    }

    // ---------------------------------------------------------------
    // Factures prestataire
    // ---------------------------------------------------------------

    #[Route('/{id}/facture/add', name: 'facture_add', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function addFacture(Prestataire $prestataire, Request $request): Response
    {
        $numFacture = trim($request->request->getString('numFacture'));
        $montantHt = $request->request->getString('montantHt');
        $montantTtc = $request->request->getString('montantTtc');
        $year = $request->request->getInt('year');
        $month = $request->request->getInt('month');

        if ('' === $numFacture || $year < 2020 || $month < 1 || $month > 12) {
            $this->addFlash('error', 'Donnees invalides.');

            return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
        }

        $facture = new FacturePrestataire($prestataire, $numFacture, $year, $month);
        $facture->setMontantHt(number_format((float) $montantHt, 2, '.', ''));
        $facture->setMontantTtc(number_format((float) $montantTtc, 2, '.', ''));

        /** @var UploadedFile|null $file */
        $file = $request->files->get('facturePdf');
        if (null !== $file && $file->isValid()) {
            $facture->setFacturePdfFile($file);
        }

        $prestataire->addFacture($facture);
        $this->em->persist($facture);
        $this->em->flush();

        $this->addFlash('success', 'Facture '.$numFacture.' ajoutee pour '.$facture->getPeriodLabel().'.');

        return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
    }

    #[Route('/{id}/facture/{factureId}/paid', name: 'facture_paid', requirements: ['id' => '\d+', 'factureId' => '\d+'], methods: ['POST'])]
    public function markPaid(Prestataire $prestataire, int $factureId): Response
    {
        $facture = $this->em->getRepository(FacturePrestataire::class)->find($factureId);

        if (null !== $facture && $facture->getPrestataire()->getId() === $prestataire->getId()) {
            $facture->setIsPaid(true);
            $facture->setPaidAt(new \DateTimeImmutable());
            $this->em->flush();
            $this->addFlash('success', 'Facture '.$facture->getNumFacture().' marquee payee.');
        }

        return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
    }

    #[Route('/{id}/facture/{factureId}/delete', name: 'facture_delete', requirements: ['id' => '\d+', 'factureId' => '\d+'], methods: ['POST'])]
    public function deleteFacture(Prestataire $prestataire, int $factureId): Response
    {
        $facture = $this->em->getRepository(FacturePrestataire::class)->find($factureId);

        if (null !== $facture && $facture->getPrestataire()->getId() === $prestataire->getId()) {
            $this->em->remove($facture);
            $this->em->flush();
            $this->addFlash('success', 'Facture supprimee.');
        }

        return $this->redirectToRoute('app_admin_prestataires_show', ['id' => $prestataire->getId()]);
    }
}
