<?php

// src/Controller/ClientsController.php

namespace App\Controller;

use App\Entity\Clients;
use App\Entity\Reductions;
use App\Form\ClientsType;
use App\Repository\ClientsRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/clients')]
final class ClientsController extends AbstractController
{
    #[Route(name: 'app_clients_index', methods: ['GET'])]
    public function index(ClientsRepository $clientsRepository): Response
    {
        return $this->render('clients/index.html.twig', [
            'clients' => $clientsRepository->findAll(),
        ]);
    }

    #[Route('/new', name: 'app_clients_new', methods: ['GET', 'POST'])]
    public function new(Request $request, EntityManagerInterface $entityManager): Response
    {
        $client = new Clients();
        $form = $this->createForm(ClientsType::class, $client);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $montantTotal = $client->getTotalDepense();
            if($montantTotal > 1000){
                $this->appliquerReductionEtCreerSiNecessaire($client, $entityManager);
            }

            $entityManager->persist($client);
            $entityManager->flush();

            return $this->redirectToRoute('app_clients_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('clients/new.html.twig', [
            'client' => $client,
            'form' => $form,
        ]);
    }

    #[Route('/{id}/edit', name: 'app_clients_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Clients $client, EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(ClientsType::class, $client);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $montantTotal = $client->getTotalDepense();
            if($montantTotal > 1000){
                $this->appliquerReductionEtCreerSiNecessaire($client, $entityManager);
            }


            $entityManager->flush();

            return $this->redirectToRoute('app_clients_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('clients/edit.html.twig', [
            'client' => $client,
            'form' => $form,
        ]);
    }

    #[Route('/{id}', name: 'app_clients_delete', methods: ['POST'])]
    public function delete(Request $request, Clients $client, EntityManagerInterface $entityManager): Response
    {
        if ($this->isCsrfTokenValid('delete'.$client->getId(), $request->request->get('_token'))) {
            $entityManager->remove($client);
            $entityManager->flush();
        }

        return $this->redirectToRoute('app_clients_index', [], Response::HTTP_SEE_OTHER);
    }

    // Méthode pour appliquer ou créer une réduction pour un client
    // src/Controller/ClientsController.php

    private function appliquerReductionEtCreerSiNecessaire(Clients $client, EntityManagerInterface $entityManager)
    {
        $montantTotal = $client->getTotalDepense();
        $entityManager->persist($client);

        $reductions = $entityManager->getRepository(Reductions::class)
            ->createQueryBuilder('r')
            ->where('r.montant_min <= :montantTotal')
            ->andWhere('r.actif = :actif')
            ->andWhere('r.DateDebut <= :currentDate')
            ->andWhere('r.DateFin >= :currentDate')
            ->setParameter('montantTotal', $montantTotal)
            ->setParameter('actif', true)
            ->setParameter('currentDate', new \DateTime())
            ->getQuery()
            ->getResult();

            $newReduction = new Reductions();

            if ($montantTotal >= 2000) {
                $montantMin = 2000;
                $pourcentage = 10;
            } elseif ($montantTotal >= 1000) {
                $montantMin = 1000;
                $pourcentage = 5;
            }

            $newReduction->setPourcentage($pourcentage)
            ->setMontantMin($montantMin)
            ->setDateDebut(new \DateTime())
            ->setDateFin((new \DateTime())->modify('+1 year'))
            ->setActif(true)
            ->setClient($client);

            $entityManager->persist($newReduction);
            $entityManager->flush();

            if (!$client->getReductions()->contains($newReduction)) {
                $client->addReduction($newReduction);
            }

        $entityManager->flush();
    }


}
