<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of wsUtil
 *
 * @author Lic. Carlos Alberto Vaca Coronado
 */

Class wsUtil{


	var $wsdlPendientes = "";
	var $wsdlPendientesUser = "";
	var $wsdlPendientesPass = "";

	var $wsdlCancelarRechazarCancelacion = "";
	var $wsdlCancelarRechazarCancelacionUser = "";
	var $wsdlCancelarRechazarCancelacionPass = "";

	var $wsdlWSUtilQueries = "";
	var $wsdlWSUtilQueriesUser = "";
	var $wsdlWSUtilQueriesPass = "";

	var $ERROR_NO=0;
	var $RESPONSE="";
	var $ERROR_MESSAGE="";
	var $CODEHTTP="";
	var $MENSAJE="";
	var $urlWS_SqlServer="";
	var $usuarioWS_SqlServer="";
	var $passWS_SqlServer="";


	function __construct($Tipo) {
		switch($Tipo){
			case "T":
						// $this->wsdlPendientes = "http://www.disxii.com/pruebaTimbrado/utilerias/wsPendientesCancelar.php";
						$this->wsdlPendientes = "https://www.dis12.com/ws/sat/t/wsPendientesCancelar.php";
						$this->wsdlPendientesUser = "test";
						$this->wsdlPendientesPass = "test";
						// $this->wsdlCancelarRechazarCancelacion = "http://www.disxii.com/pruebaTimbrado/utilerias/wsAceptaRechazaCancelacion.php";
						$this->wsdlCancelarRechazarCancelacion = "https://www.dis12.com/ws/sat/t/wsAceptaRechazaCancelacion.php";
						$this->wsdlCancelarRechazarCancelacionUser = "test";
						$this->wsdlCancelarRechazarCancelacionPass = "test";
						$this->wsdlWSUtilQueries = "http://localhost:2550/wsUtilQueries/wsUtilQueries.php";
						$this->wsdlWSUtilQueriesUser = "disxiitest";
						$this->wsdlWSUtilQueriesPass = "disxii_3x3cQu3r135";
						$this->urlWS_SqlServer = "http://localhost/EjecutaWS/WS_SqlServer/SQLSRV.php";
						$this->usuarioWS_SqlServer = "disxii_sqlsrv";
						$this->passWS_SqlServer = "d15x11_5q15rv";

						break;
			case "P":
						// $this->wsdlPendientes = "http://www.disxii.com/Timbrado/utilerias/wsPendientesCancelar.php";
						$this->wsdlPendientes = "https://www.dis12.com/ws/sat/p/wsPendientesCancelar.php";
						$this->wsdlPendientesUser = "disxii";
						$this->wsdlPendientesPass = "d15x11_p3nd13nt35";
						// $this->wsdlCancelarRechazarCancelacion = "http://www.disxii.com/Timbrado/utilerias/wsAceptaRechazaCancelacion.php";
						$this->wsdlCancelarRechazarCancelacion = "https://www.dis12.com/ws/sat/p/wsAceptaRechazaCancelacion.php";
						$this->wsdlCancelarRechazarCancelacionUser = "disxii";
						$this->wsdlCancelarRechazarCancelacionPass = "d15x11_c4nc3l4c10n";
						$this->wsdlWSUtilQueries = "http://localhost:2550/wsUtilQueries/wsUtilQueries.php";
						$this->wsdlWSUtilQueriesUser = "disxiitest";
						$this->wsdlWSUtilQueriesPass = "disxii_3x3cQu3r135";
						$this->urlWS_SqlServer = "http://localhost/EjecutaWS/WS_SqlServer/SQLSRV.php";
						$this->usuarioWS_SqlServer = "disxii_sqlsrv";
						$this->passWS_SqlServer = "d15x11_5q15rv";
						break;
			default:
						$this->ERROR_NO=100;
		}
	}

	function getPendientesCancelar($rfc){
		try{
			$data='<PendientesCancelar>
					<Usuario>'.$this->wsdlPendientesUser.'</Usuario>
					<Password>'.$this->wsdlPendientesPass.'</Password>
					<RFC>'.$rfc.'</RFC>
				   </PendientesCancelar>';
			// echo htmlspecialchars($data);exit;
			$curl  = curl_init($this->wsdlPendientes);
			curl_setopt($curl , CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl , CURLOPT_POST, true);
			curl_setopt($curl , CURLOPT_HTTPHEADER , array(
				'Content-Type: text/xml;',
				));
			curl_setopt($curl , CURLOPT_POSTFIELDS, $data);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

			$response = curl_exec($curl);
			$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$err = curl_error($curl );
			curl_close($curl );
			// echo $err;exit;
			// echo $response;exit;
			// var_dump($response);exit;
			if ($err)
			{
				$this->CODEHTTP=-1;
				throw new Exception("cURL Error #:" . $err);
			} else if($httpcode!='200') {
				$this->CODEHTTP=$httpcode;
				//die($response);
				$this->decodificaResponse($response);
				$this->ERROR_MESSAGE = $this->RESPONSE->errorWS;
			}
			else{
				$this->CODEHTTP=200;
				$this->decodificaResponse($response);
				//$this->MENSAJE = $this->RESPONSE->acuseSAT;
				return $response;
			}
		}catch(Exception $e){
			$this->ERROR_MESSAGE = $e->getMessage();
			return false;
		}
	}

	function aceptarRechazarCancelacion($rfc,$uuid,$accion,$cerPass,$cerB64,$keyB64){
		try{
			$data='<AceptarCancelarUUID>
					<Usuario>'.$this->wsdlCancelarRechazarCancelacionUser.'</Usuario>
					<Password>'.$this->wsdlCancelarRechazarCancelacionPass.'</Password>
					<RFC>'.$rfc.'</RFC>
					<uuid>'.$uuid.'</uuid>
					<accion>'.$accion.'</accion>
					<cerPass>'.$cerPass.'</cerPass>
					<cerB64>'.$cerB64.'</cerB64>
					<keyB64>'.$keyB64.'</keyB64>
					</AceptarCancelarUUID>';
			 // echo $data;exit;
			$curl  = curl_init($this->wsdlCancelarRechazarCancelacion);
			curl_setopt($curl , CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl , CURLOPT_POST, true);
			curl_setopt($curl , CURLOPT_HTTPHEADER , array(
				'Content-Type: text/xml;',
				));
			curl_setopt($curl , CURLOPT_POSTFIELDS, $data);

			$response = curl_exec($curl);
			$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$err = curl_error($curl );
			curl_close($curl );


			if ($err)
			{
				$this->CODEHTTP=-1;
				throw new Exception("cURL Error #:" . $err);
			} else if($httpcode!='200') {
				$this->CODEHTTP=$httpcode;
				$this->decodificaResponse($response);
				$this->ERROR_MESSAGE = $this->RESPONSE->errorWS;
				return false;
			}
			else{
				$this->CODEHTTP=200;
				$this->decodificaResponse($response);
				$this->MENSAJE = $this->RESPONSE->errorWS;
				return $response;
			}
		}catch(Exception $e){
			$this->ERROR_MESSAGE = $e->getMessage();
			return false;
		}
	}

	function ejecutaWS_SqlServer($json){
		try{
			$curl  = curl_init($this->urlWS_SqlServer);
			curl_setopt($curl , CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl , CURLOPT_POST, true);
			curl_setopt($curl , CURLOPT_HTTPHEADER , array(
				'Content-Type: text/plain;',
				));
			curl_setopt($curl , CURLOPT_POSTFIELDS, $json);

			$response = curl_exec($curl);
			$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$err = curl_error($curl );
			curl_close($curl );


			if ($err)
			{
				$this->CODEHTTP=-1;
				throw new Exception("cURL Error #:" . $err);
			} else if($httpcode!='200') {
				$this->CODEHTTP=$httpcode;
				$this->RESPONSE = $response;
				$this->ERROR_MESSAGE = "Ocurrio un error ".$httpcode." al ejecutar el WS";
				return false;
			}
			else{
				$this->CODEHTTP=200;
				$this->RESPONSE = $response;
				$this->MENSAJE = "WS ejecutado correctamente.";
				return $response;
			}
		}catch(Exception $e){
			$this->ERROR_MESSAGE = $e->getMessage();
			return false;
		}
	}

	function preparaJSON_WS_SQLSERVER($query){
			$data='{ "Usuario"  : "'.$this->usuarioWS_SqlServer.'", "Password" : "'.$this->passWS_SqlServer.'", "querys" : [ { "query":"'.$query.'"}] }';
			 return $data;
	}

	function cancelaBDExterna($uuid){
		try{
			$data='{
				"usuario": "'.$this->wsdlWSUtilQueriesUser.'",
				"password": "'.$this->wsdlWSUtilQueriesPass.'",
				"consulta": "ActualizaCancelado",
				"etiquetaValor": ":nuevoValor|C|s^:UUID|'.$uuid.'|s"
			}';
			 // echo $data;exit;
			$curl  = curl_init($this->wsdlWSUtilQueries);
			curl_setopt($curl , CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl , CURLOPT_POST, true);
			curl_setopt($curl , CURLOPT_HTTPHEADER , array(
				'Content-Type: text/xml;',
				));
			curl_setopt($curl , CURLOPT_POSTFIELDS, $data);

			$response = curl_exec($curl);
			$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$err = curl_error($curl );
			curl_close($curl );
			$this->ERROR_MESSAGE = "";

			if ($err)
			{
				$this->CODEHTTP=-1;
				throw new Exception("cURL Error #:" . $err);
			} else if($httpcode!='200') {
				$this->CODEHTTP=$httpcode;
				$this->decodificaResponse($response);
				return false;
			}
			else{
				$this->CODEHTTP=200;
				$this->decodificaResponse($response);
				return $response;
			}
		}catch(Exception $e){
			$this->ERROR_MESSAGE = $e->getMessage();
			return false;
		}
	}

	function decodificaResponse($JSON){
		$this->RESPONSE = json_decode($JSON);
	}

	function Encripta($cadena,$tipo=0){
	    $salida="";
	    if ($tipo===0)
	        {
	        $cadInv = strrev(str_replace(" ","--SPACE--",$cadena));
	        for($i=0; $i < strlen($cadInv); $i++)
	            {
	            $asc = ord($cadInv[$i]);
	            $salida.=utf8_encode(chr((intval($asc) ^ intval(5))));
	            }
	        $salida = base64_encode($salida);
	        }
	   else
	       {
	        $cadInv = base64_decode($cadena);
	        for($i=0; $i < strlen($cadInv); $i++)
	            {
	            $asc = ord($cadInv[$i]);
	            $salida.=utf8_encode(chr((intval($asc) ^ intval(5))));
	            }
	        $salida = str_replace("--SPACE--"," ",strrev($salida));
	       }
	  return $salida;
	}

}
