<?php

namespace App\Api;

use DB;
use Request;

class AbstrahereApi
{

    function __construct($rut_empresa = '', $rut_usuario = '') {
		$this->rut_empresa = $rut_empresa;
		$this->rut_usuario = $rut_usuario;
		$this->url = env('ABSTRAHERE_API');
		$this->api_key = "eM+Gz/k/6WUFqOj3PksDBtla6YBFxJ6WSDeMKyt1JMN5IV9/JSxB8Xs7kjUJk2J6J0/CEIOvLVzlRYoKJ78Dax8GVb3Zfan5aeJTGebb3zc=";
	}

	/**
	 * Consultar a un servidor a través del protocolo HTTP (GET).
	 * Se utiliza para consultar recursos en una API REST
	 *
	 * @param string $URL URL recurso, ejemplo: http://website.com/recurso/(id) no obligatorio
	 * @param string $TOKEN token de autenticación
	 * @return JSON
	 */
	public function GET($end_point, $header_adicional = ''){
		$metodo = $this->url.''.$end_point;
		
		$headers = array(
			'x-api-key:'.$this->api_key,
			$header_adicional,
			'Content-Type: application/json'
		);

		$tiempo_inicial = microtime(true);

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $metodo,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "GET",
			CURLOPT_HTTPHEADER => $headers,
		));

		$response = curl_exec($curl);
		
		$tiempo_final = microtime(true);
		$tiempo = $tiempo_final - $tiempo_inicial;

		$datapost = '';
		$this->log('GET', $end_point, $datapost, $response, $tiempo);

		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
			echo "cURL Error #:" . $err;
		} else {
			//echo $response;
		}

		return $response;
	}


    /**
	 * Enviar parámetros a un servidor a través del protocolo HTTP (POST).
	 * Se utiliza para agregar datos en una API REST
	 *
	 * @param string $URL URL recurso, ejemplo: http://website.com/recurso
	 * @param string $TOKEN token de autenticación
	 * @param array $ARRAY parámetros a envíar
	 * @return JSON
	 */
	public function POST($end_point, $datapost){
		
		$metodo = $this->url.''.$end_point;

		$headers = array(
			"cache-control: no-cache",
			"content-type: application/json",
			"postman-token: bbfa70b4-afba-f134-1ed5-7685f125397d",
			"x-api-key:" . $this->api_key
		);

		$tiempo_inicial = microtime(true);

		$curl = curl_init();

		curl_setopt_array($curl, array(
		  CURLOPT_URL => $metodo,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 30,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "POST",
		  //CURLOPT_POSTFIELDS => "{\n   \"rutEmpresa\" : \"76087323-3\",\n   \"tipoDTE\": \"61\",\n   \"cantidadDctos\": \"75\"\n}\n",
		  CURLOPT_POSTFIELDS => $datapost,
		  CURLOPT_HTTPHEADER => $headers,
		));

		$response = curl_exec($curl);

		$tiempo_final = microtime(true);
		$tiempo = $tiempo_final - $tiempo_inicial;
		
		$this->log('POST', $end_point, $datapost, $response, $tiempo);

		$err = curl_error($curl);

		curl_close ($curl);

		return $response;
	}

	/**
	 * Registrar entrada y salida de datos enviados por api
	 * Se utiliza para revisar datos enviados por API
	 *
	 */
	private function log($metodo, $end_point, $entrada='', $salida, $duracion){

		//$coneccion_respaldo = conectaPDO_migracion();
		//$coneccion_respaldo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		//obtiene ip
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP'))
			$ipaddress = getenv('HTTP_CLIENT_IP');
		else if(getenv('HTTP_X_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		else if(getenv('HTTP_X_FORWARDED'))
			$ipaddress = getenv('HTTP_X_FORWARDED');
		else if(getenv('HTTP_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		else if(getenv('HTTP_FORWARDED'))
		$ipaddress = getenv('HTTP_FORWARDED');
		else if(getenv('REMOTE_ADDR'))
			$ipaddress = getenv('REMOTE_ADDR');
		else
			$ipaddress = 'UNKNOWN';

		try{

            $ingreso = DB::connection('log')->table('log_api_abstrahere')
                ->insert([
                    'rut_empresa' => $this->rut_empresa,
                    'rut_usuario' => $this->rut_usuario,
					'metodo' => $metodo,
                    'endpoint' => $end_point,
                    'entrada' => $entrada,
                    'salida' => $salida,
                    'ip' => $ipaddress,
                    'duracion' => $duracion
                ]);
        } catch(Exception $e) {
            return false;
        }


	}

	/**
	 * Convertir JSON a un ARRAY
	 *
	 * @param json $json Formato JSON
	 * @return ARRAY
	 */
	public function JSON_TO_ARRAY($json){
		return json_decode($json,true);
	}


}