<?php

namespace App\Controller;

use App\Entity\EFlex;
use App\Entity\EFlexLine;
use App\Service\MailerService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

class EFlexProcessController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $em,
        private MailerService $mailer,
        private Environment $twig,
    ) {
    }

    #[Route('/eflex/verify/{id}', name: 'app_eflex_verify', requirements: ['id' => '\d+'])]
    public function verify(int $id, Request $request): Response
    {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        $customer = $eflex->getCustomer();
        $session = $request->getSession();
        $error = null;

        // Verification code
        if ($request->isMethod('POST')) {
            $code = $request->request->getString('code');
            $storedCode = $session->get('eflex_code_'.$id);
            $expires = $session->get('eflex_code_expires_'.$id, 0);

            if (time() > $expires) {
                $error = 'Code expire. Veuillez en demander un nouveau.';
            } elseif ($code !== $storedCode) {
                $error = 'Code incorrect.';
            } else {
                $session->set('eflex_verified_'.$id, true);

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

        // Envoyer un code si pas encore fait
        if (null === $session->get('eflex_code_'.$id) && null !== $customer->getEmail()) {
            $code = str_pad((string) random_int(0, 999999), 6, '0', \STR_PAD_LEFT);
            $session->set('eflex_code_'.$id, $code);
            $session->set('eflex_code_expires_'.$id, time() + 900);

            $this->mailer->sendEmail(
                $customer->getEmail(),
                'Code de verification - E-Flex '.$eflex->getReference(),
                $this->twig->render('emails/eflex_verify_code.html.twig', [
                    'customer' => $customer,
                    'code' => $code,
                ]),
                null,
                null,
                false,
            );
        }

        return $this->render('eflex/verify.html.twig', [
            'eflex' => $eflex,
            'customer' => $customer,
            'error' => $error,
        ]);
    }

    #[Route('/eflex/verify/{id}/resend', name: 'app_eflex_resend_code', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function resendCode(int $id, Request $request): Response
    {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        $customer = $eflex->getCustomer();
        $session = $request->getSession();

        if (null !== $customer->getEmail()) {
            $code = str_pad((string) random_int(0, 999999), 6, '0', \STR_PAD_LEFT);
            $session->set('eflex_code_'.$id, $code);
            $session->set('eflex_code_expires_'.$id, time() + 900);

            $this->mailer->sendEmail(
                $customer->getEmail(),
                'Nouveau code - E-Flex '.$eflex->getReference(),
                $this->twig->render('emails/eflex_verify_code.html.twig', [
                    'customer' => $customer,
                    'code' => $code,
                ]),
                null,
                null,
                false,
            );
        }

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

    #[Route('/eflex/process/{id}', name: 'app_eflex_process', requirements: ['id' => '\d+'])]
    public function process(int $id, Request $request): Response
    {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        $session = $request->getSession();
        if (!$session->get('eflex_verified_'.$eflex->getId(), false)) {
            return $this->redirectToRoute('app_eflex_verify', ['id' => $id]);
        }

        return $this->render('eflex/process.html.twig', [
            'eflex' => $eflex,
            'customer' => $eflex->getCustomer(),
        ]);
    }

    #[Route('/eflex/sign/{id}', name: 'app_eflex_sign', requirements: ['id' => '\d+'])]
    public function sign(
        int $id,
        \App\Service\DocuSealService $docuSeal,
        #[Autowire(env: 'DOCUSEAL_URL')] string $docuSealUrl = '',
    ): Response {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex || null === $eflex->getSubmissionId()) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        // @codeCoverageIgnoreStart
        $slug = $docuSeal->getSubmitterSlug((int) $eflex->getSubmissionId());
        if (null !== $slug) {
            return $this->redirect(rtrim($docuSealUrl, '/').'/s/'.$slug);
        }
        // @codeCoverageIgnoreEnd

        throw $this->createNotFoundException('Lien de signature introuvable.');
    }

    #[Route('/eflex/signed/{id}', name: 'app_eflex_signed', requirements: ['id' => '\d+'])]
    public function signed(int $id, Request $request): Response
    {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        return $this->render('eflex/signed.html.twig', [
            'eflex' => $eflex,
            'customer' => $eflex->getCustomer(),
        ]);
    }

    /**
     * Page de configuration SEPA pour E-Flex.
     */
    #[Route('/eflex/setup-payment/{id}', name: 'app_eflex_setup_payment', requirements: ['id' => '\d+'])]
    public function setupPayment(
        int $id,
        Request $request,
        #[Autowire(env: 'STRIPE_SK')] string $stripeSk = '',
        #[Autowire(env: 'STRIPE_PK')] string $stripePk = '',
    ): Response {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        $session = $request->getSession();
        if (!$session->get('eflex_verified_'.$eflex->getId(), false)) {
            return $this->redirectToRoute('app_eflex_verify', ['id' => $id]);
        }

        // Si SEPA deja configure, afficher la page de confirmation
        if (null !== $eflex->getStripePaymentMethodId()) {
            return $this->render('eflex/setup_payment_done.html.twig', [
                'eflex' => $eflex,
                'customer' => $eflex->getCustomer(),
            ]);
        }

        if (!\in_array($eflex->getState(), [EFlex::STATE_ACTIVE, EFlex::STATE_PENDING_SETUP], true)) {
            return $this->redirectToRoute('app_eflex_process', ['id' => $id]);
        }

        $customer = $eflex->getCustomer();

        // @codeCoverageIgnoreStart
        \Stripe\Stripe::setApiKey($stripeSk);

        $stripeCustomerId = $eflex->getStripeCustomerId() ?? $customer->getStripeCustomerId();
        if (null === $stripeCustomerId) {
            $stripeCustomer = \Stripe\Customer::create([
                'email' => $customer->getEmail(),
                'name' => $customer->getFullName(),
            ]);
            $stripeCustomerId = $stripeCustomer->id;
            $customer->setStripeCustomerId($stripeCustomerId);
            $eflex->setStripeCustomerId($stripeCustomerId);
            $this->em->flush();
        }

        $setupIntent = \Stripe\SetupIntent::create([
            'customer' => $stripeCustomerId,
            'payment_method_types' => ['sepa_debit'],
            'metadata' => ['eflex_id' => (string) $eflex->getId()],
        ]);
        // @codeCoverageIgnoreEnd

        return $this->render('eflex/setup_payment.html.twig', [
            'eflex' => $eflex,
            'customer' => $customer,
            'clientSecret' => $setupIntent->client_secret,
            'stripePk' => $stripePk,
        ]);
    }

    #[Route('/eflex/setup-payment/{id}/confirm', name: 'app_eflex_setup_payment_confirm', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function setupPaymentConfirm(
        int $id,
        Request $request,
        #[Autowire(env: 'STRIPE_SK')] string $stripeSk = '',
    ): Response {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            return new JsonResponse(['error' => 'E-Flex introuvable'], Response::HTTP_NOT_FOUND);
        }

        $session = $request->getSession();
        if (!$session->get('eflex_verified_'.$eflex->getId(), false)) {
            return new JsonResponse(['error' => 'Non autorise'], Response::HTTP_FORBIDDEN);
        }

        $data = json_decode($request->getContent(), true);
        $paymentMethodId = $data['payment_method'] ?? null;

        if (null === $paymentMethodId) {
            return new JsonResponse(['error' => 'payment_method manquant'], Response::HTTP_BAD_REQUEST);
        }

        // @codeCoverageIgnoreStart
        try {
            \Stripe\Stripe::setApiKey($stripeSk);

            $stripeCustomerId = $eflex->getStripeCustomerId();
            $pm = \Stripe\PaymentMethod::retrieve($paymentMethodId);
            $pm->attach(['customer' => $stripeCustomerId]);
            \Stripe\Customer::update($stripeCustomerId, [
                'invoice_settings' => ['default_payment_method' => $paymentMethodId],
            ]);

            $sepa = $pm->sepa_debit ?? null;
            if (null !== $sepa) {
                $eflex->setStripeSepaLast4($sepa->last4 ?? null);
                $eflex->setStripeSepaBankName($sepa->bank_code ?? null);
                $eflex->setStripeSepaCountry($sepa->country ?? null);
            }
        } catch (\Throwable $e) {
            return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        // @codeCoverageIgnoreEnd

        $eflex->setStripePaymentMethodId($paymentMethodId);
        $eflex->setState(EFlex::STATE_ACTIVE);
        $this->em->flush();

        return new JsonResponse(['status' => 'ok']);
    }

    /**
     * Paiement CB pour une echeance E-Flex via Stripe Checkout.
     */
    #[Route('/eflex/pay/{id}/{lineId}', name: 'app_eflex_pay', requirements: ['id' => '\d+', 'lineId' => '\d+'])]
    public function pay(
        int $id,
        int $lineId,
        Request $request,
        #[Autowire(env: 'STRIPE_SK')] string $stripeSk = '',
    ): Response {
        $eflex = $this->em->getRepository(EFlex::class)->find($id);
        if (null === $eflex) {
            throw $this->createNotFoundException('E-Flex introuvable.');
        }

        $session = $request->getSession();
        if (!$session->get('eflex_verified_'.$eflex->getId(), false)) {
            return $this->redirectToRoute('app_eflex_verify', ['id' => $id]);
        }

        $line = $this->em->getRepository(EFlexLine::class)->find($lineId);
        if (null === $line || $line->getEflex()->getId() !== $eflex->getId()) {
            throw $this->createNotFoundException('Echeance introuvable.');
        }

        if (EFlexLine::STATE_OK === $line->getState()) {
            return $this->redirectToRoute('app_eflex_process', ['id' => $id]);
        }

        // @codeCoverageIgnoreStart
        \Stripe\Stripe::setApiKey($stripeSk);

        $customer = $eflex->getCustomer();

        // Creer le customer Stripe si besoin
        $stripeCustomerId = $eflex->getStripeCustomerId() ?? $customer->getStripeCustomerId();
        if (null === $stripeCustomerId) {
            $stripeCustomer = \Stripe\Customer::create([
                'email' => $customer->getEmail(),
                'name' => $customer->getFullName(),
            ]);
            $stripeCustomerId = $stripeCustomer->id;
            $customer->setStripeCustomerId($stripeCustomerId);
            $eflex->setStripeCustomerId($stripeCustomerId);
            $this->em->flush();
        }

        $successUrl = $this->generateUrl('app_eflex_process', ['id' => $id], UrlGeneratorInterface::ABSOLUTE_URL);
        $cancelUrl = $successUrl;

        $checkoutSession = \Stripe\Checkout\Session::create([
            'mode' => 'payment',
            'payment_method_types' => ['card'],
            'customer' => $stripeCustomerId,
            'line_items' => [[
                'price_data' => [
                    'currency' => 'eur',
                    'unit_amount' => (int) round((float) $line->getAmount() * 100),
                    'product_data' => [
                        'name' => $line->getLabel().' - '.$eflex->getReference(),
                    ],
                ],
                'quantity' => 1,
            ]],
            'payment_intent_data' => [
                'setup_future_usage' => 'off_session',
                'metadata' => [
                    'eflex_id' => (string) $eflex->getId(),
                    'eflex_line_id' => (string) $line->getId(),
                    'position' => (string) $line->getPosition(),
                    'reference' => $eflex->getReference(),
                ],
            ],
            'success_url' => $successUrl,
            'cancel_url' => $cancelUrl,
        ]);

        return $this->redirect($checkoutSession->url);
        // @codeCoverageIgnoreEnd
    }
}
