<?php

namespace App\Controller;

use App\Entity\ContratsPayments;
use App\Entity\Devis;
use App\Entity\Product;
use App\Entity\ProductReserve;
use App\Kernel;
use App\Repository\ProductRepository;
use App\Service\Mailer\Mailer;
use App\Service\Pdf\PlPdf;
use App\Service\Stripe\Client;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Attribute\Route;

class Webhooks extends AbstractController
{
    #[Route(path: '/webhooks/payment-intent', name: 'webhooks_payment', options: ['sitemap' => false], methods: ['POST'])]
    public function payment(Mailer $mailer,KernelInterface $kernel,\App\Service\Signature\Client $sig, ProductRepository $productRepository, Request $request, Client $client, EntityManagerInterface $entityManager): Response
    {
        // 1. Vérification de la signature
        if ($client->checkWebhooks($request, 'payment')) {

            $payload = json_decode($request->getContent(), true);
            if (!$payload) {
                return new Response('Invalid JSON', 400);
            }

            if ($payload['type'] === 'checkout.session.completed') {
                $session = $payload['data']['object'];
                $paymentId = $session['id'] ?? null;

                if ($paymentId) {
                    $pl = $entityManager->getRepository(ContratsPayments::class)->findOneBy(['paymentId' => $paymentId]);
                    if ($pl instanceof ContratsPayments && $pl->getState() !== "complete") {

                        // MAJ du paiement
                        $pl->setState("complete");
                        $pl->setValidateAt(new \DateTimeImmutable('now'));
                        $pl->setCard($client->paymentMethod($session['payment_intent']));



                        $contrat = $pl->getContrat();
                        $customer = $contrat->getCustomer();

                        $pdf = new PlPdf($kernel, $pl, $contrat);
                        $pdf->generate();
                        $content = $pdf->Output('S');
                        $tmpSigned = sys_get_temp_dir() . '/sign_' . uniqid() . '.pdf';
                        file_put_contents($tmpSigned, $content);

                        // On utilise UploadedFile pour simuler un upload propre pour VichUploader
                        $pl->setPaymentFile(new UploadedFile($tmpSigned, "confirmed-" . $pl->getId() . ".pdf", "application/pdf", null, true));
                        $pl->setUpdateAt(new \DateTimeImmutable('now'));
                        $entityManager->persist($pl);
                        $entityManager->flush();
                        $data = $sig->autoSignConfirmedPayment($pl);
                        // 1. Gestion du PDF SIGNÉ
                        $tmpSigned = sys_get_temp_dir() . '/sign_' . uniqid() . '.pdf';
                        $signedContent = file_get_contents($data);
                        file_put_contents($tmpSigned, $signedContent);

                        // On utilise UploadedFile pour simuler un upload propre pour VichUploader
                        $pl->setPaymentSignedFile(new UploadedFile($tmpSigned, "confirmed-certificate-" . $pl->getId() . ".pdf", "application/pdf", null, true));
                        $pl->setUpdateAt(new \DateTimeImmutable('now'));
                        $entityManager->persist($pl);
                        
                        // Update Reservation State if Accompte and Signed
                        if ($pl->getType() === 'accompte' && $contrat->isSigned()) {
                            $contrat->setReservationState('ready');
                            $entityManager->persist($contrat);

                            // Send email to Prestataire
                            $prestataire = $contrat->getPrestataire();
                            if ($prestataire) {
                                $dateStart = $contrat->getDateAt()->format('d/m/Y');
                                $dateEnd = $contrat->getEndAt()->format('d/m/Y');
                                
                                $mailer->send(
                                    $prestataire->getEmail(),
                                    $prestataire->getSurname() . ' ' . $prestataire->getName(),
                                    "Nouveau contrat attribué - " . $contrat->getNumReservation(),
                                    "mails/prestataire/new_contrat.twig",
                                    [
                                        'contrat' => $contrat,
                                        'prestataire' => $prestataire,
                                        'dateStart' => $dateStart,
                                        'dateEnd' => $dateEnd
                                    ]
                                );
                            }
                        }
                        
                        $entityManager->flush();

                        // --- ENVOI DES EMAILS ---
                        if ($customer) {
                            // 1. Détermination du sujet pour le CLIENT
                            $subjectCustomer = match($pl->getType()) {
                                'accompte'      => "[Ludikevent] Confirmation de votre acompte - #" . $contrat->getNumReservation(),
                                'caution'       => "[Ludikevent] Confirmation de votre caution - #" . $contrat->getNumReservation(),
                                'solde_partiel' => "[Ludikevent] Confirmation de votre versement partiel - #" . $contrat->getNumReservation(),
                                'solde'         => "[Ludikevent] Votre réservation est désormais soldée ! - #" . $contrat->getNumReservation(),
                                'etl_payment'   => "[Ludikevent] Confirmation de paiement (via Prestataire) - #" . $contrat->getNumReservation(),
                                default         => "[Ludikevent] Confirmation de paiement - #" . $contrat->getNumReservation(),
                            };

                            // 2. Envoi au CLIENT
                            $mailer->send(
                                $customer->getEmail(),
                                $customer->getSurname() . ' ' . $customer->getName(),
                                $subjectCustomer,
                                "mails/customer/accompte_confirmation.twig",
                                [
                                    'contrat' => $contrat,
                                    'payment' => $pl,
                                    'customer' => $customer,
                                    'reservationLink' => "https://reservation.ludikevent.fr" . $this->generateUrl('gestion_contrat_view', ['num' => $contrat->getNumReservation()])
                                ]
                            );

                            // 3. ENVOI NOTIFICATION INTERNE (Admin)
                            $subjectAdmin = match($pl->getType()) {
                                'accompte'      => "🔔 NOUVEL ACOMPTE : " . $customer->getSurname() . " (#" . $contrat->getNumReservation() . ")",
                                'caution'       => "🛡️ CAUTION DÉPOSÉE : " . $customer->getSurname() . " (#" . $contrat->getNumReservation() . ")",
                                'solde_partiel' => "💰 PAIEMENT PARTIEL : " . $customer->getSurname() . " (#" . $contrat->getNumReservation() . ")",
                                'solde'         => "✅ DOSSIER SOLDÉ : " . $customer->getSurname() . " (#" . $contrat->getNumReservation() . ")",
                                'etl_payment'   => "📱 PAIEMENT MOBILE (ETL) : " . $customer->getSurname() . " (#" . $contrat->getNumReservation() . ")",
                                default         => "💳 Nouveau paiement reçu - #" . $contrat->getNumReservation(),
                            };

                            $mailer->send(
                                'contact@ludikevent.fr',
                                'Ludikevent Admin',
                                $subjectAdmin,
                                "mails/customer/admin_confirmation.twig", // On peut réutiliser le même template ou en créer un spécifique admin
                                [
                                    'contrat' => $contrat,
                                    'payment' => $pl,
                                    'customer' => $customer,
                                    'isAdmin' => true, // Optionnel : pour afficher des infos admin dans le template
                                    'reservationLink' => $this->generateUrl('app_crm_contrats_view',['id'=>$contrat->getId()]) // Lien vers l'intranet admin
                                ]
                            );
                        }
                    }
                }
            }

            return new Response('Event Handled', 200);
        }

        return new Response('Invalid Signature', 400);
    }
}
