<?php
require_once '../../Comunes/Clases/clase_metodos_comunes_php.php';
require_once('../../Bibliotecas/nusoap/lib/nusoap.php');

class Clase_SoapSII{
    private $sNameSpace='https://solclic.martabid.com/wsdl';
    private $oSlcXml;
    public function __construct() {
         $this->oSlcXml=new Clase_SlcXml(); 
    }
    
    public function getFunctions($aParams){
        $client = new SoapClient($aParams['server']);
        var_dump($client->__getFunctions());
    }
    
    public function callFunction($aParams){
        $oClient = new SoapClient($aParams['server']);
        return $oClient->__soapCall($aParams['function'], $aParams['arguments']);
    }
    
    public function nusoapCallFunction($aParams){
           $client = new nusoap_client($aParams['server'], true);
           
           $aResp['success']=false;
           $err = $client->getError();
           if ($err) {
                $aResp['error']=$err;
           }
           
           $result=$client->call($aParams['function'], $aParams['arguments'], '',   '', false, null, 'rpc', 'literal');
           if ($client->fault) {
                    $aResp['error']=$result;
            }else {
                    $err = $client->getError();
                    if ($err) {
                        $aResp['error']=$err;
                    }else{
                        $aResp['success']=true;
                        $aResp['response']=$result;
                    }
            }
            
           /* 
            echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
            echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
            echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
            */
            return $aResp;
    }
    public function getServerString($sTipo){
        
        if (SLC_HAMBIENTE == 'PRODUCCION')
            $sServer='palena';//oficial SII
        else
            $sServer='maullin';//pruebas SII
        
        
        switch ($sTipo) {
            case 'crseed':{
                return 'https://'.$sServer.'.sii.cl/DTEWS/CrSeed.jws?WSDL';
            } 
            
            case 'tokenfromseed':{
                return 'https://'.$sServer.'.sii.cl/DTEWS/GetTokenFromSeed.jws?WSDL';
            }
            
            case 'upload_xml':{
                return 'https://'.$sServer.'.sii.cl/cgi_dte/UPL/DTEUpload';
            }
            
            case 'consultaestado':{
                return 'https://'.$sServer.'.sii.cl/DTEWS/QueryEstUp.jws?WSDL';
            }
            
            case 'estado_dte':{
                return 'https://'.$sServer.'.sii.cl/DTEWS/QueryEstDte.jws?WSDL';
            }
        }
    }
   
    
    
    
      
      public function getSeed(){
            $aResp['success']=false;
            $aXmlCall=$this->nusoapCallFunction(array('server'=>$this->getServerString('crseed'),
                                                    'function'=>'getSeed',
                                                    'arguments'=>array()
                                                    ));
            if ($aXmlCall['success']){
                $aRespData=$this->oSlcXml->getArrayFromXml($aXmlCall['response']);
                if (isset($aRespData['SII:RESP_BODY'])){
                    $aResp['success']=true;
                    $aResp['semilla']=$aRespData['SII:RESP_BODY']['SEMILLA']; 
                }
            }else{
                return $aXmlCall;
            }
            return $aResp;
     }
      public function getToken($aPKey){
          $aSeed=$this->getSeed();
          
          $aResp['success']=false;
          if ($aSeed['success']){
                      $sXml = "<getToken>\n\t<item>\n\t\t<Semilla>".$aSeed['semilla']."</Semilla>\n\t</item>\n</getToken>";
                      $aXmlSing=$this->oSlcXml->singXmlString($sXml, $aPKey);
                      $aXmlCall=$this->nusoapCallFunction(array('server'=>$this->getServerString('tokenfromseed'),
                                                                'function'=>'getToken',
                                                                'arguments'=>'<pszXml xsi:type="xsd:string"><![CDATA['.$aXmlSing['contenido'].']]></pszXml>'));
                      if ($aXmlCall['success']){
                          $aToken=$this->oSlcXml->getArrayFromXml($aXmlCall['response']);
                          if (isset($aToken['SII:RESP_BODY'])){
                              $aResp['success']=true;
                              $aResp['token']=$aToken['SII:RESP_BODY']['TOKEN'];
                          }
                      }else{
                          $aResp=$aXmlCall;
                      }
                      return $aResp;
         }else{
             return $aSeed;
         }
      }
     
      public function consultaEstadoEnvioDTE($aParams){
          
          list($sEmpRut, $sDvRutEmp)=explode('-', $aParams['emp_rut']);
          
          $sXmlQuery = '<Rut xsi:type="xsd:string">'.str_replace('.','',$sEmpRut).'</Rut>
                                     <Dv xsi:type="xsd:string">'.strtoupper($sDvRutEmp).'</Dv>
                                     <TrackId xsi:type="xsd:string">'.$aParams['env_trackid'].'</TrackId>
                                     <Token xsi:type="xsd:string">'.$aParams['token'].'</Token>';
          
          
          $aXmlCall=$this->nusoapCallFunction(
                  array('server'=>$this->getServerString('consultaestado'),
                        'function'=>'getEstUp',
                        'arguments'=>$sXmlQuery));
          
            if ($aXmlCall['success']){
                $aResp['response']=$this->oSlcXml->getArrayFromXml($aXmlCall['response']);
                $aResp['response_xml']=$aXmlCall['response'];
            }else{
                $aResp=$aXmlCall;
            }
           
          return $aResp;
      }
    
      public function consultaEstadoDTE($aParams){
          
          list($sEmpRut, $sDvRutEmp)=explode('-', $aParams['emp_rut']);
          list($sRutRecep, $sDvRutRecep)=explode('-', $aParams['ent_rut_entidad']);
          list($sRutConsul, $sDvRutConsul)=explode('-', $aParams['emp_rutcertbase']);
          $sl=chr(10);
          $aQuery=array('server'=>$this->getServerString('estado_dte'),
                        'function'=>'getEstDte',
                        'arguments'=>'<RutConsultante xsi:type="xsd:string">'.str_replace('.','',$sRutConsul).'</RutConsultante>'.$sl.
                                      '<DvConsultante xsi:type="xsd:string">'.strtoupper($sDvRutConsul).'</DvConsultante>'.$sl.
                                      '<RutCompania xsi:type="xsd:string">'.str_replace('.','',$sEmpRut).'</RutCompania>'.$sl.
                                      '<DvCompania xsi:type="xsd:string">'.strtoupper($sDvRutEmp).'</DvCompania>'.$sl.
                                      '<RutReceptor xsi:type="xsd:string">'.str_replace('.','',$sRutRecep).'</RutReceptor>'.$sl.
                                      '<DvReceptor xsi:type="xsd:string">'.strtoupper($sDvRutRecep).'</DvReceptor>'.$sl.
                                      '<TipoDte xsi:type="xsd:string">'.$aParams['tdo_coddoctoelectronicosii'].'</TipoDte>'.$sl.
                                      '<FolioDte xsi:type="xsd:string">'.$aParams['doc_numero'].'</FolioDte>'.$sl.
                                      '<FechaEmisionDte xsi:type="xsd:string">'.str_replace('-','',$aParams['doc_fecha_es']).'</FechaEmisionDte>'.$sl.
                                      '<MontoDte xsi:type="xsd:string">'.ROUND($aParams['doc_montototal'],0).'</MontoDte>'.$sl.
                                      '<Token xsi:type="xsd:string">'.$aParams['token'].'</Token>');
           
          
            $aXmlCall=$this->nusoapCallFunction($aQuery);
             
            
            
            if ($aXmlCall['success']){
                $aResp['response']=$this->oSlcXml->getArrayFromXml($aXmlCall['response']);
                $aResp['response_xml']=$aXmlCall['response'];
                $aResp['success']=$aXmlCall['success'];
            }else{
                $aResp=$aXmlCall;
            }
            
          
          
            return $aResp;
      }
      
      
      public function sendUploadDTE($aParams){
          
            
            $sUrl=$this->getServerString('upload_xml');
            $aEmpersa=$aParams['aEmpresa'];
         
            list($sEmpRut, $sDvRutEmp)=explode('-', $aEmpersa['emp_rut']);
            list($sRutEnvia, $sDvEnvia)=explode('-',$_SESSION['rutPersona']);
            
            $aPost = array('rutSender'=>str_replace('.','',$sRutEnvia),
                           'dvSender'=>strtoupper($sDvEnvia), 
                           'rutCompany'=>str_replace('.','',$sEmpRut),
                           'dvCompany'=> strtoupper($sDvRutEmp),
                           'archivo'=>'@'.realpath($aParams['archivo'])
                    );
            
            $handler = curl_init();  
            curl_setopt($handler, CURLOPT_URL, $sUrl);
            curl_setopt($handler, CURLOPT_POST, true);
            curl_setopt($handler, CURLOPT_PORT, 443);
            curl_setopt($handler, CURLOPT_VERBOSE, true);
            curl_setopt($handler, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
            curl_setopt($handler, CURLINFO_HEADER_OUT, true);
            curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, FALSE);
            
            curl_setopt($handler, CURLOPT_POSTFIELDS, $aPost);
            curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($handler, CURLOPT_FORBID_REUSE, true);
            curl_setopt($handler, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; PROG 1.0; Windows NT 5.0; YComp 5.0.2.4");  
            
            curl_setopt($handler, CURLOPT_HTTPHEADER, array('Accept-Language: es-cl', 'Accept-Encoding: gzip, deflate',"Cache-Control: no-cache", 'Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/vnd.ms-powerpoint, application/ms-excel,application/msword, */*'));
            curl_setopt($handler, CURLOPT_COOKIE, 'TOKEN='.$aParams['token']);
          
            $response = curl_exec ($handler);  
            curl_close($handler);  
            return $response;  
      }
}
?>