<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Site\PaymentType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\PaymentProviderManager;
use CpCreation\VitiCore\Cart\Repository\PaymentMethodRepository;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use CpCreation\VitiCore\Payment\Repository\PaymentRepository;
use CpCreation\VitiCore\Shop\Repository\ShopConfigRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

final class PaymentController extends AbstractController
{
    public function __construct(
        private readonly PaymentRepository $paymentRepository,
        private readonly PaymentProviderManager $paymentProviderManager,
        private readonly ContactRepository $contactRepository,
        private readonly PaymentMethodRepository $paymentMethodRepository,
        private readonly ShopConfigRepository $shopConfigRepository,
    ) {
    }

    public function index(Request $request): Response
    {
        $form = $this->createForm(PaymentType::class);
        $form->handleRequest($request);

        $paymentMethod = $this->paymentMethodRepository->findByDefaultForPaymentOnline();
        $config = $this->shopConfigRepository->findOne();

        if (!$paymentMethod) {
            throw new \RuntimeException("Méthode de paiement inexistante pour le système de paiement en ligne");
        }

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                /** @var Payment $payment */
                $payment = $form->getData();

                $this->paymentRepository->save($payment);
                $contact = $this->contactRepository->findOne();

                return $this->paymentProviderManager->createPaymentProviderManager($contact, $payment);
            }

            $this->addFlash('error', 'Le formulaire n\'est pas rempli correctement !');
        }

        return $this->render('payment.html.twig', [
            'classMenu' => 'black',
            'form' => $form->createView(),
            'paymentMethod' => $paymentMethod,
            'config' => $config,
        ]);
    }

    public function item(Request $request, Payment $payment): Response
    {
        $form = $this->createForm(PaymentType::class, $payment);
        $form->handleRequest($request);

        $paymentMethod = $this->paymentMethodRepository->findByDefaultForPaymentOnline();
        $config = $this->shopConfigRepository->findOne();

        return $this->render('payment.html.twig', [
            'classMenu' => 'black',
            'form' => $form->createView(),
            'paymentMethod' => $paymentMethod,
            'config' => $config,
        ]);
    }
}
