<?php


namespace App\Util;

use App\Entity\Model\Empresa;
use Exception;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordToken;

class RestApiFunciones
{

    public function getEmisor(&$error)
    {
        $error = false;

        try {
            $data = '{"ruc":"' . $this->ruc . '","fecha":"' . $this->fecha . '","secuencia":' . $this->secuencia . ',"ptoemision":"' . $this->ptoemision . '","codestab":"' . $this->codestab . '"}';

            $client = new \GuzzleHttp\Client();

            $response = $client->request('POST', $this->url . "rest/facturas/claveacceso", [
                'body' => $data,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'ShaRaPp150108.&svycar']
            ]);


            if ($response->getStatusCode() == 200) {
                $body = $response->getBody();
                $obj = json_decode($body);
                $this->claveAcceso = $obj->claveacceso;
                return $obj;
            }

            $error = true;
            return $response->getBody();


        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        }

    }

    public static function validarPasswordFirma(&$error, $ruc, $url)
    {
        $error = false;

        try {

            $headers = array(
                'Accept' => 'application/json',
                'User-Agent' => 'sharafacphp/1.0',
                //'Content-Type' => 'application/xml',
                'Authorization' => 'sHaRa150108&X' . $ruc);

            $client = HttpClient::create(['headers' => $headers]);

            $response = $client->request('POST', $url . "caducafirma.php", [
                'headers' => $headers,
                'body' => '',
            ]);

            if ($response->getStatusCode() == 200) {
                $body = $response->getContent();
                $obj = json_decode($body);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                    return $obj->message;
                }
                return $obj;
            }

            $error = true;
            return $response->getContent();

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {

        }
    }

    public static function enviarComprobanteCola(&$error, $tercero, $enviarmail, $usuarioid, $xml, $clave, $url, $modulo)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $url . 'envio/clave');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $clave,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'xml' => $xml,
                'tercero' => $tercero,
                'enviarmail' => $enviarmail,
                'usuarioid' => $usuarioid,
                'modulo' => $modulo,
            ];
            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }

    }

    public static function enviarComprobante(&$error, $xml, $clave, $url)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $url . 'envio.php');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $clave,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'xml' => base64_encode($xml)
            ];
            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }

    }

    public function enviarComprobanteFacope(&$error, $tercero, $enviarmail, $usuarioid, $xml)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $this->url . 'envio/clave');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $this->claveAcceso,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'xml' => $xml,
                'tercero' => $tercero,
                'enviarmail' => $enviarmail,
                'usuarioid' => $usuarioid,
                'modulo' => 'facope',
            ];
            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }

    }

    public function enviarComprobanteRetope(&$error, $tercero, $enviarmail, $usuarioid, $xml)
    {
        $error = false;

        /*try {
            $headers = array('Accept' => 'application/json',
                'Content-Type' => 'application/xml',
                'authorization' => 'sHaRa150108&X' . $this->claveAcceso);

            //$response = Unirest\Request::post($this->url."rest/facturas/colaphp", $headers, $xml);

            //$data = '{"ruc":"' . $this->ruc . '","fecha":"' . $this->fecha . '","secuencia":' . $this->secuencia . ',"ptoemision":"' . $this->ptoemision . '","codestab":"' . $this->codestab . '"}';

            $client = new \GuzzleHttp\Client();

            $response = $client->request('POST', $this->url . "api.php", [
                'body' => $xml,
                'headers' => $headers
            ]);

            if ($response->getStatusCode() == 200) {
                $body = $response->getBody();
                $obj = json_decode($body);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                    return $obj->message;
                }
                return $obj;
            }

            $error = true;
            return $response->getBody();

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        }
        */

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $this->url . 'envio/clave');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $this->claveAcceso,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'xml' => $xml,
                'tercero' => $tercero,
                'enviarmail' => $enviarmail,
                'usuarioid' => $usuarioid,
                'modulo' => 'retope',

            ];
            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }

    }

    public function enviarDatos(&$error, $ruc, $json, $pathFirma = null, $rutaLogo = null, $extensionLogo)
    {
        $error = false;

        try {

            $headers = array('Accept' => 'application/json',
                'User-Agent' => 'sharafacphp/1.0',
                //'Content-Type' => 'application/xml',
                'authorization' => 'ShaRaPp150108.XsvycarX' . $ruc);

            //$client = new \GuzzleHttp\Client();

            $firmaLogo = [
                [
                    'name' => 'data',
                    'contents' => $json
                ]
            ];

            if ($pathFirma != null) {
                $firmaLogo[] = [
                    /*'name' => 'firma',
                    'contents' => file_get_contents($pathFirma),
                    'filename' => $ruc,
                    */
                    //'headers' => [
                    //    'Content-Length:' => filesize($pathFirma)
                    //]

                    'firma' => DataPart::fromPath($pathFirma),
                ];
            }

            if ($rutaLogo != null) {
                $firmaLogo[] = [
                    /*'name' => 'logo',
                    'contents' => file_get_contents($rutaLogo),
                    'filename' => "logo_" . $ruc . "." . $extensionLogo,
                    */
                    //'headers' => [
                    //    'Content-Length:' => filesize($pathFirma)
                    //]
                    'firma' => DataPart::fromPath($rutaLogo),
                ];
            }

            $formData = new FormDataPart($firmaLogo);

            // this header is added to all requests made by this client
            $client = HttpClient::create(['headers' => $headers]);

            $response = $client->request('POST', $this->url, [

                'headers' => $formData->getPreparedHeaders()->toArray(),
                'body' => $formData->bodyToIterable(),
            ]);

            /*$response = $client->request('POST', $this->url, [
                //'body' => $json,
                'headers' => $headers,
                //'stream' => true,
                'multipart' => $firmaLogo
            ]);
            */

            // gets the HTTP status code of the response
            $statusCode = $response->getStatusCode();

// gets the HTTP headers as string[][] with the header names lower-cased
            $headers = $response->getHeaders();

// gets the response body as a string
            $content = $response->getContent();

// casts the response JSON contents to a PHP array
            $content = $response->toArray();

// cancels the request/response
            $response->cancel();

// returns info coming from the transport layer, such as "response_headers",
// "redirect_count", "start_time", "redirect_url", etc.
            $httpInfo = $response->getInfo();

            if ($response->getStatusCode() == 200) {
                $body = $response->getBody()->getContents();
                $obj = json_decode($body);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                    return $obj->message;
                }
                return $obj;
            }

            $error = true;
            return $response->getBody();


        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        }

    }

    public static function variosEmisorApi(&$error, $ruc, $json, $url)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $url . 'varios.php');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $ruc,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'json' => base64_encode($json)
            ];

            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }
    }

    public static function enviaUserApi(&$error, $ruc, $json, $url)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $url . 'user.php');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $ruc,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'json' => base64_encode($json)
            ];


            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }
    }

    public static function enviarEmisorApi(&$error, $ruc, $json, $url, $firma = null, $logo = null)
    {
        $error = false;

        // get cURL resource
        $ch = curl_init();
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $url . 'emisor.php');

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $ruc,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            // form body
            $body = [
                'json' => base64_encode($json)
            ];

            if ($logo !== null)
                $body['ruta_logo'] = curl_file_create($logo);

            if ($firma !== null)
                $body['ruta_firma'] = curl_file_create($firma);

            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                }
                return $obj->message;
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }
    }

    public static function consultarAutoComprobante(&$error, $url, $clave)
    {
        $error = false;

        $ch = curl_init();
        try {

            curl_setopt($ch, CURLOPT_URL, $url . 'autorizacion.php');

            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&',
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/json',
            ]);

            $body = [
                'clave' => $clave,
            ];

            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            $response = curl_exec($ch);

            if (!$response) {
                $error = true;
                return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
            }

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $obj = json_decode($response);
                //$this->claveAcceso = $obj->claveacceso;
                if ($obj->error) {
                    $error = true;
                    return $obj->message;
                } else {
                    $error = false;
                    return $obj;
                }
            }

            $error = true;
            return $response;

        } catch (Exception $e) {
            $error = true;
            return $e->getMessage();
        } finally {
            curl_close($ch);
        }
    }

    public static function getPdf(&$error, $app_url, $clave, $xml, &$mensaje, $ruc = null)
    {
        // get cURL resource
        $ch = curl_init();
        $response = null;
        try {

            // set url
            curl_setopt($ch, CURLOPT_URL, $app_url);

            // set method
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

            // return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            // set headers
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                'Authorization: sHaRa150108&X' . $clave,
                'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                'Accept: application/octet-stream',
            ]);

            if ($ruc)
                $body = [
                    'cadena' => base64_encode($xml),
                    'offline' => true,
                    'ruc2' => $ruc
                ];
            else
                $body = [
                    'cadena' => base64_encode($xml),
                    'offline' => true,
                ];
            //$body = http_build_query($body);

            // set body
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

            // send the request and save response to $response
            $response = curl_exec($ch);

            // stop if fails
            if (!$response) {
                $error = true;
                $mensaje = 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
                $response = null;
            }

            //echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
            //echo 'Response Body: ' . $response . PHP_EOL;

            if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                $error = false;
            } else {
                $error = true;
                $response = null;
                $mensaje = json_encode($response);
            }

        } catch (Exception $e) {
            $error = true;
            $mensaje = $e->getMessage();
        } finally {
            // close curl resource to free up system resources
            curl_close($ch);
        }

        return $response;
    }

    public static function envioMailComprobante($tercero, $numero, $clave, $fechaAuto, $comprobante, $email, $pdf, $xml_autorizado, Empresa $empresa)
    {
        $html = RestApiFunciones::plantillaMail($tercero, $comprobante, $numero, $clave, $fechaAuto);

        file_put_contents($clave . '.pdf', $pdf);

        $pdf = file_get_contents($clave . '.pdf');

        $subject = $comprobante . ': ' . $numero;

        //$usuario = new User();
        $mailuser = $empresa->getMailfrom();
        $mailpass = $empresa->getPassmail();
        $mailhost = $empresa->getMailHost();
        $mailport = $empresa->getMailPort();
        $mailencrypt = $empresa->getMailStarttls();

        if (strcmp($mailhost, "smtp.gmail.com") == 0)
            $mailencrypt = "tls";

        $attachmentPdf = new \Swift_Attachment($pdf, $comprobante . '_' . $numero . '.pdf', 'application/pdf');

        if ($xml_autorizado != null)
            $attachmentXml = new \Swift_Attachment(utf8_decode($xml_autorizado), $comprobante . '_' . $numero . '.xml', 'application/xml');

        /*$transport = \Swift_SmtpTransport::newInstance()
            ->setHost($mailhost)
            ->setPort($mailport)
            ->setEncryption($mailencrypt)
            ->setUsername($mailuser)
            ->setPassword($mailpass)

        ;

        $mailer = \Swift_Mailer::newInstance($transport);

        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom($mailuser, $usuario->getName())
            ->setTo($email)
            ->setCc($usuario->getEmail())
            ->setBody($html, 'text/html',  'utf8')
            ->attach($attachmentPdf)
            ->attach($attachmentXml);

        //$message->setCharset('iso-8859-1');

        $headers = "\r\n" . "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=utf8" . "\r\n";

        $result = $mailer->send($message);
        */

        $transport = new \Swift_SmtpTransport();

        $transport->setAuthMode('login');
        $transport->setHost($mailhost);
        $transport->setPort($mailport);
        $transport->setEncryption($mailencrypt);
        $transport->setUsername($mailuser);
        $transport->setPassword($mailpass);

        $mailer = new \Swift_Mailer($transport);

        $message = new \Swift_Message();
        $message->setCharset('utf8');

        $message->setSubject($subject);
        $message->setFrom($mailuser, $empresa->getNombreComercial());
        $message->setTo($email);
        $message->setCc($empresa->getEmail());
        $message->setBody($html, 'text/html');
        $message->attach($attachmentPdf);

        if ($xml_autorizado != null)
            $message->attach($attachmentXml);

        $result = $mailer->send($message, $failures);

        try {
            unlink($clave . ".pdf");
        } catch (\Exception $ex) {

        }

        return $result;

        /* $header = "Content-Type: text/html; charset=ISO-8859-1";

         $mail = new PHPMailer(true);


         $mail->isSMTP();
         $mail->Host = $mailhost;
         $mail->Port = $mailport;
         $mail->SMTPAuth = true;
         $mail->Username = $mailuser;
         $mail->Password = $mailpass;
         $mail->SMTPSecure = $mailencrypt;
         $mail->smtpClose();

         $mail->From = $mailuser;
         $mail->FromName = $usuario->getName();

         file_put_contents($clave . '.xml', utf8_decode($xml_autorizado));

         $mail->CharSet = 'UTF-8';
         //$mail->Encoding = "quoted­printable";


         $mail->addAttachment($clave . '.pdf');         // Add attachments
         $mail->addAttachment($clave . '.xml', 'auto.xml');    // Optional name


         $mail->addAddress($email);

         $mail->isHTML(true);
         $mail->Subject= $subject;
         $mail->Body =  $html;
         $isSend = $mail->send();

         return $isSend;
        */

    }

    public static function consultarContribuyente(&$error, $url,  $ruc)
    {
        $respuesta = null;
        $error = false;
        try {


            $ch = curl_init();
            try {

                curl_setopt($ch, CURLOPT_URL, $url.'emisor.php');

                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    //'Cookie: XSRF-TOKEN=eyJpdiI6Ilo3bk1FYVF5emtjVTNZT1lmTEFPS0E9PSIsInZhbHVlIjoiTFh6RkFGeVdZU1A2S2tOTUo1bEhOVFlLT1NobnZYVDlneHFDWEI0Rk9xUk9yelhzM0t6YmJqelBPYlY3NnZlUCIsIm1hYyI6IjA3YzJhNGQyMTJlNDYyMjE5YTg0OTM0YTQ2M2RlNzFhOGU3NGEyOTk1NjQ3Yjg2NGJjNmIzYzFkYTJlOGQzOWQifQ%3D%3D; laravel_session=eyJpdiI6IjhRYzZ1NmJXcWpZSkNOQjBOWXNJd0E9PSIsInZhbHVlIjoidmorNUxyUnFmNGRpRFlmZ3YzQTR6ZUpFUWNwbnhBODFpVGhKVkVXRWg3dGZ0dnFjc3Y2d2NyN1VOU0I5ZjRRMSIsIm1hYyI6IjIwYWYwZTlkYzFkZWM5NjY0NDNjZGUxNzdiZmYxYjBiMzBiYTY2ZDVkYzU1ZDgwMDIwZjlmZmViZjNjNDFhNzIifQ%3D%3D',
                    'Authorization: sHaRa150108&',
                    'Content-Type: multipart/form-data',  //  IMPORTANTE NO OLVIDAR
                    'Accept: application/json',
                ]);

                $body = [
                    'ruc' => $ruc,
                ];

                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

                $response = curl_exec($ch);

                if (!$response) {
                    $error = true;
                    return 'Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch);
                }

                if (curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL == 200) {
                    $obj = json_decode($response, null, 512, JSON_THROW_ON_ERROR);
                    //$this->claveAcceso = $obj->claveacceso;
                    if ($obj->error) {
                        $error = true;
                        return $obj->message;
                    }
                    else {
                        $error = false;
                        return $obj;
                    }
                }

                $error = true;
                return $response;

            } catch (\Exception $exception) {
                $error = true;
                return $exception->getMessage();
            }
            finally{
                curl_close($ch);
            }

        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        return $respuesta;
    }

    function decodificar_utf8($cadena)
    {
        $buscar = array(
            'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ă', 'Ą',
            'Ç', 'Ć', 'Č', 'Œ',
            'Ď', 'Đ',
            'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ă', 'ą',
            'ç', 'ć', 'č', 'œ',
            'ď', 'đ',
            'È', 'É', 'Ê', 'Ë', 'Ę', 'Ě',
            'Ğ',
            'Ì', 'Í', 'Î', 'Ï', 'İ',
            'Ĺ', 'Ľ', 'Ł',
            'è', 'é', 'ê', 'ë', 'ę', 'ě',
            'ğ',
            'ì', 'í', 'î', 'ï', 'ı',
            'ĺ', 'ľ', 'ł',
            'Ñ', 'Ń', 'Ň',
            'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ő',
            'Ŕ', 'Ř',
            'Ś', 'Ş', 'Š',
            'ñ', 'ń', 'ň',
            'ò', 'ó', 'ô', 'ö', 'ø', 'ő',
            'ŕ', 'ř',
            'ś', 'ş', 'š',
            'Ţ', 'Ť',
            'Ù', 'Ú', 'Û', 'Ų', 'Ü', 'Ů', 'Ű',
            'Ý', 'ß',
            'Ź', 'Ż', 'Ž',
            'ţ', 'ť',
            'ù', 'ú', 'û', 'ų', 'ü', 'ů', 'ű',
            'ý', 'ÿ',
            'ź', 'ż', 'ž',
            'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р',
            'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'р',
            'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я',
            'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'
        );
        $remplazar = array(
            'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'A', 'A',
            'C', 'C', 'C', 'CE',
            'D', 'D',
            'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'a', 'a',
            'c', 'c', 'c', 'ce',
            'd', 'd',
            'E', 'E', 'E', 'E', 'E', 'E',
            'G',
            'I', 'I', 'I', 'I', 'I',
            'L', 'L', 'L',
            'e', 'e', 'e', 'e', 'e', 'e',
            'g',
            'i', 'i', 'i', 'i', 'i',
            'l', 'l', 'l',
            'N', 'N', 'N',
            'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'R', 'R',
            'S', 'S', 'S',
            'n', 'n', 'n',
            'o', 'o', 'o', 'o', 'o', 'o',
            'r', 'r',
            's', 's', 's',
            'T', 'T',
            'U', 'U', 'U', 'U', 'U', 'U', 'U',
            'Y', 'Y',
            'Z', 'Z', 'Z',
            't', 't',
            'u', 'u', 'u', 'u', 'u', 'u', 'u',
            'y', 'y',
            'z', 'z', 'z',
            'A', 'B', 'B', 'r', 'A', 'E', 'E', 'X', '3', 'N', 'N', 'K', 'N', 'M', 'H', 'O', 'N', 'P',
            'a', 'b', 'b', 'r', 'a', 'e', 'e', 'x', '3', 'n', 'n', 'k', 'n', 'm', 'h', 'o', 'p',
            'C', 'T', 'Y', 'O', 'X', 'U', 'u', 'W', 'W', 'b', 'b', 'b', 'E', 'O', 'R',
            'c', 't', 'y', 'o', 'x', 'u', 'u', 'w', 'w', 'b', 'b', 'b', 'e', 'o', 'r'
        );
        return str_replace($buscar, $remplazar, $cadena);

    }

    public static function getPaginationResults($query, PaginatorInterface $paginator, int $page = 1, int $limit_pagination = 30)
    {

        // Paginate the results of the query
        $facturas = $paginator->paginate(
        // Doctrine Query, not results
            $query,
            // Define the page parameter
            $page,
            // Items per page
            $limit_pagination
        );

        return $facturas;
    }

    public static function plantillaMail($tercero, $comprobante, $numero, $clave, $fecha)
    {

        $html = "<br>Estimado(a), <b>" . $tercero . "</b>" .
            "<br><br>Hemos emitido el siguiente comprobante electronico." .
            "<br><br>Documento: <b>" . $comprobante . " Electronica</b>" .
            "<br>Numero: <b>" . $numero . "</b>" .
            "<br>Clave Acceso: <b>" . $clave . "</b>" .
            "<br>Fecha de Autorizacion: <b>" . $fecha . "</b>" .
            "<br><br>El documento xml y pdf de su <b>" . $comprobante . " Electronica</b>, se encuentra adjunto a este correo." .
            //"<br><br>Saludos cordiales," .

            //"<br><br>--------------------" .
            "<br><br>¡Gracias por apoyarnos a servirle mejor y a conservar el medio ambiente!" .
            "<br>Servicio proporcionado por: <b>www.factecu.com</b>" .
            "<br><br>Las tildes han sido omitidas intencionalmente para evitar problemas de lectura<br><br><br><br>";

        return $html;
    }

    public static function plantillaMailReset(ResetPasswordToken $resetToken)
    {

        $token = $resetToken->getToken();

        $html = "<h1>Hi!</h1>

                <p>To reset your password, please visit the following link</p>
                <a href='reset-password/reset/$token'>/reset-password/reset/$token</a>
                <p>This link will expire in 1 hora.</p>
                <p>Cheers!</p>";

        return $html;
    }

    public static function getErrorValidacion($errors)
    {
        $messages = [];
        foreach ($errors as $violation) {
            //$messages[$violation->getPropertyPath()][] = $violation->getMessage();
            $messages[] = $violation->getMessage();
        }
        return $messages;
    }

}
