<?php

declare(strict_types=1);

namespace Nexius\Milenio\WS\MPM;

use DateTime;
use DateTimeZone;
use Nexius\Milenio\Curl\Curl;
use SimpleXMLElement;

class Segelevia
{
    /**
     * @var string
     */
    private $urlWS;
    /**
     * @var string
     */
    private $user;
    /**
     * @var string
     */
    private $pass;
    /**
     * @var int
     */
    private $companyCode;

    private $tokenGenerator;

    private $xmlRequest;

    private $urlSegelevia;

    private $loginUsername;

    private $usuarioId;
    
    public function __construct()
    {
        ini_set('display_errors', '1');
        ini_set('display_startup_errors', '1');
        error_reporting(E_ALL);

        $this->tokenGenerator = new TokenGen();

        //$this->urlWS = 'http://iberia.bmsgroup.com:8080/SegServices/Services';
        $this->urlWS = 'http://segelevia.bmsgroup.com:8080/SegServices/Services';
        $this->companyCode = '4253';
        $this->loginUsername = 'administrador';
        $this->usuarioId = '771';
        $this->urlSegelevia = 'https://segelevia.bmsgroup.com/';
        //$this->urlSegelevia = 'https://segelevia.bmslab.uk/';
    }

    public function ponerEntornoPruebas()
    {
        $this->urlWS = 'http://segeleviapre.bmsgroup.com:8080/SegServices/Services';
        $this->urlSegelevia = 'https://segeleviapre.bmsgroup.com/';
        //$this->urlSegelevia = 'https://segeleviapre.bmslab.uk/';
        
        return $this->urlSegelevia;
    }
    public function dameEntorno()
    {
        return $this->urlWS;
    }

    public function getLastRequest()
    {
        $lastRequest = $this->xmlRequest;

        $lastRequest = str_replace("s:", "", $lastRequest);
        $lastRequest = str_replace("c:", "", $lastRequest);
        $lastRequest = str_replace("a:", "", $lastRequest);
        $lastRequest = str_replace("b:", "", $lastRequest);
        $lastRequest = str_replace("i:", "", $lastRequest);
        $lastRequest = str_replace("z:", "", $lastRequest);

        return @(new SimpleXMLElement($lastRequest));
    }

    private function getXML(array $config)
    {
        $serviceKeyToken = $this->tokenGenerator->generate($this->npmTimestamp());
        $this->xmlRequest = file_get_contents('templates/' . $config['xml'], (boolean)FILE_USE_INCLUDE_PATH);
        return str_replace("{{serviceKeyValidation}}", $serviceKeyToken, $this->xmlRequest);
    }

    public function reportaLog($suscripcion,$log)
    {
        $log = urlencode($log);
        $suscripcion = urlencode($suscripcion);
        $url = 'https://ts2.milenio.es/colectivos24/funciones/funcionesSegelevia_Log.php?pass=luis14&ids='.$suscripcion.'&texto='.$log;
        $response = file_get_contents($url,TRUE);
        echo "<br>Log realizado".$response."<br>";
    }

    public function findByNif($nif): SimpleXMLElement
    {
        $config = [
            'xml' => 'findByNifCliente.xml',
            'endpoint' => $this->urlWS . '/Figuras/ClienteServiceDTO.svc',
            'action' => 'IClienteServiceDTO/FindByNif'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{nif}}", $nif, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar cliente');
    }

    public function FindUsingPropertyGenericCliente($alias): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindUsingPropertyGenericCliente.xml',
            'endpoint' => $this->urlWS . '/Figuras/ClienteServiceDTO.svc',
            'action' => 'IGenericRootServiceDTOOf_ClienteDTO/FindUsingPropertyGeneric'
        ];
        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{value}}", $alias, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar cliente por su alias');
    }
    public function findByPoliza($idPoliza, $nif, $oficode): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindIdPoliza.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/FindIdPolizaByNumPolizaAndNifClienteAndOficode'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{nif}}", $nif, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{oficinaId}}", $oficode, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar poliza');
    }
    public function findByIdGenericPoliza($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindIdGenericPoliza.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IGenericServiceDTOOf_PolizaDTO/FindByIdGeneric'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar poliza solo por Id');
    }

    public function obtenerPolizaEditable($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'ObtenerPolizaEditable.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/ObtenerPolizaEditable'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'ObtenerPolizaEditable por Id');
    }

    public function FindPolizaBaseById($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindPolizaBaseById.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/FindPolizaBaseById'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar poliza solo por Id');
    }

    public function FilteredFindPoliza($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'FilteredFind.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/FilteredFind'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{searchData}}", $idPoliza, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{compania_Alias}}", "", $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Buscar poliza solo por Id');
    }

    public function FilteredFindCompania($aliascompania): SimpleXMLElement
    {
        $config = [
            'xml' => 'FilteredFind.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/FilteredFind'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{pol_id}}", "", $this->xmlRequest);
        $this->xmlRequest = str_replace("{{searchData}}", $aliascompania, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{compania_Alias}}", $aliascompania, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Buscar poliza solo por Id');
    }

    public function findByAliasColaborador($alias): SimpleXMLElement
    {
        $config = [
            'xml' => 'findByAliasColaborador.xml',
            'endpoint' => $this->urlWS . '/Figuras/ColaboradorServiceDTO.svc',
            'action' => 'IColaboradorServiceDTO/FindByAlias'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{alias}}", $alias, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar colaborador o asociacion por Alias');
    }

    public function findByIdGenericRecibo($idRecibo): SimpleXMLElement
    {
        $config = [
            'xml' => 'findByIdGenericRecibo.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/FindReciboCalculated'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{rec_id}}", $idRecibo, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar recibo solo por Id');
    }

    public function ObtenerContratoDePoliza($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'ObtenerContratoDePoliza.xml',
            'endpoint' => $this->urlWS . '/ReportManager/ReportComponentDefinitionServiceDTO.svc',
            'action' => 'IReportComponentDefinitionServiceDTO/FindElementsSimple'
        ];

        $this->xmlRequest = $this->getXML($config);
        //$this->xmlReques = str_replace("{{companyCode}}",  $this->companyCode, $this->xmlReques);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Obtener Contrato de Poliza FindElementsSimple');
    }

    public function ObtenerContratoDeDomiciliacion($idDomiciliacion): SimpleXMLElement
    {
        $config = [
            'xml' => 'ObtenerContratoDeDomiciliacion.xml',
            'endpoint' => $this->urlWS . '/ReportManager/ReportComponentDefinitionServiceDTO.svc',
            'action' => 'IReportComponentDefinitionServiceDTO/FindElementsSimple'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{domic_id}}", $idDomiciliacion, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Obtener Contrato de Domiciliacion FindElementsSimple');
    }
    public function FirmarContratoDeDomiciliacion($idContratoDomiciliacion): SimpleXMLElement
    {
        $config = [
            'xml' => 'FirmarContratoDeDomiciliacion.xml',
            'endpoint' => $this->urlWS . '/General/Contratos/GestionContratoServiceDTO.svc',
            'action' => 'IGestionContratoServiceDTO/FirmarContrato'
        ];
        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{idContratoDomiciliacion}}", $idContratoDomiciliacion, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Firmar Contrato de Domiciliacion');
    }   

    public function ObtenerRecibosDePoliza($idPoliza): SimpleXMLElement
    {
        $config = [
            'xml' => 'ObtenerRecibosDePoliza.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/ObtenerRecibosDePoliza'
        ];

        $this->xmlRequest = $this->getXML($config);
        //$this->xmlReques = str_replace("{{companyCode}}",  $this->companyCode, $this->xmlReques);
        $this->xmlRequest = str_replace("{{pol_id}}", $idPoliza, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Obtener Recibos de Poliza');
    }
    public function findByIdGenericEjecutivo($idEjecutivo): SimpleXMLElement
    {
        $config = [
            'xml' => 'findByIdGenericEjecutivo.xml',
            'endpoint' => $this->urlWS . '/Figuras/EjecutivoServiceDTO.svc',
            'action' => 'IGenericServiceDTOOf_EjecutivoDTO/FindByIdGeneric'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{idEjecutivo}}", $idEjecutivo, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar ejecutivo');
    }

    public function crearCliente($data): SimpleXMLElement
    {
        if ( isset($data['ejecutivo'])){
            $ejecutivo = $this->findByIdGenericEjecutivo($data['ejecutivo']);
            $ConEjecutivo = true;
        } else {
            $ConEjecutivo = False;
        }
        if ($ConEjecutivo) {
            $config = [
                'xml' => 'crearCliente.xml',
                'endpoint' => $this->urlWS . '/Figuras/ClienteServiceDTO.svc',
                'action' => 'IClienteServiceDTO/CrearCliente'
            ];
        } else{
            $config = [
                'xml' => 'crearClienteSinEjecutivo.xml',
                'endpoint' => $this->urlWS . '/Figuras/ClienteServiceDTO.svc',
                'action' => 'IClienteServiceDTO/CrearCliente'
            ];
        }

        $this->xmlRequest = $this->getXML($config);
        
        if ($ConEjecutivo && !empty((string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->Id)) {
            echo 'Hay ejecutivo<br>';
            $this->xmlRequest = str_replace("{{ejecutivo}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->Id, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{creationDate_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->CreationDate, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{alias_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->Alias, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{autCodigo_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->AutCodigo, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{codigoOficina_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->CodigoOficina, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{estado_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->Estado, $this->xmlRequest);
            $this->xmlRequest = str_replace("{{nombre_Eje}}", (string)$ejecutivo->Body->FindByIdGenericResponse->FindByIdGenericResult->Data->Nombre, $this->xmlRequest);
        } 

        $this->xmlRequest = str_replace("{{Nif}}", $data['Nif'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Nombre}}", $data['Nombre'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Apellido1}}", $data['Apellido1'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Apellido2}}", $data['Apellido2'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Nacimiento}}", $data['Nacimiento'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{FechaAlta}}", $data['FechaAlta'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{Alias}}", $data['Nif'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{TelfMovil}}", $data['TelfMovil'], $this->xmlRequest);
        if (isset($data['TelfPal'])) {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfPal'], $this->xmlRequest);
        } else {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfMovil'], $this->xmlRequest);
        }
        
        $this->xmlRequest = str_replace("{{Entidad}}", $data['Entidad'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{oficinaId}}", $data['oficinaId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{oficinaComercialId}}", $data['oficinaComercialId'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{NombreDireccion}}", $data['NombreDireccion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{CodigoPostal}}", $data['CodigoPostal'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{LocalidadCP}}", $data['LocalidadCP'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Localidad}}", $data['LocalidadCP'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Provincia}}", $data['Provincia'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Email}}", $data['Email'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{IbanCli}}", $data['IbanCli'], $this->xmlRequest);
        //$this->xmlRequest = str_replace("{{ejecutivo}}", $data['ejecutivo'], $this->xmlRequest);


        return Curl::send($config, $this->xmlRequest, 'Crear cliente');
    }

    public function editarDireccion($data,$idDireccionPoliza, $aliasDireccionPoliza, $esPrincipal): SimpleXMLElement
    {
        $config = [
            'xml' => 'editarDireccion.xml',
            'endpoint' => $this->urlWS . '/General/DireccionServiceDTO.svc',
            'action' => 'IDireccionServiceDTO/EditarDireccion'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{clientId}}", $data['clientId'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{idDireccionPoliza}}", $idDireccionPoliza, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{aliasDireccionPoliza}}", $aliasDireccionPoliza, $this->xmlRequest);

        $this->xmlRequest = str_replace("{{NombreDireccion}}", $data['NombreDireccion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{CodigoPostal}}", $data['CodigoPostal'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Localidad}}", $data['LocalidadCP'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Provincia}}", $data['Provincia'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Email}}", $data['Email'], $this->xmlRequest);
        if (isset($data['TelfPal'])) {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfPal'], $this->xmlRequest);
        } else {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfMovil'], $this->xmlRequest);
        }
        $this->xmlRequest = str_replace("{{TelfMovil}}", $data['TelfMovil'], $this->xmlRequest);        
        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{esPrincipal}}", $esPrincipal, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Editar direccion');
    }

        public function editarDireccionCliente($data,$idDireccionPoliza, $aliasDireccionPoliza, $esPrincipal): SimpleXMLElement
    {
        $config = [
            'xml' => 'editarDireccionCliente.xml',
            'endpoint' => $this->urlWS . '/General/DireccionServiceDTO.svc',
            'action' => 'IDireccionServiceDTO/EditarDireccionCliente'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{clientId}}", $data['clientId'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{idDireccionPoliza}}", $idDireccionPoliza, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{aliasDireccionPoliza}}", $aliasDireccionPoliza, $this->xmlRequest);

        $this->xmlRequest = str_replace("{{NombreDireccion}}", $data['NombreDireccion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{CodigoPostal}}", $data['CodigoPostal'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Localidad}}", $data['LocalidadCP'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Provincia}}", $data['Provincia'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Email}}", $data['Email'], $this->xmlRequest);
        if (isset($data['TelfPal'])) {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfPal'], $this->xmlRequest);
        } else {
            $this->xmlRequest = str_replace("{{TelfPal}}", $data['TelfMovil'], $this->xmlRequest);
        }
        $this->xmlRequest = str_replace("{{TelfMovil}}", $data['TelfMovil'], $this->xmlRequest);        
        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{esPrincipal}}", $esPrincipal, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Editar direccion Cliente');
    }
    public function obtenerDireccionesCliente($idCliente): SimpleXMLElement
    {
        $config = [
            'xml' => 'ObtenerDireccionesCliente.xml',
            'endpoint' => $this->urlWS . '/General/DireccionServiceDTO.svc',
            'action' => 'IDireccionServiceDTO/GetDireccionesCliente'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{clientId}}", $idCliente, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Obtener direcciones del cliente');
    }

    public function obtenerIdDireccionporAlias($respuestaXML,$alias) {
        if (!isset($respuestaXML->Body->GetDireccionesClienteResponse->GetDireccionesClienteResult->DireccionDTO)) {
            return null; // No hay direcciones
        }
        $direcciones = $respuestaXML->Body->GetDireccionesClienteResponse->GetDireccionesClienteResult->DireccionDTO;
        foreach ($direcciones as $direccion) {
            if ((string)$direccion->Alias === $alias) {
                return (string)$direccion->Id;
            }
        }
        return null; // No se encontró una dirección con alias "Principal"
    }

    public function eliminarDireccionCliente($idDireccion): SimpleXMLElement
    {
        $config = [
            'xml' => 'EliminarDireccionCliente.xml',
            'endpoint' => $this->urlWS . '/General/DireccionServiceDTO.svc',
            'action' => 'IDireccionServiceDTO/Eliminar'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{idDireccion}}", $idDireccion, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Eliminar direccion del cliente');
    }

    public function crearPolizaBasico($data): SimpleXMLElement
    {
        $config = [
            'xml' => 'crearPoliza.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/CrearPolizaBasico'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{clientId}}", $data['clientId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{companiaId}}", $data['companiaId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{productoId}}", $data['productoId'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{oficinaId}}", $data['oficinaId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{oficinaComercialId}}", $data['oficinaComercialId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoGestion}}", $data['tipoGestion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorId}}", $data['gestorId'], $this->xmlRequest);
        if (isset($data['ejecutivo'])){
            $this->xmlRequest = str_replace("{{ejecutivo}}", $data['ejecutivo'], $this->xmlRequest);
        }else {
            $this->xmlRequest = str_replace("<ejecutivo>{{ejecutivo}}</ejecutivo>", "", $this->xmlRequest);
        }
        $this->xmlRequest = str_replace("{{ejecutivo}}", isset($data['ejecutivo']) ? $data['ejecutivo'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{numPoliza}}", $data['numPoliza'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoRiesgo}}", $data['tipoRiesgo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{iban}}", $data['Iban'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaAlta}}", $data['FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaVencimiento}}", $data['FechaVencimiento'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{NombreDireccion}}", $data['NombreDireccion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{CodigoPostal}}", $data['CodigoPostal'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Localidad}}", $data['LocalidadCP'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Provincia}}", $data['Provincia'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Email}}", $data['Email'], $this->xmlRequest);
        
        $this->xmlRequest = str_replace("{{descripcionRiesgo}}", $this->limpiaParaSegelevia($data['descripcionRiesgo']), $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Matricula}}",  $this->limpiaParaSegelevia($data['Matricula']), $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Marca}}", $this->limpiaParaSegelevia($data['Marca']), $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Modelo}}", $this->limpiaParaSegelevia($data['Modelo']), $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Valor}}", $data['valorVehiculo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{UsoVehiculo}}", $data['usoVehiculo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaCompra}}", $data['fechaCompra'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoVehiculoId}}", $data['tipoVehiculoId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Version}}", $data['version'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);

        //Parte de codeoscopic
        $this->xmlRequest = str_replace("{{ConductorApellido1}}", isset($data['conductorApellido1']) ? $data['conductorApellido1'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorApellido2}}", isset($data['conductorApellido2']) ? $data['conductorApellido2'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorFechaCarnet}}", isset($data['conductorFechaCarnet']) ? $data['conductorFechaCarnet'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorFechaNacimiento}}", isset($data['conductorFechaNacimiento']) ? $data['conductorFechaNacimiento'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorNIF}}", isset($data['conductorNif']) ? $data['conductorNif'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorNombre}}", isset($data['conductorNombre']) ? $data['conductorNombre'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ConductorSexo}}", isset($data['conductorSexo']) ? $data['conductorSexo'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PropietarioApellido1}}", isset($data['propietarioApellido1']) ? $data['propietarioApellido1'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PropietarioApellido2}}", isset($data['propietarioApellido2']) ? $data['propietarioApellido2'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PropietarioNIF}}", isset($data['propietarioNif']) ? $data['propietarioNif'] : '', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PropietarioNombre}}", isset($data['propietarioNombre']) ? $data['propietarioNombre'] : '', $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Crear poliza');

    }

    public function reasignarFiguras($id,$idColaborador1,$ejecutivo): SimpleXMLElement
    {
        $config = [
            'xml' => 'ReasignarFiguras.xml',
            'endpoint' => $this->urlWS . '/Polizas/PolizaServiceDTO.svc',
            'action' => 'IPolizaServiceDTO/ReasignarFiguras'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{pol_id}}", $id, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{idColaborador1}}", $idColaborador1, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{ejecutivo}}", $ejecutivo, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Reasignar colaborador poliza');

    }

    public function reasignarFigurasRecibos($idRecibo,$idColaborador1,$ejecutivo): SimpleXMLElement
    {
        $config = [
            'xml' => 'ReasignarFigurasRecibos.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/ReasignarFiguras'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{idRecibo}}", $idRecibo, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{idColaborador1}}", $idColaborador1, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Reasignar colaborador recibo');

    }

    public function prepararMatriz($data): SimpleXMLElement
    {
        $config = [
            'xml' => 'PrepararMatriz.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/PrepararMatriz'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{pol_id}}", $data['pol_Id'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaAlta}}", $data['poliza_FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaVencimiento}}", $data['poliza_FechaVencimiento'], $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Preparar matriz recibo');
    }

    public function EditarRecibo($data): SimpleXMLElement
    {
        $config = [
            'xml' => 'EditarRecibo.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/Editar'
        ];
        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{recibo_id}}", $data['recibo_id'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{numeroRecibo}}", $data['numeroRecibo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaAlta}}", $data['poliza_FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaVencimiento}}", $data['poliza_FechaVencimiento'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{pol_id}}", $data['pol_Id'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PrimaNetaAnual}}", $data['PrimaNetaAnual'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{PrimaTotalAnual}}", $data['PrimaTotalAnual'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{impuesto}}", $data['impuesto'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{consorcio}}", $data['consorcio'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{comisionCorreduria}}", $data['comisionCorreduria'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{descuento}}", $data['descuento'], $this->xmlRequest);
        
        $this->xmlRequest = str_replace("{{totalPagarCalcularDescuento}}", isset($data['totalPagarCalcularDescuento']) ? $data['totalPagarCalcularDescuento'] : '0', $this->xmlRequest);
        $this->xmlRequest = str_replace("{{oficinaId}}", $data['oficinaId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorId}}", $data['gestorId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoGestion}}", $data['tipoGestion'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{TipoRecibo}}", $data['tipoRecibo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{codigoReciboCompania}}", $data['referenciaRecibo'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{gestorAlias}}", $data['gestorAlias'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorAutCodigo}}", $data['gestorAutCodigo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorSituacionRecibo}}", $data['gestorSituacionRecibo'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorformaCobro}}", $data['gestorformaCobro'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorReciboTipo}}", $data['gestorReciboTipo'], $this->xmlRequest);

        $this->xmlRequest = str_replace("{{clientId}}", $data['clientId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Nif}}", $data['Nif'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Nombre}}", $data['Nombre'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Apellido1}}", $data['Apellido1'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{Apellido2}}", $data['Apellido2'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{iban}}", $data['Iban'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{domiciliacionAlias}}", $data['domiciliacionAlias'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaCreacion}}", $this->fechas_segelevia(date("d-m-Y")),$this->xmlRequest);

        $this->xmlRequest = str_replace("{{bicId}}", $data['bicId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{bicCode}}", $data['bicCode'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{bicCodigoBanco}}", $data['bicCodigoBanco'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{bicNombreBanco}}", $data['bicNombreBanco'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{bicPais}}", $data['bicPais'], $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Editar recibo');
    }
    public function CobroTotalRecibo($data): SimpleXMLElement
    {
        $config = [
            'xml' => 'CobroTotalRecibo.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/CobroTotalRecibo'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{recibo_id}}", $data['recibo_id'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorId}}", $data['gestorId'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaCobro}}", $data['FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{formaCobro}}", $data['gestorformaCobro'], $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Cobrado recibo');
    }

    public function CobroParcialRecibo($data,$importe,$formaCobro,$gestorId): SimpleXMLElement
    {
        $config = [
            'xml' => 'CobroParcialRecibo.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/CobroParcialRecibo'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{recibo_id}}", $data['recibo_id'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{importe}}", $importe, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{gestorId}}", $gestorId, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaCobro}}", $data['FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{formaCobro}}", $formaCobro, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Cobro recibo parcial');
    }

    public function facturarMatriz($data): SimpleXMLElement
    {
        $config = [
            'xml' => 'FacturarMatriz.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IReciboServiceDTO/FacturarMatriz'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{recibo_id}}", $data['recibo_id'], $this->xmlRequest);
        //$this->xmlRequest = str_replace("{{fechaAlta}}", $data['FechaAlta'], $this->xmlRequest);
        $this->xmlRequest = str_replace("{{fechaAlta}}", $this->fechas_segelevia(date("d-m-Y")), $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Facturada matriz recibo');
    }

    public function AsignarCriterio($tipo, $id, $conceptoId, $texto): SimpleXMLElement
    {   //$tipo=1 para clientes y $tipo=7 para pólizas
        //$id es el id o del cliente o de la póliza
        $config = [
            'xml' => 'AsignarValorCriterioService.xml',
            'endpoint' => $this->urlWS . '/General/CriterioServiceDTO.svc',
            'action' => 'ICriterioServiceDTO/AsignarValor'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoobjeto}}", $tipo, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{id}}", $id, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{conceptoId}}", $conceptoId, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{texto}}", $texto, $this->xmlRequest);

        if ($tipo == '1') {
            return Curl::send($config, $this->xmlRequest, 'Asignar criterio cliente');
        } else {
            return Curl::send($config, $this->xmlRequest, 'Asignar criterio poliza');
        }
    }

    public function findUsingPropertyGenericRecibo($numrecibo): SimpleXMLElement
    {
        $config = [
            'xml' => 'findUsingPropertyGenericRecibo.xml',
            'endpoint' => $this->urlWS . '/Recibos/ReciboServiceDTO.svc',
            'action' => 'IGenericRootServiceDTOOf_ReciboDTO/FindUsingPropertyGeneric'
        ];

        $this->xmlRequest = $this->getXML($config);

        // $this->xmlReques = str_replace("{{companyCode}}",  $this->companyCode, $this->xmlReques);
        // $this->xmlReques = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlReques);
        $this->xmlRequest = str_replace("{{value}}", $numrecibo, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'findUsingPropertyGenericRecibo');
    }

    public function FindUsingPropertyUniqueGenericSiniestro($numSiniestro): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindUsingPropertyUniqueGenericSiniestro.xml',
            'endpoint' => $this->urlWS . '/Siniestros/SiniestroServiceDTO.svc',
            'action' => 'IGenericRootServiceDTOOf_SiniestroDTO/FindUsingPropertyUniqueGeneric'
        ];

        $this->xmlRequest = $this->getXML($config);

        // $this->xmlReques = str_replace("{{companyCode}}",  $this->companyCode, $this->xmlReques);
        // $this->xmlReques = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlReques);
        $this->xmlRequest = str_replace("{{value}}", $numSiniestro, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'FindUsingPropertyUniqueGenericSiniestro');
    }
    public function FindByCodigoGestordeCobro($AutCodigo): SimpleXMLElement
    {
        $config = [
            'xml' => 'FindByCodigoGestordeCobro.xml',
            'endpoint' => $this->urlWS . '/Figuras/GestorDeCobroServiceDTO.svc',
            'action' => 'IGestorDeCobroServiceDTO/FindByCodigo'
        ];

        $this->xmlRequest = $this->getXML($config);
        $this->xmlRequest = str_replace("{{AutCodigo}}", $AutCodigo, $this->xmlRequest);
        return Curl::send($config, $this->xmlRequest, 'Buscar Gestor de Cobro');
    }
    public function CrearDocumento($tipo_obj, $id_obj, $nombreDocumento): SimpleXMLElement
    {
        $config = [
            'xml' => 'CrearDocumento.xml',
            'endpoint' => $this->urlWS . '/General/ArchivoDocumentalServiceDTO.svc',
            'action' => 'IArchivoDocumentalServiceDTO/CrearDocumento'
        ];
        /*
        tipo_obj:
        Clientes = 1
        Polizas = 7
        Recibos = 10
        Riesgos = 11
        Siniestros = 13
        Suplementos = 14
        */
        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{id_obj}}", $id_obj, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipo_obj}}", $tipo_obj, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{nombreDocumento}}", $nombreDocumento, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{publicablecli}}", "false", $this->xmlRequest);
        $this->xmlRequest = str_replace("{{publicable}}", "true", $this->xmlRequest);

        //$this->xmlReques = str_replace("{{observacionesDocumento}}", $observacionesDocumento, $this->xmlReques);

        return Curl::send($config, $this->xmlRequest, 'Crear Documento');
    }

    public function CrearDocumentoRobot($tipo_obj, $id_obj, $nombreDocumento, $publicarParaPerfilCliente): SimpleXMLElement
    {
        $config = [
            'xml' => 'CrearDocumento.xml',
            'endpoint' => $this->urlWS . '/General/ArchivoDocumentalServiceDTO.svc',
            'action' => 'IArchivoDocumentalServiceDTO/CrearDocumento'
        ];
        /*
        tipo_obj:
        Clientes = 1
        Polizas = 7
        Recibos = 10
        Riesgos = 11
        Siniestros = 13
        Suplementos = 14
        */
        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{id_obj}}", $id_obj, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipo_obj}}", $tipo_obj, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{nombreDocumento}}", $nombreDocumento, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{publicablecli}}", $publicarParaPerfilCliente, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{publicable}}", "true", $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Crear Documento');
    }

    public function SubirDocumento($idArchivo, $documentContent): SimpleXMLElement
    {
        $config = [
            'xml' => 'SubirDocumento.xml',
            'endpoint' => $this->urlWS . '/General/ArchivoDocumentalServiceDTO.svc',
            'action' => 'IArchivoDocumentalServiceDTO/SubirDocumento'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{loginUsername}}", $this->loginUsername, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{idArchivo}}", $idArchivo, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{archivo}}", $documentContent, $this->xmlRequest);

        return Curl::send($config, $this->xmlRequest, 'Subir Documento');
    }

    public function GuardarDocumentoSegeleviadeURL($tipo_obj, $id_obj, $nombre, $numPoliza, $url)
    {
        /*
        tipo_obj:
        Clientes = 1
        Polizas = 7
        Recibos = 10
        Riesgos = 11
        Siniestros = 13
        Suplementos = 14
        */
        $pdf = base64_encode(file_get_contents($url, TRUE));
        if ($pdf) {            
            $nombreDocumento = $nombre . '_' . $numPoliza . '.pdf';
            $documento = $this->CrearDocumento($tipo_obj, $id_obj, $nombreDocumento);
            $respuesta = (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Success;
            if ($respuesta) {
                $idDocumento = (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Data->Id;
                echo "<br>Id del documento real= $idDocumento <br>";
                $documento = $this->SubirDocumento($idDocumento, $pdf);
                $respuesta = (string)$documento->Body->SubirDocumentoResponse->SubirDocumentoResult->Success;
                if ($respuesta) {
                    echo "<br>Documento $nombreDocumento añadido<br>";
                    echo "<a href=".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Polizas.Poliza.PolizaDataPanel?_pageRender_pol_id=$id_obj#gestion target=_blank>".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Polizas.Poliza.PolizaDataPanel?_pageRender_pol_id=$id_obj#gestion</a><br><br>";
                    return "Sucess";

                } else {
                    echo "<br>Error: Documento $nombreDocumento  NO añadido por ".(string)$documento->Body->SubirDocumentoResponse->SubirDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField."<br>";
                    return (string)$documento->Body->SubirDocumentoResponse->SubirDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField;
                }
            } else{
                echo "<br>Error: Documento $nombreDocumento  NO añadido por ".(string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField."<br>";
                return (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField;
            }
        } else {
            echo "<br>Error: Documento $nombre  No ha podido recuperarse de la compañía<br>";
            return "Error: Documento $nombre  No ha podido recuperarse de la compañía";
        }
    }

    public function GuardarDocumentoSegeleviadeRobot($tipo_obj, $id_obj, $nombre, $pdf, $publicarParaPerfilCliente)
    {
        /*
        tipo_obj:
        Clientes = 1
        Polizas = 7
        Recibos = 10
        Riesgos = 11
        Siniestros = 13
        Suplementos = 14
        */
        //$nombreDocumento = $tipo_obj.'_'.$id_obj.'_'.$nombre;
        $nombreDocumento = $nombre;
        if ($pdf <> "") {
            $documento = $this->CrearDocumentoRobot($tipo_obj, $id_obj, $nombreDocumento, $publicarParaPerfilCliente);
            $respuesta = (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Success;
            if ($respuesta) {
                $idDocumento = (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Data->Id;
                echo "<br>Id del documento real= $idDocumento <br>";
                $documento = $this->SubirDocumento($idDocumento, $pdf);
                $respuesta = (string)$documento->Body->SubirDocumentoResponse->SubirDocumentoResult->Success;
                if ($respuesta) {
                    echo "<br>Documento $nombreDocumento añadido<br>";
                    if ($tipo_obj == "1") { //clientes
                        echo "<a href=".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Figuras.Cliente.ClienteDataPanel?_pageRender_cli_id=$id_obj#principal target=_blank>".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Figuras.Cliente.ClienteDataPanel?_pageRender_cli_id=$id_obj#principal</a><br><br>";
                    } elseif ($tipo_obj == "7") {//polizas
                        echo "<a href=".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Polizas.Poliza.PolizaDataPanel?_pageRender_pol_id=$id_obj#gestion target=_blank>".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Polizas.Poliza.PolizaDataPanel?_pageRender_pol_id=$id_obj#gestion</a><br><br>";
                    } elseif ($tipo_obj == "13") {//siniestros
                        echo "<a href=".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Siniestros.Siniestro.SiniestroDataPanel?_pageRender_sin_id=$id_obj#gestion target=_blank>".$this->urlSegelevia."SegElevia4253/PageRender.mvc/seg.Siniestros.Siniestro.SiniestroDataPanel?_pageRender_sin_id=$id_obj#gestion</a><br><br>";
                    }
                    return "Success";
                } else {
                    echo "<br>Error: Documento $nombreDocumento  NO añadido<br>";
                    return (string)$documento->Body->SubirDocumentoResponse->SubirDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField;
                }
            }else {
                echo "<br>Error: Documento $nombreDocumento  NO añadido<br>";
                return (string)$documento->Body->CrearDocumentoResponse->CrearDocumentoResult->Messages->Message->_x003C_InternalMessage_x003E_k__BackingField;
            } 
        }else {
            echo "<br>Error: Documento $nombreDocumento  NO ha podido guardarse<br>";
            return "Error: Documento $nombreDocumento  NO ha podido guardarse";
        }
    }

    public function CrearCriterio($tipo, $id, $conceptoId, $texto): SimpleXMLElement
    {   //$tipo=1 para clientes y $tipo=7 para pólizas
        //$id es el id o del cliente o de la póliza
        $config = [
            'xml' => 'CrearCriterioService.xml',
            'endpoint' => $this->urlWS . '/General/CriterioServiceDTO.svc',
            'action' => 'ICriterioServiceDTO/CrearCriterio'
        ];

        $this->xmlRequest = $this->getXML($config);

        $this->xmlRequest = str_replace("{{companyCode}}", $this->companyCode, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{tipoobjeto}}", $tipo, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{id}}", $id, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{conceptoId}}", $conceptoId, $this->xmlRequest);
        $this->xmlRequest = str_replace("{{texto}}", $texto, $this->xmlRequest);

        if ($tipo == '1') {
            return Curl::send($config, $this->xmlRequest, 'Crear criterio cliente');
        } else {
            return Curl::send($config, $this->xmlRequest, 'Crear criterio poliza');
        }
    }

   
    private function npmTimestamp(): string
    {
        $date = new DateTime('NOW', new DateTimeZone('Europe/Madrid'));
        return $date->format('YmdHis') . '00';
    }

    //En Segelevia ponemos la misma función que para Visual
    function limpiaParaSegelevia($c){
        $no_permitidas= array ("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","À","Ã","Ì","Ò","Ù","Ã™","Ã ","Ã¨","Ã¬","Ã²","Ã¹","ç","Ç","Ã¢","ê","Ã®","Ã´","Ã»","Ã‚","ÃŠ","ÃŽ","Ã”","Ã›","ü","Ã¶","Ã–","Ã¯","Ã¤","«","Ò","Ã","Ã„","Ã‹","'","&","#39;","º");
        $permitidas= array ("a","e","i","o","u","A","E","I","O","U","n","N","A","E","I","O","U","a","e","i","o","u","c","C","a","e","i","o","u","A","E","I","O","U","u","o","O","i","a","e","U","I","A","E"," ","y"," "," ");
        $c = str_replace($no_permitidas, $permitidas ,$c);
        $c=strtoupper($c);
        return $c;
    }

    function fechas_segelevia($fecha){
        if ((isset($fecha)) && (strtotime($fecha))){
            $arrayDate = explode("-", $fecha);
            if (count($arrayDate)==3){
                //Ejemplo de fecha: 2019-09-04T00:00:00+02:00
                return $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . 'T00:00:00';
            }else {
                return '1900-01-01T00:00:00';    
            }
        }else{
            return '1900-01-01T00:00:00';
        }
    }    
}