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

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

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Cart\Model\Payment\Etransactions;
use CpCreation\VitiCore\Cart\Model\Payment\PayPlugModel;
use CpCreation\VitiCore\Cart\Repository\PaymentMethodRepository;
use League\ISO3166\ISO3166;
use Payplug\Resource\APIResource;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Payplug\Payplug;
use Payplug\Resource\Payment;
use Payplug\Notification;
use ReflectionClass;

class PayPlugPayment
{
    const METHOD     = 'payplug';
    const DEVISE     = 978;
    const CURRENCY   = 'EUR';
    const PBX_RETOUR = 'Mt:M;Ref:R;Auto:A;Appel:T;Abo:B;Erreur:E;Trans:S;Pays:Y;Heure:Q;3DSecureVersion:v;Authentification:c,3DSecure:G;Carte4:j;Signature:K;Ip:I';

    private $paymentMethodRepository;
    private $serializer;
    private $router;
    private $paths;
    private $request;
    private $payplug;
    private $payplugPayment;
    private $payment;
    private $config;
    private $notify;
    private $dataArray;

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

        $paymentMethod = $this->paymentMethodRepository->findOneBy(['method' => static::METHOD]);
        if($paymentMethod && $paymentMethod->getConfiguration()){
            $this->config  = $this->serializer->denormalize($paymentMethod->getConfiguration(), PayPlugModel::class);
            $this->payplug = new PayPlug($this->config->getPrivateKey());
        }
        $this->notify = new Notification();
        $this->dataArray = [];

        foreach ($paths as $key => $path) {
            if ($path['name'] === static::METHOD) {
                $this->paths[$key] = $path;
            }
        }
    }

    public function createData(HasPayment $payment)
    {
        $this->payplug::init([
            'secretKey'  => $this->config->getPrivateKey(),
            'apiVersion' => "2019-08-06",
        ]);
        $this->dataArray = [
            'amount'           => $payment->getTotal(),
            'currency'         => self::CURRENCY,
            'save_card'        => false,
            'billing'          => [
                'title'               => null,
                "first_name"          => $payment->getFirstname(),
                "last_name"           => $payment->getLastname(),
                "mobile_phone_number" => null,
                "email"               => $payment->getEmail(),
                "address1"            => $payment->getStreet(),
                "postcode"            => $payment->getPostalCode(),
                "city"                => $payment->getCity(),
                "country"             => $payment->getCountry(),
            ],
            'shipping'         => [
                'title'               => null,
                "first_name"          => $payment->getFirstname(),
                "last_name"           => $payment->getLastname(),
                "mobile_phone_number" => null,
                "email"               => $payment->getEmail(),
                "address1"            => $payment->getStreet(),
                "postcode"            => $payment->getPostalCode(),
                "city"                => $payment->getCity(),
                "country"             => $payment->getCountry(),
            ],
            'hosted_payment'   => [
                'return_url' => $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['payplug']['done'], [], true)),
                'cancel_url' => $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['payplug']['refused'], [], true)),
            ],
            'notification_url' => $this->request->getCurrentRequest()->getUriForPath($this->router->generate($this->paths['payplug']['response_at'], [], true)),
            'metadata' => [
                'transaction_id' => $payment->getToken(),
            ]
        ];

        $this->payplugPayment = Payment::create($this->dataArray);
        return $this->payplugPayment;
    }

    public function valid($paymentArray)
    {
        $resourcePayment = Payment::retrieve($paymentArray['id'],$this->payplug);
        // Utilisation de la réflexion pour accéder à la propriété protégée _attributes
        $reflectionClass = new ReflectionClass(get_class($resourcePayment));
        $property = $reflectionClass->getProperty('_attributes');
        $property->setAccessible(true);

        // Obtention de la valeur de la propriété protégée
        $attributes = $property->getValue($resourcePayment);

        return $attributes;
    }
}
