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

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

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\SherlockService;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;

class SherlockPayment
{
    const METHOD = 'sherlock';

    private $router;
    private $paths;
    private $request;
    private $sherlockFinder;

    public function __construct(RouterInterface $router,
        RequestStack $requestStack,
        array $paths,
        SherlockService $sherlockFinder
    ) {
        $this->router         = $router;
        $this->request        = $requestStack;
        $this->sherlockFinder = $sherlockFinder;
        foreach ($paths as $key => $path) {
            if ($path['name'] === static::METHOD) {
                $this->paths[$key] = $path;
            }
        }
    }

    /**
     * @param HasPayment $payment
     * @return string
     */
    public function createData(HasPayment $payment)
    {

        $certif         = $this->sherlockFinder->getFileContent("certif");
        $parmcom_client = $this->sherlockFinder->getFileContent("client");
        $pathfilePath   = $this->sherlockFinder->getFileInfos("pathfile", 'pathname');
        $infos_certificat = explode("!", "$certif");
        $parmcom          = explode("!", "$parmcom_client");
        $params           = " merchant_id=".$infos_certificat[1];
        $params           .= " merchant_country=".$infos_certificat[3];
        $params           .= " amount=".$payment->getTotal();
        $params .= " currency_code=".$parmcom[7];
        $params .= " pathfile=".$pathfilePath;
        $params .= " caddie=".$payment->getToken();

        return $params;
    }

    public function valid($response = null)
    {
        if ($response) {
            $code          = $response[1];
            $bank_response_code = $response[18];
            if ($code == "0" && $bank_response_code == "00") {
                return true;
            }
        }

        return false;
    }
}
