<?php
/**
 * @author Colinet Julien
 */

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

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\PaymentProviderManager;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\AxeptaPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\CawlPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\EtransactionsPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\MoneticoPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\PayPlugPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\Sherlock2Payment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\SherlockPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\SogeCommercePayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment\SystemPayPayment;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\Payment\Sherlock;
use CpCreation\VitiCore\Cart\Repository\CartRepository;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use CpCreation\VitiCore\Payment\Repository\PaymentRepository;
use OnlinePayments\Sdk\Domain\GetHostedCheckoutResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MethodPaymentController extends AbstractController
{
    private $cartRepository;
    private $paymentRepository;
    private $contactRepository;
    private $paymentProviderManager;
    private $etransactionsPayment;
    private $moneticoPayment;
    private $systempay;
    private $sherlockPayment;
    private $sogeCommercePayment;
    private $axeptaPayment;
    private $sherlock2Payment;
    private $payPlugPayment;
    private $sherlockDir;
    private $translator;
    private $session;
    private $parameterBag;
    private $cawlPayment;

    public function __construct(
        CartRepository $cartRepository,
        PaymentRepository $paymentRepository,
        ContactRepository $contactRepository,
        PaymentProviderManager $paymentProviderManager,
        EtransactionsPayment $etransactionsPayment,
        array $sherlockDir,
        MoneticoPayment $moneticoPayment,
        SystemPayPayment $systempay,
        SherlockPayment $sherlockPayment,
        SogeCommercePayment $sogeCommercePayment,
        AxeptaPayment $axeptaPayment,
        Sherlock2Payment $sherlock2Payment,
        PayPlugPayment $payPlugPayment,
        TranslatorInterface $translator,
        SessionInterface $session,
        ParameterBagInterface $parameterBag,
        CawlPayment $cawlPayment,
    ) {
        $this->cartRepository         = $cartRepository;
        $this->paymentRepository      = $paymentRepository;
        $this->contactRepository      = $contactRepository;
        $this->paymentProviderManager = $paymentProviderManager;
        $this->etransactionsPayment   = $etransactionsPayment;
        $this->moneticoPayment        = $moneticoPayment;
        $this->systempay              = $systempay;
        $this->sherlockPayment        = $sherlockPayment;
        $this->sogeCommercePayment    = $sogeCommercePayment;
        $this->sherlockDir            = $sherlockDir;
        $this->translator             = $translator;
        $this->session                = $session;
        $this->axeptaPayment          = $axeptaPayment;
        $this->sherlock2Payment       = $sherlock2Payment;
        $this->payPlugPayment         = $payPlugPayment;
        $this->parameterBag           = $parameterBag;
        $this->cawlPayment            = $cawlPayment;
    }

    /**
     * @param Request $request
     * @param Cart    $cart
     * @Route("/paiement/{id}/check", name="payment_check")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCheckAction(Request $request,
        Cart $cart,
        SessionInterface $session
    ) {
        return $this->render(
            'payment/check.html.twig',
            [
                'classMenu' => 'black',
                'cart'      => $cart,
            ]
        );
    }

    /**
     * @param Request $request
     * @param Cart    $cart
     * @Route("/paiement/{id}/banktransfert", name="payment_banktransfert")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentBankTransfertAction(Request $request,
        Cart $cart,
        SessionInterface $session
    ) {
        return $this->render(
            'payment/banktransfert.html.twig',
            [
                'classMenu' => 'black',
                'cart'      => $cart,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/etransactions", name="payment_cb_etransactions")
     * @Route("/paiement/{id}/etransactions", name="payment_etransactions")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response|null
     */
    public
    function paymentEtransactionsAction(Request $request,
        HasPayment $payment
    ) {
        $data = $this->etransactionsPayment->createData($payment);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request $request
     * @Route("/paiement/cb/retour", name="payment_cb_return")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbReturnAction(Request $request
    ) {
        $code  = $request->query->get('Erreur');
        $ref   = $request->query->get('Ref');
        $error = null;
        $view  = "cb_return.html.twig";
        if ($code === '00000') {
            $msg = $this->translator->trans('shop.return.success');
            if ($this->session->get('payment') === "Payment") {
                $msg  = $this->translator->trans('payment.success');
                $view = "payment_return.html.twig";
            }
        } else {
            $msg   = $this->translator->trans('shop.return.echec');
            $error = $this->translator->trans('shop.return.error');
            if ($this->session->get('payment') === "Payment") {
                $msg   = $this->translator->trans('payment.echec');
                $error = $this->translator->trans('payment.error');
                $view  = "payment_return.html.twig";
            }
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cb_monetico", name="payment_cb_monetico")
     * @Route("/paiement/{id}/cb_monetico", name="payment_monetico")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbMoneticoAction(Request $request,
        HasPayment $payment
    ) {
        $data = $this->moneticoPayment->createData($payment);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request $request
     * @Route("/paiement/cb_monetico/retour/erreur", name="payment_cb_monetico_return_error")
     * @Route("/paiement/cb_monetico/retour/erreur", name="payment_monetico_return_error")
     * @Route("/paiement/systempay/retour/erreur", name="payment_systempay_return_error")
     * @Route("/paiement/axepta/retour/erreur", name="payment_axepta_return_error")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbReturnErrorAction(Request $request
    ) {
        $view  = "cb_return.html.twig";
        $msg   = $this->translator->trans('shop.return.echec');
        $error = $this->translator->trans('shop.return.error');
        if ($this->session->get('payment') === "Payment") {
            $msg   = $this->translator->trans('payment.echec');
            $error = $this->translator->trans('payment.error');
            $view  = "payment_return.html.twig";
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

    /**
     * @param Request $request
     * @Route("/paiement/cb_monetico/retour/success", name="payment_cb_monetico_return_success")
     * @Route("/paiement/cb_monetico/retour/success", name="payment_monetico_return_success")
     * @Route("/paiement/systempay/retour/success", name="payment_systempay_return_success")
     * @Route("/paiement/axepta/retour/success", name="payment_axepta_return_success")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbReturnSuccessAction(Request $request
    ) {
        $error = null;
        $msg   = $this->translator->trans('shop.return.success');
        $view  = "cb_return.html.twig";
        if ($this->session->get('payment') === "Payment") {
            $msg  = $this->translator->trans('payment.success');
            $view = "payment_return.html.twig";
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/sherlock", name="payment_cb_sherlock")
     * @Route("/paiement/{id}/sherlock", name="payment_sherlock")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response|null
     */
    public
    function paymentSherlockAction(Request $request,
        HasPayment $payment
    ) {
        $data     = [];
        $params   = $this->sherlockPayment->createData($payment);
        $path_bin = $this->sherlockDir['sherlock_request_path'];
        $result   = exec("$path_bin $params");
        $doc      = new \DOMDocument();
        $doc->loadHTML($result);
        $form        = $doc->getElementsByTagName('form');
        $formString  = $form->item(0)->ownerDocument->saveXML($form->item(0));
        $data['URL'] = $form->item(0)->attributes->getNamedItem('action')->textContent;
        $inputs      = $form->item(0)->getElementsByTagName('input');
        for ($i = 0; $i < $inputs->length; $i++) {
            if ($inputs->item($i)->attributes->getNamedItem('name')->textContent === 'DATA') {
                $data[$inputs->item($i)->attributes->getNamedItem('name')->textContent] = $inputs->item($i)->attributes->getNamedItem('value')->textContent;
            }
        }
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cb_systempay", name="payment_cb_systempay")
     * @Route("/paiement/{id}/cb_systempay", name="payment_systempay")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function paymentSystemPay(Request $request, HasPayment $payment)
    {
        $data = $this->systempay->createData($payment);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/cb.html.twig',
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cb_sogecommerce", name="payment_cb_sogecommerce")
     * @Route("/paiement/{id}/cb_sogecommerce", name="payment_sogecommerce")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */

    public
    function paymentCbSogeCommerceAction(Request $request,
        HasPayment $payment
    ) {
        $data = $this->sogeCommercePayment->createData($payment);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }


    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cb_axepta", name="payment_cb_axepta")
     * @Route("/paiement/{id}/cb_axepta", name="payment_axepta")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbAxeptaAction(Request $request,
        HasPayment $payment
    ) {

        $data = $this->axeptaPayment->createData($payment);
        $file     = "log_axepta.txt";
        $fullpath = $this->parameterBag->get('kernel.project_dir').$file;
        $log = fopen($fullpath, "w") or die ("Unable to open file!");
        $timestamp = date("Y-m-d H:i:s");
        fwrite($log, "[$timestamp] - $data" . PHP_EOL);
        fclose($log);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cb_sherlock2", name="payment_cb_sherlock2")
     * @Route("/paiement/{id}/cb_sherlock2", name="payment_sherlock2")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentCbSherlock2Action(Request $request,
        HasPayment $payment
    ) {

        $data = $this->sherlock2Payment->createData($payment);
        $view = "cb.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }


    /**
     * @param Request $request
     * @Route("/paiement/sherlock2/retour", name="payment_sherlock2_normal")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentSherlock2ReturnAction(Request $request
    ) {
        $response = $request->request->all();
        $data     = $this->sherlock2Payment->valid($response);
        $error    = "";
        $view     = "cb_return.html.twig";

        if ($data["Valid"] == true) {
            $msg = $this->translator->trans('shop.return.success');
            if ($this->session->get('payment') === "Payment") {
                $msg  = $this->translator->trans('payment.success');
                $view = "payment_return.html.twig";
            }
        } else {
            $msg   = $this->translator->trans('shop.return.echec');
            $error = $this->translator->trans('shop.return.error');
            if ($this->session->get('payment') === "Payment") {
                $msg   = $this->translator->trans('payment.echec');
                $error = $this->translator->trans('payment.error');
                $view  = "payment_return.html.twig";
            }
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/payplug", name="payment_payplug")
     * @ParamConverter("payment", converter="haspayment_converter")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentPayPlugAction(Request $request,
        HasPayment $payment
    ) {
        $view = "cb_payplug.html.twig";
        $form = $this->createFormBuilder()
                     ->getForm();
        // ...
        //$this->session->set('payment', 'Cart');
        /*if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }*/

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'form'      => $form->createView(),
                'cart'      => $payment,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/payplug/{id}/process", name="payment_payplug_process")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentPayPlugProcessAction(Request $request,
        HasPayment $payment
    ) {
        $data = $this->payPlugPayment->createData($payment);

        return $this->redirect($data->hosted_payment->payment_url);
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/payplug/success", name="payment_payplug_success")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentPayPlugSuccessAction(Request $request
    ) {
        $error = "";
        $view  = "cb_return.html.twig";
        $msg   = $this->translator->trans('shop.return.success');
        if ($this->session->get('payment') === "Payment") {
            $msg  = $this->translator->trans('payment.success');
            $view = "payment_return.html.twig";
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/payplug/error", name="payment_payplug_return_error")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public
    function paymentPayPlugErrorAction(Request $request
    ) {
        $error = "";
        $view  = "cb_return.html.twig";
        $msg   = $this->translator->trans('shop.return.echec');
        $error = $this->translator->trans('shop.return.error');
        if ($this->session->get('payment') === "Payment") {
            $msg   = $this->translator->trans('payment.echec');
            $error = $this->translator->trans('payment.error');
            $view  = "payment_return.html.twig";
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }
    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/{id}/cawl", name="payment_cawl")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function paymentCawlAction(Request $request,HasPayment $payment){
        $data = $this->cawlPayment->createData($payment);
        $view = "cb_cawl.html.twig";
        $this->session->set('payment', 'Cart');
        if ($payment instanceof Payment) {
            $view = "payment.html.twig";
            $this->session->set('payment', 'Payment');
        }

        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'cart'      => $payment,
                'data'      => $data,
            ]
        );
    }

    /**
     * @param Request    $request
     * @param HasPayment $payment
     * @Route("/paiement/cawl/return", name="payment_cawl_return")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function paymentCawlReturnAction(Request $request){
        $returnData = $request->query->all();
        /** @var GetHostedCheckoutResponse $status */
        $status = $this->cawlPayment->getStatus($returnData['hostedCheckoutId']);
        $error = "";
        $view  = "cb_return.html.twig";
        if($status->status !== "PAYMENT_CREATED" && $status->status !== "IN_PROGRESS"){
            $msg   = $this->translator->trans('shop.return.echec');
        } else {
            $msg   = $this->translator->trans('shop.return.success');
        }
        if ($this->session->get('payment') === "Payment") {
            if($status['status'] !== "PAYMENT_CREATED" && $status['status'] !== "IN_PROGRESS"){
                $msg   = $this->translator->trans('payment.echec');
                $error = $this->translator->trans('payment.error');
            } else {
                $msg   = $this->translator->trans('payment.success');
                $error   = $this->translator->trans('payment.success');
            }
            $view  = "payment_return.html.twig";
        }
        return $this->render(
            'payment/'.$view,
            [
                'classMenu' => 'black',
                'msg'       => $msg,
                'error'     => $error,
            ]
        );
    }

}
