<?php

namespace App\Controller;

use App\Dto\Contact\ContactType;
use App\Dto\Contact\DtoContact;
use App\Entity\Account;
use App\Entity\AccountResetPasswordRequest;
use App\Entity\Dons;
use App\Entity\MembersCotisations;
use App\Form\RequestPasswordConfirmType;
use App\Form\RequestPasswordRequestType;
use App\Repository\MembersCotisationsRepository;
use App\Service\Mailer\Mailer;
use App\Service\Payments\PaymentClient;
use App\Service\Pdf\CotaReceiptGenerator;
use App\Service\Pdf\DonReceiptGenerator;
use App\Service\ResetPassword\Event\ResetPasswordConfirmEvent;
use App\Service\ResetPassword\Event\ResetPasswordEvent;
use Doctrine\ORM\EntityManagerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
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;

class WebhooksController extends AbstractController
{

    #[Route(path: '/webhooks', name: 'app_webhooks', options: ['sitemap' => false], methods: ['POST'])]
    public function index(DonReceiptGenerator $donReceiptGenerator,MembersCotisationsRepository $membersCotisationsRepository,Request $request,PaymentClient $paymentClient,Mailer $mailer,EntityManagerInterface $entityManager,): Response
    {
        $content = $request->getContent();
        if($paymentClient->validateWebhooks($content)) {
            $content = json_decode($content);
            $object = $content->data->object;
            $metadata = $object->metadata;
            if($object->status == "complete") {
                if($metadata->id_con) {
                    $me=  $membersCotisationsRepository->find($metadata->id_con);
                    if($me instanceof MembersCotisations) {
                        $me->setIsPaid(true);
                        $entityManager->persist($me);
                        $entityManager->flush();

                        $pdfGenerator = new CotaReceiptGenerator();

                        $v = new \DateTime();
                        $donationData = [
                            'pseudo' => $me->getMembers()->getPseudo(),
                            'email' => $me->getMembers()->getEmail(),
                            'amount' => $me->getAmount(),
                            'date' => $v->format('Y-m-d'),
                            'period' => $me->getStartdATE()->format('d/m/Y')." - ".$me->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($me->getMembers()->getEmail(),$me->getMembers()->getPseudo(), '[E-Cosplay] - Confirmation de votre paiement de votre cotisation', "mails/cota_validation.twig", [
                            'pseudo' => $me->getMembers()->getPseudo(),
                            'start_at'=> $me->getStartdATE(),
                            'end_at'=> $me->getEnddate(),
                            'amount' => $me->getAmount(),
                        ], $files);
                    }
                } else {
                    $dons = new Dons();
                    $dons->setName($metadata->name);
                    $dons->setEmail($metadata->email);
                    $dons->setAmount($metadata->amount);
                    $dons->setMessage($metadata->message);
                    $entityManager->persist($dons);
                    $pdfGenerator = new DonReceiptGenerator();

                    $v = new \DateTime();
                    $donationData = [
                        'name' => $metadata->name,
                        'email' => $metadata->email,
                        'amount' => $metadata->amount,
                        'date' => $v->format('Y-m-d'),
                        'message' => $metadata->message ?? null,
                    ];
                    $files = [];
                    $pdfContent = $pdfGenerator->generate(
                        $donationData,
                        'recu_don_E-Cosplay.pdf',
                        'S'
                    );
                    $files[] = new DataPart($pdfContent, 'recu_don_E-Cosplay.pdf', 'application/pdf');

                    $mailer->send($metadata->email, $metadata->name, '[E-Cosplay] - Confirmation de votre don de ' . $metadata->amount . " €", "mails/dons.twig", [
                        'don' => $dons,
                    ], $files);

                    $mailer->send($metadata->email, $metadata->name, '[E-Cosplay] - Confirmation d\'un don de ' . $metadata->amount . " €", "mails/dons_new.twig", [
                        'don' => $dons,
                    ]);

                    $entityManager->flush();
                }
            }
        }
        return $this->json([]);
    }
}
