<?php


class PixSicredi
{

    private $clientId;
    private $clientSecret;
    private $urlToken;
    private $url;
    private $environment;
    private $base64;
    private $headers;
    private $fields;
    private $certificatePem;
    private $certificateKey;

    public function __construct($clientId, $clientSecret, $certificatePem, $certificateKey, $environment = 'production')
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->certificatePem = $certificatePem;
        $this->certificateKey = $certificateKey;

        $this->urlToken = 'https://api-pix.sicredi.com.br/oauth/token?grant_type=client_credentials&scope=cob.read+cob.write+pix.write+pix.read+webhook.read+webhook.write+payloadlocation.read+payloadlocation.write';
        $this->url = 'https://api-pix.sicredi.com.br';
        $this->environment = $environment;

        if ($environment == 'sandbox') {
            $this->urlToken = '';
            $this->url = '';
            $this->environment = $environment;
        }
    }

    protected function headers(array $headers)
    {
        if (!$headers) {
            return;
        }
        foreach ($headers as $k => $v) {
            $this->header($k, $v);
        }
    }

    protected function header(string $key, string $value)
    {
        if (!$key) {
            return;
        }
        $keys = filter_var($key, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $values = strip_tags($value);
        $this->headers[] = "{$keys}: {$values}";
    }

    protected function fields(array $fields, string $format = "json")
    {
        if ($format == "json") {
            $this->fields = (!empty($fields) ? json_encode($fields) : null);
            return;
        }
        if ($format == "query") {
            $this->fields = (!empty($fields) ? http_build_query($fields) : null);
            return;
        }
    }


    public function getTokenAccess()
    {

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->urlToken,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_HTTPHEADER => array(
                'Authorization: Basic ' . base64_encode($this->clientId . ':' . $this->clientSecret)
            ),
        ));

        return json_decode(curl_exec($curl));
    }

    public function registerPix(array $fields, $txtId = null)
    {
        $this->headers([
            "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
            "Content-Type"      => "application/json"
        ]);
        if ($this->environment == 'sandbox') {
            $this->headers([
                "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
                "Content-Type"      => "application/json"
            ]);
        }

        $this->fields($fields, 'json');

        $curl = curl_init("{$this->url}/api/v2/cob/{$txtId}");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_POSTFIELDS => $this->fields,
            CURLOPT_HTTPHEADER => ($this->headers),
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLINFO_HEADER_OUT => true
        ]);
        return json_decode(curl_exec($curl));
    }

    public function devolutionPix(array $fields, $e2eid = null, $id = null)
    {
        $this->headers([
            "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
            "Content-Type"      => "application/json"
        ]);
        if ($this->environment == 'sandbox') {
            $this->headers([
                "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
                "Content-Type"      => "application/json"
            ]);
        }

        $this->fields($fields, 'json');

        $curl = curl_init("{$this->url}/api/v2/pix/{$e2eid}/devolucao/{$id}");

        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_POSTFIELDS => $this->fields,
            CURLOPT_HTTPHEADER => ($this->headers),
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLINFO_HEADER_OUT => true
        ]);
        return json_decode(curl_exec($curl));
    }

    public function readPix($txtId)
    {
        $this->headers([
            "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
            "Content-Type"      => "application/json"
        ]);
        if ($this->environment == 'sandbox') {
            $this->headers([
                "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
                "Content-Type"      => "application/json"
            ]);
        }

        $curl = curl_init("{$this->url}/api/v2/cob/{$txtId}");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $this->fields,
            CURLOPT_HTTPHEADER => ($this->headers),
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLINFO_HEADER_OUT => true
        ]);

        return json_decode(curl_exec($curl));
    }

    public function readPixPeriodo($dataInicial, $dataFinal)
    {
        $this->headers([
            "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
            "Content-Type"      => "application/json"
        ]);
        if ($this->environment == 'sandbox') {
            $this->headers([
                "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
                "Content-Type"      => "application/json"
            ]);
        }

        $curl = curl_init("{$this->url}/api/v2/cob?inicio={$dataInicial}&fim={$dataFinal}");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $this->fields,
            CURLOPT_HTTPHEADER => ($this->headers),
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLINFO_HEADER_OUT => true
        ]);

        return json_decode(curl_exec($curl));
    }

    public function registerWebhook(array $fields, string $chavePix)
    {
        $this->headers([
            "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
            "Content-Type"      => "application/json"
        ]);
        if ($this->environment == 'sandbox') {
            $this->headers([
                "Authorization"     => "Bearer " . $this->getTokenAccess()->access_token,
                "Content-Type"      => "application/json"
            ]);
        }

        $this->fields($fields, 'json');

        $curl = curl_init("{$this->url}/api/v2/webhook/{$chavePix}");
        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_POSTFIELDS => $this->fields,
            CURLOPT_HTTPHEADER => ($this->headers),
            CURLOPT_SSLCERT => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificatePem),
            CURLOPT_SSLKEY => realpath(__DIR__ . '/../../arquivos/certificados/' . $this->certificateKey),
            CURLOPT_SSLCERTTYPE => 'PEM',
            CURLOPT_SSL_VERIFYPEER => true,
            CURLINFO_HEADER_OUT => true
        ]);
        return json_decode(curl_exec($curl));
    }
}
