<?php

namespace App\Traits;

use GuzzleHttp\Client;
use Symfony\Component\Intl\Locales;

Trait PaymentTrait
{

    /**
     * API url
     * @var string
     */
    private $url = null;

    /**
     * API key
     * @var string
     */
    protected $api_key = null;

    /**
     * Format
     * @var string
     */
    protected $format = null; // json, xml, printr, js

    /**
     * Curl options
     * @var options
     */
    protected $curl_options = array(
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT => 8
    );

    /**
     * Error codes
     * @var array
     */
    protected $http_errors = array
    (
        400 => '400 Bad Request',
        401 => '401 Unauthorized',
        403 => '403 Forbidden',
        404 => '404 Not Found',
        422 => '422 Unprocessable Entity',
        500 => '500 Internal Server Error',
        501 => '501 Not Implemented',
    );

    /**
     * Allowed formats
     * @var unknown
     */
    protected $formats = array('json', 'xml', 'js', 'printr');

    /**
     * Get response
     * @param string $method
     * @param string $path
     * @param array $params
     * @param bool $format_response
     * @param bool $is_upload_file
     * @throws Exception
     * @return string|array
     */
    protected function sendRequest($method, $path, $params = null, $format_response = true, $is_upload_file = false)
    {
        // do the actual connection
        $curl = curl_init();

        // set URL
        curl_setopt($curl, CURLOPT_URL, $this->url.$path.'.'.(isset($this->format) ? $this->format : 'json'));
        // set api key
        $headers = array( 'X-Api-Key:' . $this->api_key);

        // is uplaoded file
        if (true == $is_upload_file)
        {
            $headers[] = 'Content-type: multipart/form-data';
        }

        switch ($method) {
            case 'GET':
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case 'POST':
                curl_setopt($curl, CURLOPT_POST, true);
                $headers[] = 'Expect:';
                break;
            case 'PUT':
                if(empty($params))
                {
                    $headers[] = 'Content-Length: 0';
                }
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
                break;
            default:
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        // add params
        if (!empty($params))
        {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $is_upload_file ? $params : http_build_query($params));
        }

        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 8);
        curl_setopt($curl, CURLOPT_TIMEOUT, 8);
        //curl_setopt_array($curl, $this->curl_options);//estaba marcando error

        // send the request
        $response = curl_exec($curl);

        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if (isset($this->http_errors[$http_code]))
        {
            throw new \Exception($response, $http_code);
        }
        elseif (!in_array($http_code, array(200,201)))
        {
            throw new \Exception('Response status code: ' . $http_code);
        }

        // check for curl error
        if (0 < curl_errno($curl))
        {
            throw new \Exception('Unable to connect to '.$this->url . ' Error: ' . curl_error($curl));
        }

        // close the connection
        curl_close($curl);

        // check return format
        if (!isset($this->format) && true == $format_response)
        {
            $response = json_decode($response);
        }
        return $response;
    }


    protected function createMBWAYPayment ($request, $orderCode)
    {
        $locales = Locales::getNames(null);
        $languages = [];
        foreach($this->getParameter('app.languages') as $language)
        {
            if(isset($locales[$language]))
            {
                $languages[$locales[$language]] = $language;
            }
        }

        return $languages;
    }

    protected function createMULTIBANCOPayment ($request, $orderCode)
    {
        $this->url =  $_ENV['API_EUPAGO'];
        $params = array(
            'valor' => $request->get('total'),
            'chave' => $_ENV['KEY_EUPAGO'],
            'id' => $orderCode,
            'per_dup' => 0,
            'admin_callback' => $_ENV['URL_EUPAGO_CALLBACK'],
            //'campos_extra'  => '[{"id":369,"valor":"um valor"},{"id":178,"valor":"outro valor"}]'
        );

        //$output = $this->sendRequest('POST', '', $params);
        $client = new \GuzzleHttp\Client();


        $response = $client->request('POST', 'https://sandbox.eupago.pt/clientes/rest_api/multibanco/create', [
          'body' => json_encode($params),
          'headers' => [
            'accept' => 'application/json',
            'content-type' => 'application/json',
          ],
        ]);

        $output = $response->getBody();

        dd($output);
    }
}
