<?php
function ejecuta_clienteb2b($rut)
{
	$conn = db_connect(HOST, USER, PASS, DB);
        //$rut = substr ( $rut, 0 , -1 ) . '-' . substr ( $rut, strlen($rut) -1 , 1 );
        //$url = 'http://172.17.209.175:8080/redis/geko/pub/clientes/' . $rut; //URL QA
        $url ='http://172.17.212.130:8080/redis/geko/pub/clientes/' . $rut; //URL PROD
	error_log("voy a la url b2b: $url");

	$sql = 'select gc13_id_dispositivo,t02_id_area from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_dispositivo = $row[0];
        $idarea =$row[1];


        $datos = array(
                'ws' => 'b2b',
                'dato_enviado' => $rut
        );

        $sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_logws = $row[0];

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $url);

	curl_setopt($ch, CURLOPT_TIMEOUT,6);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,6);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	$output = curl_exec($ch);

	$info = curl_getinfo($ch);
	$error = curl_error($ch);
	curl_close($ch);

	$data = json_decode($output, true);

	//error_log("Esta consulta se demoro " .  $info['total_time']);

        $retorno ="";
        if ($data)
        {
                $tipo=$data["data"]["tipoCliente"];
                if($tipo==1 || $tipo==2 || $tipo==3)
                {
                        $retorno="B2B ";
                }
        }

		 $datos = array (
                'error'  => $error,
                'retorno' => $retorno,
                'resultado' => $retorno
        );


        $sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($datos) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
        //error_log("DEBUG: SQL = " . $sql);
        $rs=$conn->query($sql);


        error_log("en cliente b2b : --> Rut $rut --> $retorno");
        return $retorno;


}

function ejecuta_migradb_bkp($rut)
{

	if($rut=='135541966')
	{
		//lo marco como andes
		$retorno='A';
	}else{
		$retorno='T';
	}
	return $retorno;
}

function ejecuta_migradb_geko($rut)
{
	$cn = db_connect("geko.vtr.cl", USER, PASS, "gekocentral");
        $sSql ="select rut_cliente from cm02_cliente_andes where rut_cliente = '$rut';";
        $rs=$cn->query($sSql);
        if ($row = $rs->fetch())
       	{
       		$ret="A";
        }else{
                $ret="T";
        }
	return $ret;
}

function ejecuta_migradb($rut)
{
	//Esto es solo GEKO:
	        //$rut = substr ( $rut, 0 , -1 ) . '-' . substr ( $rut, strlen($rut) -1 , 1 );
		//$ret=ejecuta_migradb_geko($rut);

	//esto es Migra luego GEKO:
	//$ret=ejecuta_migradb_ws($rut);
	//MigraDB bloqueada .... todos clientes SON ANDES 2021-10-21
	$ret="A";
	return $ret;

}

function ejecuta_migradb_ws($rut)
{
	$conn = db_connect(HOST, USER, PASS, DB); 
       //$rut = str_pad(number_format( substr ( $rut, 0 , -1 ) , 0, "", ""),8,"0", STR_PAD_LEFT) . '-' . substr ( $rut, strlen($rut) -1 , 1 );
        $rut = substr ( $rut, 0 , -1 ) . '-' . substr ( $rut, strlen($rut) -1 , 1 );
        $request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:con="http://osbcorp.vtr.cl/ARQ/EMP/ConsultarEstadoMigracionUsuario">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <con:ConsultarEstadoMigracionUsuarioRequest>
         <con:rutCliente>'.$rut.'</con:rutCliente>
         <con:identificadorServicio>?</con:identificadorServicio>
         <con:tipoServicio>?</con:tipoServicio>
      </con:ConsultarEstadoMigracionUsuarioRequest>
   </soap:Body>
</soap:Envelope>';

	 $sql = 'select gc13_id_dispositivo,t02_id_area from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_dispositivo = $row[0];
	$idarea =$row[1];


        $datos = array(
                'ws' => 'migradb',
                'dato_enviado' => $rut
        );

        $sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
        //error_log('DEBUG: SQL = ' . $sql);
        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_logws = $row[0];


        $url = "http://osbcorp.vtr.cl:8000/consultarEstadoMigracionUsuario";
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSLVERSION, 3);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
        curl_setopt($ch, CURLOPT_TIMEOUT,15);

        //curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

        $output = curl_exec ($ch);
	$error = curl_error($ch);
        curl_close($ch);

        $migrado = valor_campo($output, '<con:esClienteServicioMigrado>', '</con:esClienteServicioMigrado>');
	//error_log ("MIGRA COMPLETA $output");
        if ($migrado=="true")
        {
                $ret="A";
        }else{
                $ret="T";
        }

	$ret2=ejecuta_migradb_geko($rut);

	error_log("MIGRA: $ret BDD: $ret2");
	if ($error)
	{
		$sSql = "insert into t15_log_servidor values(now(),$idarea,1,'$error',1)";
		$rs=$conn->query($sql);
		$ret=$ret2;
	}
	if($ret <> $ret2)
	{
		$sSql = "insert into t15_log_servidor values(now(),$idarea,1,'Inconsistencia : MigraDB: $ret BDD: $ret2',1)";
                $rs=$conn->query($sql);

	}

	$datos = array (
		'error'	 => $error,
		'migrado' => $migrado,
		'resultado' => $ret
	);
	
	
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($datos) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
        //error_log("DEBUG: SQL = " . $sql);
        $rs=$conn->query($sql);


        return $ret;
}



function ejecuta_nombre($rut)
{
	//return "";
	//exit();
	$rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
	$url = "http://osb.vtr.cl/obtenerDatosPersona?WSDL";
	

	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:obt="http://osb.vtr.cl/CLI/EMP/ObtenerDatosPersona" xmlns:head="http://osb.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:opob="http://osb.vtr.cl/CLI/EMP/OpObtenerDatosPersonaRequest">
   <soap:Header>
      <obt:headerRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </obt:headerRequest>
   </soap:Header>
   <soap:Body>
      <obt:obtenerDatosPersona>
         <obt:reqObtenerDatosPersona>
            <opob:tipoIdentificador></opob:tipoIdentificador>
            <opob:identificador>'.$rut.'</opob:identificador>
            <opob:canal>SV</opob:canal>
            <opob:origen>TANGO</opob:origen>
         </obt:reqObtenerDatosPersona>
      </obt:obtenerDatosPersona>
   </soap:Body>
	</soap:Envelope>';

	
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
	curl_setopt($ch, CURLOPT_TIMEOUT,15);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	curl_close($ch);
	//echo $output;

	$nombre = valor_campo($output, '<opob1:nombres>', '</opob1:nombres>');
	$paterno = valor_campo($output, '<opob1:apellidoPaterno>', '</opob1:apellidoPaterno>');
	$materno = valor_campo($output, '<opob1:apellidoMaterno>', '</opob1:apellidoMaterno>');

	//$sSql = "update gc17_log_ws set gc17_respuesta = '$output', gc17_fin = now() where gc17_id_log = $idlog;";
        //$conn->query($sSql);	
	
	 $salida = $nombre . ' ' . $paterno . ' ' . $materno;
        if (strlen($salida)>100)
                $salida="";

        $salida =str_replace("'","", $salida);
        $salida =str_replace(chr(34),"", $salida);

        return $salida;

}

function ejecuta_saldo($rut,$id_navegacion,$id_dispositivo)
{
	$url = "https://osb.vtr.cl/obtenerDetalleDeudaCliente?wsdl";
	$usr = "gdf";
	$pwd = "gestor.de.fila.2017";
	$conn = db_connect(HOST, USER, PASS, DB);
	$rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );

	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:obt="http://osb.vtr.cl/CLI/EMP/obtenerDetalleDeudaCliente/" xmlns:head="http://osb.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:obt1="http://osb.vtr.cl/CLI/EMP/obtenerDetalleDeudaClienteRequest">
		<soap:Header>
	      <obt:headerRequest>
	         <head:Username>?</head:Username>
	         <head:Company>?</head:Company>
	         <head:AppName>?</head:AppName>
	         <head:IdClient>?</head:IdClient>
	         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
	      </obt:headerRequest>
	   </soap:Header>
	   <soap:Body>
	      <obt1:detalleClienteVTR>
	         <!--Optional:-->
	         <rutCliente>'.$rut.'</rutCliente>
	         <!--Optional:-->
	         <numeroCuenta></numeroCuenta>
	         <!--Optional:-->
	         <numeroDocumento></numeroDocumento>
	      </obt1:detalleClienteVTR>
	   </soap:Body>
	</soap:Envelope>';

	//$sSql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values ($id_dispositivo, '$request', now()) RETURNING gc17_id_log;";
	//$conn->query($sSql);
	//$row = $result->fetch();
        //$idlog=$row["gc17_id_log"];	
	
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
	curl_setopt($ch, CURLOPT_TIMEOUT,15);

	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //CURLAUTH_ANYSAFE
	curl_setopt($ch, CURLOPT_USERPWD, "$usr:$pwd");
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	curl_close($ch);

	//echo $output;

	$cabeza = '<det1:detalleClienteVTRResponse xmlns:det1="http://osb.vtr.cl/CLI/EMP/obtenerDetalleDeudaClienteResponse">';
	$pies = '</resultadodetalleClienteVTR>';

	if(strrpos($output, '<resultadodetalleClienteVTR>') > 0){
        	$saldoxml = valor_campo($output, $cabeza, $pies);
        	$pasoxml = "<DatosCliente>" . $saldoxml . "</resultadodetalleClienteVTR></DatosCliente>";
        	//echo $pasoxml;
        	$xml = simplexml_load_string($pasoxml);
        	
		$sSql="insert into gc21_imprimir_contenido(gc18_id, gc13_id_dispositivo, gc21_contexto, gc21_tipo, gc21_estado, gc21_fecha)
                                                    values($id_navegacion, $id_dispositivo, '" . json_encode($xml) ."', 1, 0,  now());";
        	
		//error_log("DEBUG: SQL = ". $sSql);
		$conn->query($sSql);
		$retorno='Imprimiendo Saldo';
	}elseif(strrpos($output, '<soap:Text xml:lang="en">Cliente No Registra Deuda</soap:Text>') > 0){
        	$xml = simplexml_load_string("<DatosCliente><Saldo>Sin saldo</Saldo></DatosCliente>");
        	$retorno='Cliente no registra deuda';
	}elseif(strrpos($output, 'Error Rut del Cliente no Existe, verifique') > 0){
		$xml = simplexml_load_string("<DatosCliente><Saldo>Cliente no existe</Saldo></DatosCliente>");
                $retorno='Cliente no existe, verifique';
	}

	//$sSql = "update gc17_log_ws set gc17_respuesta = '$output', gc17_fin = now() where gc17_id_log = $idlog;";
	//$conn->query($sSql);


	return $retorno;
}

function ejecuta_ldap($ldapuser,$ldappasswd)
{
	$url = "http://osbcorpqa.vtr.cl:8000/autentificarUsuario?wsdl";
	$url = "http://osbcorp.vtr.cl:8000/autentificarUsuario?wsdl";
	$usr = "UserADCorp";
	$pwd = "UserADCorp2016";
	//cuenta prod:
	$usr = "UserWSCorp";
	$pwd = "UserWSCorp2017.vtr";
	$timeout = 5;
	$retorno = '';


	if(empty($ldapuser)){
		return "Datos invalidos";
	}
	
	$conn = db_connect(HOST, USER, PASS, DB);
	

	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:aut="http://osbcorp.vtr.cl/PRF/EMP/AutentificarUsuario">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
	     <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
	     </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <aut:AutentificaUsuario>
         <aut:codigoUsuarioRed>'.$ldapuser.'</aut:codigoUsuarioRed>
         <aut:claveUsuarioRed>'.$ldappasswd.'</aut:claveUsuarioRed>
         <!--Optional:-->
         <aut:miembroDe>
            <!--Zero or more repetitions:-->
            <aut:grupo>?</aut:grupo>
         </aut:miembroDe>
      </aut:AutentificaUsuario>
   	</soap:Body>
	</soap:Envelope>';

	$sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_dispositivo = $row[0];

	$datos = array(
		'ws' => 'ldap',
		'dato_enviado' => $ldapuser . ' ' . $ldappasswd
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];
	
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	//curl_setopt($ch, CURLOPT_PROXY, false);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //CURLAUTH_ANYSAFE
	curl_setopt($ch, CURLOPT_USERPWD, "$usr:$pwd");
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);

	//echo $output; die();

	$iexito = '<res:ejecucionExitosa xmlns:res="http://osbcorp.vtr.cl/GLOBAL/EMP/ResultadoEjecucion">';
	$fexito = '</res:ejecucionExitosa>';
	
	$exito = valor_campo($output, $iexito, $fexito);
	$exito = ($exito === 'true');

	$imensaje = '<res:mensaje xmlns:res="http://osbcorp.vtr.cl/GLOBAL/EMP/ResultadoEjecucion">';
	$fmensaje = '</res:mensaje>';
	$mensaje  = valor_campo($output, $imensaje, $fmensaje);

	//var_dump($exito);

	if($exito){
		$iresultado = '<aut:informacionLogin>';
		$fresultado = '</aut:informacionLogin>';
		$resultado  = valor_campo($output, $iresultado, $fresultado);
		$resultado  = '<DatosUsuario><habilitado>True</habilitado><mensaje>'. $mensaje . '</mensaje>' . str_replace('aut:', '', $resultado) . '</DatosUsuario>';

		$resultado = json_encode(simplexml_load_string($resultado));
	}else{
		//echo 'test';
		$datos = array(
			'habilitado' => $exito, 
			'mensaje' => $mensaje
		);

		$resultado = json_encode($datos);
	}
	$datos = array(
		'error' => $error,
		'retorno' => substr($resultado, 1,100),
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($datos) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	//error_log("DEBUG: SQL = " . $sql);
	$rs=$conn->query($sql);


	return $resultado;
}

function ejecuta_c2c($eljson)
{
	$url = "http://172.17.209.161:10007/integracion/pub/c2c";

	$request = json_encode($eljson);


		
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: application/json"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
	curl_setopt($ch, CURLOPT_TIMEOUT,15);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	curl_close($ch);

	return $output; 

	
	//return $retorno;
}
function ejecuta_saldoandes($rut,$id_navegacion,$id_dispositivo){
	//$retorno = 'ERROR: Conexón con ANDES';
	//return $retorno;
	//exit();

	//$url = "http://osbcorpqa.vtr.cl:8000/obtenerSaldoAperturado?wsdl";
	//prod : 
	$url = "http://osbcorp.vtr.cl:8000/obtenerSaldoAperturado?wsdl";
	$rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
	$conn = db_connect(HOST, USER, PASS, DB);
	$timeout = 20;
	$retorno = '';


	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cli="http://osb.vtr.cl/CLIEMPobtenerSaldoAperturado/" xmlns:head="http://osb.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:cli1="http://osb.vtr.cl/CLIEMPobtenerSaldoAperturado">
   <soap:Header>
      <cli:headerRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </cli:headerRequest>
   </soap:Header>
   <soap:Body>
      <cli1:obtenerSaldoAperturado>
         <rutCliente>'.$rut.'</rutCliente>
      </cli1:obtenerSaldoAperturado>
   </soap:Body>
</soap:Envelope>';


	$datos = array(
		'ws' => 'saldoandes',
		'dato_enviado' => $rut
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];
		
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);

	//error_log("DEBUG: saldoandes = " . $output);

	$cabeza = '<obt:obtenerSaldoAperturadoResponse xmlns:obt="http://osb.vtr.cl/CLI/EMP/obtenerSaldoAperturadoResponse">';
	$pies = '</obt:obtenerSaldoAperturadoResponse>';

	//	echo $output;

	if(strrpos($output, '<resultadodetalleClienteVTR>') > 0){
        $saldoxml = valor_campo($output, $cabeza, $pies);
        $pasoxml = "<DatosCliente>" . $saldoxml . "<andes>SI</andes></DatosCliente>";
        
        $xml = simplexml_load_string($pasoxml);
        //error_log("DEBUG: ANDES=".var_dump($xml));
        	
        	
		$sSql="insert into gc21_imprimir_contenido(gc18_id, gc13_id_dispositivo, gc21_contexto, gc21_tipo, gc21_estado, gc21_fecha)
                                            values($id_navegacion, $id_dispositivo, '" . json_encode($xml) ."', 1, 0,  now());";
        	
		//error_log("DEBUG: SQL = ". $sSql);
		//error_log("DEBUG: XML = ". $xml);
		$conn->query($sSql);
		$retorno='Imprimiendo Saldo';
	}elseif(strrpos($output, '<soap:Text xml:lang="en">RUT existe sin deuda</soap:Text>') > 0){
        $xml = simplexml_load_string("<DatosCliente><Saldo>Sin saldo</Saldo></DatosCliente>");
        $retorno='Cliente no registra deuda';
	}elseif(strrpos($output, 'Error Rut del Cliente no Existe, verifique') > 0){
		$xml = simplexml_load_string("<DatosCliente><Saldo>Cliente no existe</Saldo></DatosCliente>");
        $retorno='Cliente no existe, verifique';
	}elseif(strrpos($error, 'timed out')>0){
		$retorno = 'ERROR: Tiempo espera agotado';
	}elseif(strrpos($output, 'Numero de Rut no existe') > 0){
		$retorno='Numero de Rut no existe';
	}else{
		$retorno = 'ERROR: Tiempo espera agotado en WS';
	}

	$resultado = array(
		'error' => $error,
		'retorno' => $retorno,
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	$rs=$conn->query($sql);
	error_log("DEBUG: SALDO ANDES!");
	error_log("DEBUG: Cliente = ". $rut . " retorno = " . $retorno);
	return $retorno;	
}
function ejecuta_pendientes($username){
	$url = "http://osbcorpqa.vtr.cl:8000/consultarActividadesUsuario?wsdl";
	//prod : $url = "http://osbcorp.vtr.cl:8000/consultarActividadesUsuario?wsdl";
	$conn = db_connect(HOST, USER, PASS, DB);
	$timeout = 2;
	$retorno = '';
	
	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:con="http://osbcorp.vtr.cl/CLI/EMP/ConsultarActividadesUsuario" xmlns:con1="http://osbcorp.vtr.cl/CLI/EMP/ConsultarActividadesUsuarioReq">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <con:ConsultarActividadesUsuarioReq>
         <con1:reqConsultarActividadesUsuario>
         	<con1:estado>Pendiente</con1:estado>
            <con1:usuario>'. $username .'</con1:usuario>
         </con1:reqConsultarActividadesUsuario>
      </con:ConsultarActividadesUsuarioReq>
   </soap:Body>
	</soap:Envelope>';

	$sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_dispositivo = $row[0];

	$datos = array(
		'ws' => 'actividadespendientes',
		'dato_enviado' => $username
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];

		
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);


	if(strrpos($output, '<con2:existeActividades>false</con2:existeActividades>') > 0){
        $retorno=false;
	}elseif(strrpos($output, '<con2:existeActividades>true</con2:existeActividades>') > 0){
        $retorno=true;
	}else{
		$retorno=false;
	}

	$resultado = array(
		'error' => $error,
		'retorno' => $retorno,
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	$rs=$conn->query($sql);
	error_log("DEBUG: WS Pendiente = " . $retorno);

	return $retorno;	
}
function ejecuta_vista($username, $tipovista){
	$url = "http://osbcorpqa.vtr.cl:8000/obtenerVistasEmpleador?wsdl";
	//prod: 
	$url = "http://osbcorp.vtr.cl:8000/obtenerVistasEmpleador?wsdl";
	$conn = db_connect(HOST, USER, PASS, DB);
	$timeout = 2;
	$retorno = '';
	
	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorpqa.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:obt="http://osbcorpqa.vtr.cl/CLI/EMP/ObtenerVistasEmpleador" xmlns:obt1="http://osbcorpqa.vtr.cl/CLI/EMP/ObtenerVistasEmpleadorRequest">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <obt:obtenerVistasEmpleadorReq>
         <obt1:reqObtenerVistasEmpleadorRequest>
            <obt1:login>'. $username .'</obt1:login>
            <obt1:tipoVista>'. $tipovista .'</obt1:tipoVista>
         </obt1:reqObtenerVistasEmpleadorRequest>
      </obt:obtenerVistasEmpleadorReq>
   </soap:Body>
	</soap:Envelope>';

	$sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_dispositivo = $row[0];

	$datos = array(
		'ws' => 'vistaEmpleador',
		'dato_enviado' => $username . ' ' . $tipovista
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];
		
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);

	//echo $output;


	if(strrpos($output, '<obt2:VistasEmpleador>') > 0){
		$iapplet = '<obt2:applet>';
		$fapplet = '</obt2:applet>';
		$applet = valor_campo($output, $iapplet, $fapplet);

		$ivista = '<obt2:vista>';
		$fvista = '</obt2:vista>';
		$vista = valor_campo($output, $ivista, $fvista);

		$datos = array('error' => false,
					   'usuario' => $username,
					   'applet' => $applet,
					   'vista' => $vista,
					   'tipovista' => $tipovista);
		
        $retorno= json_encode($datos);
	}else{
		$datos = array('error' => true,
					   'usuario' => $username,
					   'applet' => '',
					   'vista' => '',
					   'tipovista' => $tipovista);
		$retorno=json_encode($datos);
	}
	$resultado = array(
		'error' => $error,
		'retorno' => substr($retorno, 1, 100),
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	$rs=$conn->query($sql);

	return $retorno;	
}
function ejecuta_actividad($rut, $propietario){
	$url = "http://osbcorpqa.vtr.cl:8000/registroDeActividad?wsdl";
	//prod $url = "http://osbcorp.vtr.cl:8000/registroDeActividad?wsdl";
	$rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
	$conn = db_connect(HOST, USER, PASS, DB);
	$timeout = 20;
	$retorno = '';
	
	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:reg="http://osbcorp.vtr.cl/CLI/EMP/RegistroDeActividad">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <reg:RegistroDeActividadRequest>
         <reg:rutCliente>'. $rut .'</reg:rutCliente>
         <reg:tipoInteraccion>Llamada Entrante - Sucursal</reg:tipoInteraccion>
         <reg:razonInteraccion>Canal Sucursal</reg:razonInteraccion>
         <reg:detalleRazonInteraccion></reg:detalleRazonInteraccion>
         <reg:identificacionInteraccionIVR></reg:identificacionInteraccionIVR>
         <reg:descripcionInteraccion>Cliente es atendido en la sucursal</reg:descripcionInteraccion>
         <reg:razonInteraccionDiscador></reg:razonInteraccionDiscador>
         <reg:interaccionANI></reg:interaccionANI>
         <reg:resolucion></reg:resolucion>
         <reg:usuarioPropietario>'. $propietario .'</reg:usuarioPropietario>
      </reg:RegistroDeActividadRequest>
   </soap:Body>
	</soap:Envelope>';

	$sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_dispositivo = $row[0];

	$datos = array(
		'ws' => 'registroDeActividad',
		'dato_enviado' => $rut . ' ' . $propietario
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];

	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);

	//echo $output;

	if(strrpos($output, '<reg:identificadorInteraccion>') > 0){
		$cabecera = '<reg:identificadorInteraccion>';
		$pies = '</reg:identificadorInteraccion>';
		$identificador = valor_campo($output, $cabecera, $pies);

		$datos = array(
			'error' => false,
			'identificador' => $identificador
		);

        $retorno = json_encode($datos);
	}else{
		$datos = array(
			'error' => true, 
			'identificador' => 0
		);
		
		$retorno = json_encode($datos);
	}

	$resultado = array(
		'error' => $error,
		'retorno' => substr($retorno, 1, 100),
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	$rs=$conn->query($sql);

	return $retorno;	
}
function ejecuta_perfil($rut){
	//return '';
	//exit();

	//$url = "http://osbcorpqa.vtr.cl:8000/consultarPerfilCliente?wsdl";
	// prod:
	 $url = "http://osbcorp.vtr.cl:8000/consultarPerfilCliente?wsdl";
	$rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
	$conn = db_connect(HOST, USER, PASS, DB);
	$timeout = 5;
	$retorno = '';
	
	$request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:con="http://osbcorp.vtr.cl/CLI/EMP/consultarPerfilCliente" xmlns:con1="http://osbcorp.vtr.cl/CLI/EMP/consultarPerfilClienteReq">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <con:consultarPerfilClienteReq>
         <con1:reqConsultarPerfilCliente>
            <!--You have a CHOICE of the next 2 items at this level-->
            <con1:rutCliente>'. $rut .'</con1:rutCliente>
            
         </con1:reqConsultarPerfilCliente>
      </con:consultarPerfilClienteReq>
   </soap:Body>
   </soap:Envelope>';

   	$sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_dispositivo = $row[0];

	$datos = array(
		'ws' => 'perfilCliente',
		'dato_enviado' => $rut 
	);

	$sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
	//error_log('DEBUG: SQL = ' . $sql);
	$rs = $conn->query($sql);
	$row = $rs->fetch();
	$id_logws = $row[0];

		
	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_SSLVERSION, 3);

	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
	curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

	curl_setopt($ch, CURLOPT_VERBOSE, true);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

	$output = curl_exec ($ch);
	$error = curl_error($ch);
	curl_close($ch);

	//error_log("Perfil Cliente OUTPUT:"  . $output);
	//error_log("Perfil Cliente error:"  .$error);

	if(strrpos($output, 'con2:identificadorCliente>') > 0){
		$cabecera = '<con2:identificadorCliente>';
		$pies = '</con2:identificadorCliente>';
		$rowid = valor_campo($output, $cabecera, $pies);

		$inombre = '<con2:nombreCliente>';
		$fnombre = '</con2:nombreCliente>';
		$nombre = valor_campo($output, $inombre, $fnombre);

		$ipaterno = '<con2:apellidoPaterno>';
		$fpaterno = '</con2:apellidoPaterno>';
		$paterno  = valor_campo($output, $ipaterno, $fpaterno);

		$imaterno = '<con2:apellidoMaterno>';
		$fmaterno = '</con2:apellidoMaterno>';
		$materno = valor_campo($output, $imaterno, $fmaterno);

		$datos = array(
			'error' => false,
			'rowid' => $rowid,
			'nombre' => $nombre . ' ' . $paterno . ' ' . $materno
		);

        $retorno = json_encode($datos);
	}else{
		$datos = array(
			'error' => true, 
			'rowid' => 0,
			'nombre' => ''
		);
		$retorno = json_encode($datos);
	}

	$resultado = array(
		'error' => $error,
		'retorno' => substr($retorno, 1, 100),
		'timeout' => $timeout
	);
	$sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
	$rs=$conn->query($sql);

	return $retorno;	
}
function get_estado($tipo){
	$conn = db_connect(HOST, USER, PASS, DB);
	$area = AREA;
	$sSql= "select t02_configuracion_general as cfg from t02_area where t02_id_area = $area";	

	$result=$conn->query($sSql);
	$row = $result->fetch();		
	$cfg=$row["cfg"];
	//error_log("DEBUG: CFG = " . $cfg);
	if($tipo == "migradb"){
		$estado = valor_campo($cfg, '<migradb>', '</migradb>') === "1";
	}elseif($tipo == 'ldap'){
		$estado = valor_campo($cfg, '<ldap>', '</ldap>') === "1";
	}elseif($tipo == 'andes'){
		$estado = valor_campo($cfg, '<andes>', '</andes>') === "1";
	}elseif($tipo == 'saldoandes'){
		$estado = valor_campo($cfg, '<saldoandes>', '</saldoandes>') === "1";
	}

	return $estado;
}


function ejecuta_campanaSMA($rut){
        $url = "http://osbcorpqa.vtr.cl:8000/consultarCampanasSMA?wsdl";
        // prod:
        $url = "http://osbcorp.vtr.cl:8000/consultarCampanasSMA?wsdl";
        $rut = number_format( substr ( $rut, 0 , -1 ) , 0, "", "") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
        $conn = db_connect(HOST, USER, PASS, DB);
        $timeout = 5;
        $retorno = '';

        $request = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:head="http://osbcorp.vtr.cl/GLOBAL/EMP/HeaderRequest" xmlns:con="http://osbcorp.vtr.cl/CLI/EMP/ConsultarCampanasSMA" xmlns:con1="http://osbcorp.vtr.cl/CLI/EMP/ConsultarCampanasSMAReq">
   <soap:Header>
      <head:HeaderRequest>
         <head:Username>?</head:Username>
         <head:Company>?</head:Company>
         <head:AppName>?</head:AppName>
         <head:IdClient>?</head:IdClient>
         <head:ReqDate>'.date('Y-m-d').'T'.date('H:i:s').'</head:ReqDate>
      </head:HeaderRequest>
   </soap:Header>
   <soap:Body>
      <con:ConsultarCampanasSMAReq>
         <con1:reqConsultarCampanasSMA>
            <con1:rutPersona>'. $rut .'</con1:rutPersona>
            <con1:codigoPuestoTrabajo>TOTEM</con1:codigoPuestoTrabajo>
         </con1:reqConsultarCampanasSMA>
      </con:ConsultarCampanasSMAReq>
   </soap:Body>
</soap:Envelope>';

        $sql = 'select gc13_id_dispositivo from gc13_dispositivo where gc13_estado = 1 and gc13_tipo = 5 limit 1;';

        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_dispositivo = $row[0];

        $datos = array(
                'ws' => 'CampanaSMA',
                'dato_enviado' => $rut
        );

        $sql = "insert into gc17_log_ws (gc13_id_dispositivo, gc17_comando, gc17_inicio) values (" . $id_dispositivo . ", '" . json_encode($datos) . "', now()) RETURNING gc17_id_log";
        //error_log('DEBUG: SQL = ' . $sql);
        $rs = $conn->query($sql);
        $row = $rs->fetch();
        $id_logws = $row[0];


        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array("content-type: content=text/xml"));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);

        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);


        $output = curl_exec ($ch);
        $error = curl_error($ch);
        curl_close($ch);
        $oferta="";
        if(strrpos($output, '<con2:scriptAccion>') > 0){
                $cabecera = '<con2:scriptAccion>';
                $pies = '</con2:scriptAccion>';
                $rowid = valor_campo($output, $cabecera, $pies);

                $oferta  = valor_campo($output, $cabecera, $pies);
                error_log("Oferta-->" . $oferta);
                /*$datos = array(
                        'error' => false,
                        'rowid' => 0,
                        'oferta' => $oferta
                );
                $retorno = json_encode($datos);*/
        }else{
                $datos = array(
                        'error' => true,
                        'rowid' => 0,
                        'oferta' => ''
                );
                $retorno = json_encode($datos);
        }
        $resultado = array(
                'error' => $error,
                'retorno' => substr($retorno, 1, 100),
                'timeout' => $timeout
        );
        $sql = "update gc17_log_ws set gc17_respuesta = '" . json_encode($resultado) . "' , gc17_fin = now() where gc17_id_log = " . $id_logws;
        $rs=$conn->query($sql);

        $retorno=$oferta;
        return $retorno;
}
?>
