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

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

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

class SystemPayPayment
{
    const METHOD = 'systempay';
    const DEVISE = 978;

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

    public function __construct(PaymentMethodRepository $paymentMethod,
        SerializerInterface $serializer,
        RouterInterface $router,
        RequestStack $requestStack,
        $paths
    ) {
        $this->router                  = $router;
        $this->request                 = $requestStack;
        $this->paths                   = $paths;
        $this->paymentMethodRepository = $paymentMethod;
        $this->serializer              = $serializer;
    }


    public function createData(HasPayment $payment)
    {
        $paymentMethod = $this->paymentMethodRepository->findOneBy(['method' => static::METHOD]);

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

        $data['URL']                   = 'https://paiement.systempay.fr/vads-payment/';
        $data['vads_action_mode']      = 'INTERACTIVE';
        $data['vads_amount']           = $payment->getTotal();
        $data['vads_ctx_mode']         = $config->getMode();
        $data['vads_currency']         = self::DEVISE;
        $data['vads_cust_address']     = $payment->getStreet();
        $data['vads_cust_zip']         = $payment->getPostalCode();
        $data['vads_cust_city']        = $payment->getCity();
        $data['vads_cust_country']     = $payment->getCountry();
        $data['vads_cust_email']       = $payment->getEmail();
        $data['vads_cust_cell_phone '] = $payment->getPhone();
        $data['vads_cust_first_name']  = $payment->getFirstname();
        $data['vads_cust_last_name']   = $payment->getLastname();
        if ($payment->getCompany()) {
            $data['vads_cust_status']     = 'COMPANY';
            $data['vads_cust_legal_name'] = $payment->getCompany();
        } else {
            $data['vads_cust_status'] = '';
            $data['vads_cust_status'] = 'PRIVATE';
        }
        $data['vads_order_id']       = $payment->getToken();
        $data['vads_page_action']    = 'PAYMENT';
        $data['vads_payment_config'] = 'SINGLE';
        $data['vads_site_id']        = $config->getSiteId();
        $data['vads_threeds_mpi']    = 4;
        $data['vads_trans_date']     = gmdate('YmdHis');
        $data['vads_trans_id']       = $payment->getToken();
        $data['vads_version']        = 'V2';
        $data['vads_url_cancel']     = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['systempay']['refused'], [], true));//Annulé
        $data['vads_url_return']     = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['systempay']['refused'], [], true));;//Retour a la boutique
        $data['vads_url_success']    = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['systempay']['done'], [], true));;//Paiement validé
        $data['vads_url_check']      = $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['systempay']['response_at'], [], true));

        ksort($data);
        $msg = '';
        foreach ($data as $key => $item) {
            if ($key != 'URL') {
                $msg .= $item.'+';
            }

        }
        $msg .= $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 SystemPay $config */
            $config    = $this->serializer->denormalize($paymentMethod->getConfiguration(), SystemPay::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;
    }
}
