<?php

namespace App\Controller\Admin;

use App\Dto\Ag\AgMembersType;
use App\Dto\Ag\AgOrderType;
use App\Dto\Ag\AgType;
use App\Dto\Ag\AgTypeEdit;
use App\Dto\Ag\AgVoteType;
use App\Entity\Account;
use App\Entity\AccountResetPasswordRequest;
use App\Entity\Ag\Main;
use App\Entity\Ag\MainMember;
use App\Entity\Ag\MainOrder;
use App\Entity\Ag\MainSigned;
use App\Entity\Ag\MainVote;
use App\Entity\Event;
use App\Entity\InviteEPage;
use App\Entity\Members;
use App\Entity\MembersCotisations;
use App\Entity\Products;
use App\Form\EventType;
use App\Form\MembersType;
use App\Form\ProductsType;
use App\Form\RequestPasswordConfirmType;
use App\Form\RequestPasswordRequestType;
use App\Repository\Ag\MainRepository;
use App\Repository\EventRepository;
use App\Repository\InviteEPageRepository;
use App\Repository\JoinRepository;
use App\Repository\MembersCotisationsRepository;
use App\Repository\MembersRepository;
use App\Repository\ProductsRepository;
use App\Service\Events\AdvertEvent;
use App\Service\Mailer\Mailer;
use App\Service\Payments\PaymentClient;
use App\Service\Pdf\AgAdh;
use App\Service\Pdf\AgConvocation;
use App\Service\Pdf\AgGenerator;
use App\Service\Pdf\CotaReceiptGenerator;
use App\Service\ResetPassword\Event\ResetPasswordConfirmEvent;
use App\Service\ResetPassword\Event\ResetPasswordEvent;
use Doctrine\ORM\EntityManagerInterface;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Label\Font\OpenSans;
use Endroid\QrCode\Label\LabelAlignment;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Twig\Environment;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;

class AdminController extends AbstractController
{

    #[Route(path: '/admin', name: 'admin_dashboard', options: ['sitemap' => false], methods: ['GET'])]
    public function adminDashboard(MembersRepository $membersRepository,JoinRepository $joinRepository): Response
    {
        return $this->render('admin/dashboard.twig', [
            'memberCount' => $membersRepository->count(),
            'joins' => $joinRepository->count(['state'=>'create'])+$joinRepository->count(['state'=>'waiting']),
        ]);
    }
    #[Route(path: '/admin/products', name: 'admin_products', options: ['sitemap' => false], methods: ['GET'])]
    public function adminProducts(Request $request,EntityManagerInterface $entityManager,ProductsRepository $productsRepository): Response
    {

        if($request->query->has('id')){
            $pc = $entityManager->getRepository(Products::class)->find($request->query->get('id'));
            $entityManager->remove($pc);
            $entityManager->flush();
            return $this->redirectToRoute('admin_products');
        }
        return $this->render('admin/products.twig', [
            'products' => $productsRepository->findAll(),
        ]);
    }
    #[Route(path: '/admin/products/{id}', name: 'admin_product_edit', options: ['sitemap' => false], methods: ['GET','POST'], priority: 5)]
    public function adminProductEdit(?Products $product,Request $request,EntityManagerInterface $entityManager): Response
    {


        $form = $this->createForm(ProductsType::class, $product);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $product->setImage($request->files->all()['products']['image']);
            $entityManager->persist($product);
            $entityManager->flush();
            return $this->redirectToRoute('admin_product_edit', ['id' => $product->getId()]);
        }
        return $this->render('admin/products/add.twig', [
            'form' => $form->createView(),
        ]);
    }
    #[Route(path: '/admin/products/add', name: 'admin_product_create', options: ['sitemap' => false], methods: ['GET','POST'], priority: 5)]
    public function adminProductCreate(Request $request,EntityManagerInterface $entityManager): Response
    {
        $product = new Products();
        $product->setUpdateAt(new \DateTimeImmutable());
        $product->setCreateAt(new \DateTimeImmutable());
        $product->setState("new");
        $product->setIsActive(true);
        $product->setIsPromo(false);

        $form = $this->createForm(ProductsType::class, $product);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $product->setImage($request->files->all()['products']['image']);
            $entityManager->persist($product);
            $entityManager->flush();
            return $this->redirectToRoute('admin_products');
        }
        return $this->render('admin/products/add.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route(path: '/admin/members', name: 'admin_members', options: ['sitemap' => false], methods: ['GET'])]
    public function adminMembers(MembersRepository $membersRepository): Response
    {

        return $this->render('admin/members.twig', [
            'members' => $membersRepository->findBy([],['id' => 'ASC']),
        ]);
    }
    #[Route(path: '/admin/members/{id}', name: 'admin_member_edit', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminMembersEdit(Mailer $mailer,PaymentClient $paymentClient,MembersCotisationsRepository $membersCotisationsRepository,?Members $members,Request $request,EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(MembersType::class, $members);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $file = $request->files->all()['members']['members'];
            $members->setMembers($file);
            $members->setUpdateAt(new \DateTimeImmutable());
            $entityManager->persist($members);
            $entityManager->flush();
            return $this->redirectToRoute('admin_member_edit',['id'=>$members->getId()]);
        }

        if($request->query->has('idValidateCota')) {
            $cota = $membersCotisationsRepository->find($request->query->get('idValidateCota'));
            $cota->setIsPaid(true);
            $entityManager->persist($cota);
            $entityManager->flush();

            $pdfGenerator = new CotaReceiptGenerator();

            $v = new \DateTime();
            $donationData = [
                'pseudo' => $cota->getMembers()->getPseudo(),
                'email' => $cota->getMembers()->getEmail(),
                'amount' => $cota->getAmount(),
                'date' => $v->format('Y-m-d'),
                'period' => $cota->getStartdATE()->format('d/m/Y')." - ".$cota->getEnddate()->format('d/m/Y'),
            ];
            $files = [];
            $pdfContent = $pdfGenerator->generate(
                $donationData,
                'recu_cotisation_E-Cosplay.pdf',
                'S'
            );
            $files[] = new DataPart($pdfContent, 'recu_cotisation_E-Cosplay.pdf', 'application/pdf');

            $mailer->send($members->getEmail(),$members->getPseudo(), '[E-Cosplay] - Confirmation de votre paiement de votre cotisation', "mails/cota_validation.twig", [
                'pseudo' => $members->getPseudo(),
                'start_at'=> $cota->getStartdATE(),
                'end_at'=> $cota->getEnddate(),
                'amount' => $cota->getAmount(),
            ], $files);
            return $this->redirectToRoute('admin_member_edit',['id'=>$members->getId()]);

        }
        if($request->query->has('idLinkCota')) {
            $cota = $membersCotisationsRepository->find($request->query->get('idLinkCota'));
            $link = $paymentClient->paymentCota($cota);
            $cota->setPaymentId($link->id);
            $entityManager->persist($cota);
            $entityManager->flush();
            $paymentLink = $link->url;

            $mailer->send($members->getEmail(),$members->getPseudo(),"[E-Cosplay] - Lien de paiement de votre cotisation","mails/coti_payment.twig",[
                'pseudo'=>$members->getPseudo(),
                'link'=>$paymentLink,
                'amount' => $cota->getAmount(),
                'start_at' => $cota->getStartdATE(),
                'end_at' => $cota->getEndDate(),
            ]);
            return $this->redirectToRoute('admin_member_edit',['id'=>$members->getId()]);

        }

        return $this->render('admin/member/add.twig', [
            'form' => $form->createView(),
            'member' => $members,
        ]);
    }
    #[Route(path: '/admin/members/add', name: 'admin_member_create', options: ['sitemap' => false], methods: ['GET','POST'], priority: 5)]
    public function adminMembersCreate(Request $request,EntityManagerInterface $entityManager): Response
    {
        $members = new Members();
        $members->setRole('Membre');
        $members->setTrans(false);
        $members->setCrosscosplayer(false);
        $members->setCosplayer(false);
        $form = $this->createForm(MembersType::class, $members);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $dateTimeStart = \DateTimeImmutable::createFromFormat('d/m/Y', $members->getJoinedAt());
            $dateTimeEnd = \DateTimeImmutable::createFromFormat('d/m/Y', $members->getJoinedAt());
            $dateTimeEnd = $dateTimeEnd->modify("+1 year");
            $memberCota = new MembersCotisations();
            $memberCota->setMembers($members);
            $memberCota->setStartdATE($dateTimeStart);
            $memberCota->setEndDATE($dateTimeEnd);
            $memberCota->setIsPaid(false);
            $memberCota->setAmount(10);
            $entityManager->persist($memberCota);
            $entityManager->persist($members);
            $entityManager->flush();

            return $this->redirectToRoute('admin_members');
        }
        return $this->render('admin/member/add.twig', [
            'form' => $form->createView(),
            'member' => $members,
        ]);
    }
    #[Route(path: '/admin/members/delete/{id}', name: 'admin_member_delete', options: ['sitemap' => false], methods: ['GET'])]
    public function adminMembersDelete(?Members $members,EntityManagerInterface $entityManager): Response
    {
        if($members instanceof Members){
            $entityManager->remove($members);
            $entityManager->flush();
        }
        return $this->redirectToRoute('admin_members');
    }

    #[Route(path: '/admin/events', name: 'admin_events', options: ['sitemap' => false], methods: ['GET'])]
    public function adminEvents(EventRepository $eventRepository): Response
    {
        return $this->render('admin/events.twig', [
            'events' => $eventRepository->findBy([],['id' => 'DESC']),
        ]);
    }
    #[Route(path: '/admin/events/delete', name: 'admin_events_delete', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminEventDelete(?Event $event,EntityManagerInterface $entityManager): Response
    {

    }
    #[Route(path: '/admin/events/add', name: 'admin_events_create', options: ['sitemap' => false], methods: ['GET','POST'])]
    #[Route(path: '/admin/events/{id}', name: 'admin_events_edit', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminEventAdd(?Event $event,Request $request,EntityManagerInterface $entityManager,EventDispatcherInterface $eventDispatcher): Response
    {
        $isNew = false;
        if(is_null($event)) {
            $event = new Event();
            $isNew = true;
        }
        $form  = $this->createForm(EventType::class,$event);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $event->setAffiche($request->files->all()['event']['affiche']);
            $event->setUpdateAt(new \DateTimeImmutable('now'));
            if($isNew) {
                $sendEvent = new AdvertEvent($event);
                $eventDispatcher->dispatch($sendEvent);
            }
            $entityManager->persist($event);
            $entityManager->flush();

            return $this->redirectToRoute('admin_events');
        }
        return $this->render('admin/events/add.twig', [
            'form' => $form->createView(),
            'event' => $event
        ]);
    }

    #[Route(path: '/admin/epage/invitation', name: 'admin_epage_invite', options: ['sitemap' => false], methods: ['GET'])]
    public function adminEpageInvitation(InviteEPageRepository $inviteEPageRepository): Response
    {
        return $this->render('admin/epage/invitation.twig', [
            'invitations' => $inviteEPageRepository->findBy([],['id' => 'DESC']),
        ]);
    }
    #[Route(path: '/admin/ag', name: 'admin_ag', options: ['sitemap' => false], methods: ['GET'])]
    public function adminAg(Mailer $mailer,UploaderHelper $uploaderHelper,KernelInterface $kernel,EntityManagerInterface $entityManager,Request $request,MainRepository $mainRepository): Response
    {

        if($request->query->has('idValidateSign')) {
            /** @var Main $main */
            $main = $mainRepository->find($request->query->get('idValidateSign'));
            $docuseal = new \Docuseal\Api('pgAU116mCFmeF7WQSezHqxtZW8V1fgo31u5d2FXoaKe', 'https://signature.esy-web.dev/api');
            $sub = $docuseal->getSubmitter($main->getSubmiterId());
            $link = $sub['documents'][0]['url'];
            $content = file_get_contents($link);
            $fileName = 'ag_sign_ecosplay_' . $main->getAgDateAt()->format('Ymd') . '.pdf';
            $tempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
            file_put_contents($tempFilePath, $content);
            $file = new UploadedFile($tempFilePath,$fileName,"application/pdf",0,true);
            $main->setAg($file);
            $main->setUpdateAt(new \DateTimeImmutable());
            $main->setIsSigned(true);
            $entityManager->persist($main);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag');
        }
        if($request->query->has('idQrCode')) {
            /** @var Main $idQrCode */
            $idQrCode = $mainRepository->find($request->query->get('idQrCode'));

            if($_ENV['APP_ENV'] == "prod") {
                $urlRoot = $request->getContentTypeFormat();
            } else {
                $urlRoot = $_ENV['DEV_URL'];
            }
            $builder = new Builder(
                writer: new PngWriter(),
                writerOptions: [],
                validateResult: false,
                data: $urlRoot.$this->generateUrl('app_adh',['id'=>$idQrCode->getId()]),
                encoding: new Encoding('UTF-8'),
                errorCorrectionLevel: ErrorCorrectionLevel::High,
                size: 300,
                margin: 10,
            );
            $result = $builder->build();
            $response = new Response($result->getString(),Response::HTTP_OK,[
                'Content-Type' => $result->getMimeType()
            ]);
            return $response;
        }
        if($request->query->has('idSign')) {
            /** @var Main $main */
            $main = $mainRepository->find($request->query->get('id'));
            $url = $uploaderHelper->asset($main,'ag');

            if($_ENV['APP_ENV'] == "prod") {
                $url = $request->getSchemeAndHttpHost() . $url;
                $urlRoot = $request->getSchemeAndHttpHost();
            } else {
                $url = $_ENV['DEV_URL'] . $url;
                $urlRoot = $_ENV['DEV_URL'];
            }
            $docuseal = new \Docuseal\Api('pgAU116mCFmeF7WQSezHqxtZW8V1fgo31u5d2FXoaKe', 'https://signature.esy-web.dev/api');
            $content = $docuseal->createSubmissionFromPdf([
                'name' => 'AG E-COSPLAY '.$main->getAgDateAt()->format('d/m/Y'),
                'documents' => [
                    [
                        'name' => 'ag-ecosplay-'.$main->getAgDateAt()->format('d-m-Y'),
                        'file' => $url
                    ]
                ],
                'completed_redirect_url' => $urlRoot.$this->generateUrl('admin_ag',['idValidateSign'=>$main->getId()]),
                'submitters' => [
                    [
                        'role' => 'First Party',
                        'email' => 'contact@e-cosplay.fr',
                    ]
                ]
            ]);
            $slug = $content['submitters'][0]['id'];
            $main->setSubmiterId($slug);
            $entityManager->persist($main);
            $entityManager->flush();
            $path = $content['submitters'][0]['embed_src'];
            $r = new RedirectResponse($path);
            $r->setStatusCode(302);
            return $r;
        }
        if($request->query->has('idSendConvocation')) {
            /** @var Main $main */
            $main = $mainRepository->find($request->query->get('idSendConvocation'));
            $agAdh = new AgAdh();
            $agAdh->setData($main,$kernel,$entityManager);
            $agAdh->GeneratePdf();
            $content = $agAdh->Output('S');
            $fileName = 'adh_ecosplay_' . $main->getAgDateAt()->format('Ymd') . '.pdf';
            $tempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
            file_put_contents($tempFilePath, $content);
            $file = new UploadedFile($tempFilePath,$fileName,"application/pdf",0,true);
            $main->setAgAdh($file);
            $main->setUpdateAt(new \DateTimeImmutable());
            $entityManager->persist($main);
            $entityManager->flush();
            if($_ENV['APP_ENV'] == "prod") {
                $url = $request->getSchemeAndHttpHost();
                $urlRoot = $request->getSchemeAndHttpHost();
            } else {
                $url = $_ENV['DEV_URL'];
                $urlRoot = $_ENV['DEV_URL'];
            }

            file_put_contents($kernel->getProjectDir()."/public/tmp/sign.pdf",$content);
            $sub =  [];
            foreach ($main->getMainSigneds() as $mainSigned) {
                $sub[] =  [
                    'name' => 'member_'.$mainSigned->getId(),
                    'role' => 'member_'.$mainSigned->getId(),
                    'email' => 'contact@e-cosplay.fr',
                    'completed_redirect_url' =>$urlRoot.$this->generateUrl('app_adh',['id'=>$main->getId(),'validateResult'=>true,'vr'=>$mainSigned->getId()]),
                ];
            }
            $data = [
                'name' => 'ADH E-COSPLAY '.$main->getAgDateAt()->format('d/m/Y'),
                'documents' => [
                    [
                        'name' => 'adh-ecosplay-'.$main->getAgDateAt()->format('d-m-Y'),
                        'file' => $url."/tmp/sign.pdf"
                    ]
                ],
                'submitters' => $sub,
            ];
            $docuseal = new \Docuseal\Api('pgAU116mCFmeF7WQSezHqxtZW8V1fgo31u5d2FXoaKe', 'https://signature.esy-web.dev/api');
            $content = $docuseal->createSubmissionFromPdf($data);
            foreach ($content['submitters'] as $mainSigned) {
                $role = str_replace("member_","",$mainSigned['name']);
                /** @var MainSigned $name */
                $name = $entityManager->getRepository(MainSigned::class)->find($role);
                $name->setSubmiterId($mainSigned['id']);
                $entityManager->persist($name);
            }
            $entityManager->flush();
        }
        if($request->query->has('idConvocation')) {
            /** @var Main $main */
            $main = $mainRepository->find($request->query->get('idConvocation'));
            $agAdh = new AgAdh();
            $agAdh->setData($main,$kernel,$entityManager);
            $agAdh->GeneratePdf();
            $content = $agAdh->Output('S');
            $fileName = 'adh_ecosplay_' . $main->getAgDateAt()->format('Ymd') . '.pdf';
            $tempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;

            file_put_contents($tempFilePath, $content);
            $file = new UploadedFile($tempFilePath,$fileName,"application/pdf",0,true);
            $main->setAgAdh($file);
            $main->setUpdateAt(new \DateTimeImmutable());
            $main->setIsAttestation(true);
            $entityManager->persist($main);
            $entityManager->flush();
            if($_ENV['APP_ENV'] == "prod") {
                $url = $request->getSchemeAndHttpHost();
                $urlRoot = $request->getSchemeAndHttpHost();
            } else {
                $url = $_ENV['DEV_URL'];
                $urlRoot = $_ENV['DEV_URL'];
            }
            $rList =[];
            $submitters =[];
            foreach ($entityManager->getRepository(Members::class)->findAll() as $member) {
                $isSigned = $member->getMainSigneds()->filter(function (MainSigned $sign) use ($member) {
                    return $sign->getMembers()->getId() ==  $member->getId();
                })->first();
                if(!$isSigned instanceof MainSigned) {
                    $isSigned = new MainSigned();
                    $isSigned->setMembers($member);
                    $isSigned->setMain($main);
                    $isSigned->setSubmiterId(0);
                    $entityManager->persist($isSigned);
                    $entityManager->flush();
                    $rList[] = $isSigned;
                }
                $agConvocation = new AgConvocation();
                $agConvocation->setData($main,$kernel,$member);
                $agConvocation->generateConvocation();
                $content = $agConvocation->Output('S');
                $fileName = 'convocation_ag_ecosplay_' . $main->getAgDateAt()->format('Ymd') . '.pdf';
                $mailer->send($member->getEmail(),$member->getCiv()." ".$member->getSurname().' '.$member->getName(),"[E-Cosplay] Convocation assemblée générale","mails/ag_convocation.twig",[
                    'main' => $main,
                    'member' => $member,
                ],[
                    new DataPart($content,$fileName,"application/pdf"),
                ]);

            }
            file_put_contents($kernel->getProjectDir()."/public/tmp/sign.pdf",$content);

            $data = [
                'name' => 'ADH E-COSPLAY '.$main->getAgDateAt()->format('d/m/Y'),
                'documents' => [
                    [
                        'name' => 'adh-ecosplay-'.$main->getAgDateAt()->format('d-m-Y'),
                        'file' => $url."/tmp/sign.pdf"
                    ]
                ],
                'submitters' => [
                    [
                        'role' => 'First Party',
                        'email' => 'contact@e-cosplay.fr',
                        'completed_redirect_url' =>$urlRoot.$this->generateUrl('app_adh',['id'=>$main->getId(),'validateResult'=>true,'vr'=>$isSigned->getId()]),
                    ]
                ],
            ];
            $docuseal = new \Docuseal\Api('pgAU116mCFmeF7WQSezHqxtZW8V1fgo31u5d2FXoaKe', 'https://signature.esy-web.dev/api');
            $content = $docuseal->createSubmissionFromPdf($data);
            $slug = $content['submitters'][0]['id'];
            foreach ($rList as $submitter) {
                $submitter->setSubmiterId($slug);
                $entityManager->persist($submitter);
            }
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag');
        }
        if($request->query->has('idGenerate')) {
            /** @var Main $main */
            $main = $mainRepository->find($request->query->get('idGenerate'));
            $ag = new AgGenerator();
            $ag->setData($main,$kernel,$entityManager);
            $ag->SetTitle("AG - E-Cosplay ".$main->getAgDateAt()->format('d/m/Y'));
            $ag->AliasNbPages();
            $ag->AddPage();
            $ag->writeConstitutionAndMembers();
            $ag->writeSpecificAgendaItems();
            $ag->writeBureauRenewalAndClosure();
            // 1. Récupération du contenu du PDF en chaîne de caractères
            $content = $ag->Output('S');
            $fileName = 'ag_ecosplay_' . $main->getAgDateAt()->format('Ymd') . '.pdf';
            $tempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;

            file_put_contents($tempFilePath, $content);
            $file = new UploadedFile($tempFilePath,$fileName,"application/pdf",0,true);
            $main->setAg($file);
            $main->setUpdateAt(new \DateTimeImmutable());
            $main->setIsClosed(true);
            $entityManager->persist($main);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag');
        }
        return $this->render('admin/ag.twig', [
            'ags' => $mainRepository->findBy([],['agDateAt'=>'DESC']),
        ]);
    }

    #[Route(path: '/admin/ag/new', name: 'admin_ag_new', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminAgNew(Request $request,EntityManagerInterface $entityManager): Response
    {
        $ag = new Main();
        $form = $this->createForm(AgType::class,$ag);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()){

            $entityManager->persist($ag);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag');
        }
        return $this->render('admin/ag/new.twig', [
            'ag' => $form->createView(),
        ]);
    }
    #[Route(path: '/admin/ag/{id}', name: 'admin_ag_edit', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminAgeDIT(?Main $ag,Request $request,EntityManagerInterface $entityManager): Response
    {
        $form = $this->createForm(AgTypeEdit::class,$ag);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()){
            $entityManager->persist($ag);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }

        $agOrder = new MainOrder();
        $agOrder->setMain($ag);
        $formOrder = $this->createForm(AgOrderType::class,$agOrder);
        $formOrder->handleRequest($request);
        if($formOrder->isSubmitted() && $formOrder->isValid()){
            $entityManager->persist($agOrder);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }

        $agMembers = new MainMember();
        $agMembers->setMain($ag);
        $formMember = $this->createForm(AgMembersType::class,$agMembers);
        $formMember->handleRequest($request);
        if($formMember->isSubmitted() && $formMember->isValid()){
            $rf = $entityManager->getRepository(Members::class)->find($request->request->all()['ag_members']['member']);

            $agMembers->setMember($rf);
            $t = new \DateTime();
            $tz = new \DateTime();
            $tz->modify('+1 year');
            $isValid = $agMembers->getMember()->getMembersCotisations()->filter(function (MembersCotisations $membersCotisations) use ($t,$tz) {
                return ($membersCotisations->getStartdATE()->format('Y') == $t->format('Y')) && ($membersCotisations->getEndDate()->format('Y') == $tz->format('Y'));
            })->first();
            $agMembers->setIsVotedAllow($isValid instanceof MembersCotisations);
            $entityManager->persist($agMembers);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }
        if($request->query->has('idMember')) {
            $agMembers = $entityManager->getRepository(MainMember::class)->find($request->query->get('idMember'));
            $entityManager->remove($agMembers);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }
        if($request->query->has('orderId')) {
            $agOders = $entityManager->getRepository(MainOrder::class)->find($request->query->get('orderId'));
            $entityManager->remove($agOders);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }
        if($request->query->has('agVoteId')) {
            $agOders = $entityManager->getRepository(MainVote::class)->find($request->query->get('agVoteId'));
            $entityManager->remove($agOders);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }

        $agVote = new MainVote();
        $agVote->setMain($ag);
        $formMemberVote = $this->createForm(AgVoteType::class,$agVote);
        $formMemberVote->handleRequest($request);
        if($formMemberVote->isSubmitted() && $formMemberVote->isValid()){
            $rf = $entityManager->getRepository(Members::class)->find($request->request->all()['ag_vote']['member']);
            $agVote->setMember($rf);
            $entityManager->persist($agVote);
            $entityManager->flush();
            return $this->redirectToRoute('admin_ag_edit',['id'=>$ag->getId()]);
        }


        return $this->render('admin/ag/edit.twig', [
            'ag' => $form->createView(),
            'agMain' => $ag,
            'agMembers' => $formMember->createView(),
            'agVote' => $formMemberVote->createView(),
            'agOrder' => $formOrder->createView(),
        ]);
    }
    #[Route(path: '/admin/ag/delete/{id}', name: 'admin_ag_delete', options: ['sitemap' => false], methods: ['GET','POST'])]
    public function adminAgDelete(?Main $ag,Request $request,EntityManagerInterface $entityManager): Response
    {
        foreach ($ag->getMainMembers() as $member)
            $entityManager->remove($member);
        foreach ($ag->getOrders() as $order)
            $entityManager->remove($order);
        $entityManager->remove($ag);
        $entityManager->flush();
        return $this->redirectToRoute('admin_ag');
    }
}
