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

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Payment;

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\Payment\Etransactions;
use CpCreation\VitiCore\Cart\Model\Payment\SogeCommerce;
use CpCreation\VitiCore\Cart\Repository\PaymentMethodRepository;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\SerializerInterface;

class SogeCommercePayment
{
    const METHOD = 'sogecommerce';
    const DEVISE = 978;

    private $paymentMethodRepository;
    private $serializer;
    private $request;
    private $router;
    private $paths;

    public function __construct(PaymentMethodRepository $paymentMethod,
        SerializerInterface $serializer,
        RequestStack $requestStack,
        array $paths,
        RouterInterface $router
    ) {

        $this->paymentMethodRepository = $paymentMethod;
        $this->serializer              = $serializer;
        $this->request                 = $requestStack;
        $this->router                  = $router;
        foreach ($paths as $key => $path) {
            if ($path['name'] === static::METHOD) {
                $this->paths[$key] = $path;
            }
        }
    }


    public function createData(HasPayment $payment)
    {

        $paymentMethod = $this->paymentMethodRepository->findOneBy(['method' => static::METHOD]);

        /** @var SogeCommerce $config */
        $config   = $this->serializer->denormalize($paymentMethod->getConfiguration(), SogeCommerce::class);
        $hmac     = $config->getKey();
        $hmacAlgo = $config->getHmacAlgo();

        $data['URL']                 = 'https://sogecommerce.societegenerale.eu/vads-payment/';
        $data['vads_action_mode']    = 'INTERACTIVE';
        $data['vads_amount']         = $payment->getTotal();
        $data['vads_ctx_mode']       = $config->getMode();
        $data['vads_currency']       = '978';
        $data['vads_page_action']    = 'PAYMENT';
        $data['vads_payment_config'] = 'SINGLE';
        $data['vads_threeds_mpi']    = 4;
        $data['vads_site_id']        = $config->getSiteId();
        $data['vads_trans_date']     = gmdate('YmdHis');
        $data['vads_trans_id']       = $payment->getToken();
        $data['vads_url_cancel']     = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['sogecommerce']['canceled'], [], true));//Annulé
        $data['vads_url_return']     = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['sogecommerce']['canceled'], [], true));;//Retour a la boutique
        $data['vads_url_success'] = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['sogecommerce']['done'], [], true));;//Paiement validé
        $data['vads_url_check'] = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['sogecommerce']['response_at'], [], true));;//Virement effectué
        $data['vads_version']    = 'V2';

        $msg = $data['vads_action_mode'].'+'.
               $data['vads_amount'].'+'.
               $data['vads_ctx_mode'].'+'.
               $data['vads_currency'].'+'.
               $data['vads_page_action'].'+'.
               $data['vads_payment_config'].'+'.
               $data['vads_site_id'].'+'.
               $data['vads_trans_date'].'+'.
               $data['vads_trans_id'].'+'.
               $data['vads_url_cancel'].'+'.
               $data['vads_url_check'].'+'.
               $data['vads_url_return'].'+'.
               $data['vads_url_success'].'+'.
               $data['vads_version'].'+'.
               $hmac;


        $data['signature'] = hash_hmac($hmacAlgo, $msg, $hmac);
        if ($hmacAlgo == 'sha256') {
            $data['signature'] = base64_encode(hash_hmac($hmacAlgo, $msg, $hmac, true));
        }

        return $data;
    }

    public
    function valid($response = null
    ) {
        if (isset($response['vads_hash']) && ($response['vads_auth_result'] == '00' || $response['vads_auth_result'] == '08' || $response['vads_auth_result'] == '000' || $response['vads_auth_result'] == '001')){
            $paymentMethod = $this->paymentMethodRepository->findOneBy(['method' => static::METHOD]);

            /** @var SogeCommerce $config */
            $config    = $this->serializer->denormalize($paymentMethod->getConfiguration(), SogeCommerce::class);
            $hmac      = $config->getKey();
            $hmacAlgo  = $config->getHmacAlgo();
            $signature = $response['signature'];

            ksort($response);

            $msg = '';

            foreach ($response as $nom => $valeur) {

                //Récupération des champs vads_
                if (substr($nom, 0, 5) == 'vads_') {

                    //Concaténation avec le séparateur "+"
                    $msg .= $valeur."+";
                }
            }

            $msg .= $hmac;

            $signatureNew = hash_hmac($hmacAlgo, $msg, $hmac);
            if ($hmacAlgo == 'sha256') {
                $signatureNew = base64_encode(hash_hmac($hmacAlgo, $msg, $hmac, true));
            }
            if ($signatureNew === $signature) {
                return true;
            }
        }

        return false;
    }
}
