<?php
    # Libreria Nusoap
    require_once "lib/nusoap.php";

    # Espacio de nombre
    $namespace = "http://www.ecuinfo.net";

    # Definicion de web services
    $server = new soap_server();

    # UTF-8
    date_default_timezone_set('America/Guayaquil');
    $server->soap_defencoding = 'utf-8';
    $server->decode_utf8 = false;

    $server->configureWSDL("wsedoc", $namespace); //  "urn:wsedoc");

    $server->wsdl->schemaTargetNamespace = $namespace;

    # Registro rcvxml
    // Register the method to expose
    $server->register('rcvxml',                              // method
        array('GUID'   => 'xsd:string',
              'fecgen' => 'xsd:string',
              'fecfir' => 'xsd:string',
              'fecsri' => 'xsd:string',
              'fecaut' => 'xsd:string',
              'fecenv' => 'xsd:string',
              'fecemi' => 'xsd:string',
              'fecven' => 'xsd:string',
              'doctip' => 'xsd:string',
              'doccod' => 'xsd:string',
              'docleg' => 'xsd:string',
              'valdoc' => 'xsd:decimal',
              'xmlgen' => 'xsd:string',                         
              'xmlfir' => 'xsd:string',                         
              'dcride' => 'xsd:string'),                         // input parameters
        array('return' => 'xsd:boolean'),                        // output parameters
        $namespace,                                              // namespace
        $namespace . '#rcvxml',                                  // soapaction
        'rpc',                                                   // style
        'literal',                                               // use
        'Recepcion de XML edoc'                                  // documentation
    );


    ############################
    # Funcion Recepcion de XML #
    ############################
    function rcvxml($guid,$fecgen,$fecfir,$fecsri,$fecaut,$fecenv,$fecemi,$fecven,$doctip,$doccod,$docleg,$valdoc,$xmlgen,$xmlfir,$dcride) 
{
        include "inc/functions.php";
        include "inc/db3_connect.php";
        if ($guid == "") {
            return false;
        }
        else {
            # Fecha
            $today = date("r");
            # Log File
            $logfile = "/var/log/sysedoc_test.log";
            # Cabecera de log
            $ip = '';
            $addr = inet_pton($_SERVER['REMOTE_ADDR']);
            foreach(str_split($addr) as $char) $ip = $ip . str_pad(ord($char),3,'0',STR_PAD_LEFT) . '.';
            $iporig = substr($ip,0,-1);

            $logdat = $today . ' - ' . $iporig . ' - ';            
            $fp = fopen($logfile, 'a');

            #--- Revision si empresa GUID esta habilitada para recibir edoc
            $strSql = "select serweb,sermai,em_def"
                    . " from datcia where guid = '" .$guid . "' and estpag = 1";

            $erow = $mysqli->query($strSql); 
            if ($erow->num_rows == 1) {
                $datcia = $erow->fetch_object();
                # Si esta activa la empresa y al dia en los pagos
                
		# Servicio Consulta Web
		$serweb = $datcia->serweb;
		# Servicio Buzon Mail
		$sermai = $datcia->sermai;
		# Email por defecto
		$em_def = $datcia->em_def;
 
                if ($serweb == 0 and $sermai == 0) {
                   # Ningun servicio activo 
                   fwrite($fp, $logdat . 'rcvxml - GUID: ' . $guid . ' - SRV ' . PHP_EOL);
                   return false;
                }
            }
            else {
                # Empresa no activa o suspendida por mora
                fwrite($fp, $logdat . 'rcvxml - GUID: ' . $guid . ' - PAG ' . PHP_EOL);
                return false;
            }
            #--- Fin de revision

            # Decode Base 64 - XML Generado
            $utf8_genxml = base64_decode($xmlgen);

            # Decode Base 64 - XML Firmado/Autorizado
            $utf8_firxml = base64_decode($xmlfir);

	    # Decode Base 64 - Formato RIDE
	    $utf8_dcride = base64_decode($dcride);
           
            # Carga datos de XML
            $datxml = new SimpleXMLElement($utf8_genxml);
            $codacc = $datxml->infoTributaria->{'claveAcceso'};
            $ciaruc = $datxml->infoTributaria->{'ruc'};
            $tipamb = $datxml->infoTributaria->{'ambiente'};

            if ($doctip == 'FAC') {
	       $clitip = $datxml->infoFactura->{'tipoIdentificacionComprador'};
               $usrnom = $datxml->infoFactura->{'razonSocialComprador'};
               $cliruc = $datxml->infoFactura->{'identificacionComprador'};
               $cliema = "";
            }

            if ($doctip == 'DEV') {
	       $clitip = $datxml->infoNotaCredito->{'tipoIdentificacionComprador'};
               $usrnom = $datxml->infoNotaCredito->{'razonSocialComprador'};
               $cliruc = $datxml->infoNotaCredito->{'identificacionComprador'};
               $cliema = "";
            }

            if ($doctip == 'RET') {
	       $clitip = $datxml->infoCompRetencion->{'tipoIdentificacionSujetoRetenido'};
               $usrnom = $datxml->infoCompRetencion->{'razonSocialSujetoRetenido'};
               $cliruc = $datxml->infoCompRetencion->{'identificacionSujetoRetenido'};
               $cliema = "";
            }

            if ($doctip == 'REM') {
	       $clitip = $datxml->infoGuiaRemision->{'tipoIdentificacionTransportista'};
               $usrnom = $datxml->infoGuiaRemision->{'razonSocialTransportista'};
               $cliruc = $datxml->infoGuiaRemision->{'rucTransportista'};
               $cliema = "";
            }


            foreach($datxml->infoAdicional->campoAdicional as $item) {
               switch ($item->attributes()->nombre) {
                  case "email":
                     $cliema = $item;
                     break;
      #           case "DocInfo":
         #           $fecemi = getparam($item,";",2);
         #           $fecven = getparam($item,";",3);
     #               break;
               }
            }


            if ($cliema == "") {
                $ciema = $em_def;
            }

            $docsri = 1; 
            if ($fecsri == "") {
		$docsri = 0;
            }

            $docaut = 1; 
            if ($fecaut == "") {
		$docaut = 0;
            }

            $docenv = 1;
            if ($fecenv == "") {
		$docenv = 0;
	    }

            # Ingreso datos del xml generado
            $strSql = "replace into irsedoc "
                    . "(codacc,ciaruc," 
		    . "docfir,fecfir,docpdf,fecpdf,docgen,fecgen,";
            if ($docsri == 1) {
               $strSql = $strSql . "docsri,fecsri,";
            }
            if ($docaut == 1) {
               $strSql = $strSql . "docaut,fecaut,";
            }
            if ($docenv == 1) {
               $strSql = $strSql . "docenv,fecenv,";
            }

            $strSql = $strSql . "fecemi,fecven,doctip,doccod,docleg,"
                    . "tipamb,valdoc,tipoid,userid,uemail,iporig) values ("
                    . "'$codacc',"
                    . "'$ciaruc',"
                    . "1,"
                    . "'$fecfir',"
                    . "1,"
                    . "'$fecgen',"
                    . "1,"
                    . "'$fecgen',";

            if ($docsri == 1) {
               $strSql = $strSql . "'$docsri','$fecsri',";
            }
            if ($docaut == 1) {
               $strSql = $strSql . "'$docaut','$fecaut',";
            }
            if ($docenv == 1) {
               $strSql = $strSql . "'$docenv','$fecenv',";
            }

            $strSql = $strSql . "'$fecemi',"
                    . "'$fecven',"
                    . "'$doctip',"
                    . "'$doccod',"
                    . "'$docleg',"
                    . "'$tipamb',"
                    . "'$valdoc',"
                    . "'$clitip',"
                    . "'$cliruc',"
                    . "'$cliema',"
                    . "'" . $_SERVER['REMOTE_ADDR'] . "')";

            $resp = false;
            if ($mysqli->query($strSql)) {
               fwrite($fp, $logdat . 'rcvxml - ruc: ' . $ciaruc . ' - clave: ' . $codacc . ' - OK ' . PHP_EOL);

               # Graba XML Generado
               $doctmp = mysqli_real_escape_string($mysqli, $utf8_genxml);
	       $strSql = "replace into docgen (codacc,fecdoc,detdoc) values ("
		       . "'$codacc',"
		       . "'$fecgen',"
		       . "'$doctmp')";

               if ($mysqli->query($strSql)) {
                  $resp = true;
               }

	       # Graba XML Firmado/Autorizado
               #$doctmp = mysqli_real_escape_string($mysqli, $utf8_firxml);
               if ($docaut == 1) {
                  $strSql = "replace into docaut (codacc,fecdoc,detdoc) values ("
                       . "'$codacc',"
                       . "'$fecgen',"
                       . "'$utf8_firxml')";
	       }
	       else {
                  $strSql = "replace into docfir (codacc,fecdoc,detdoc) values ("
                       . "'$codacc',"
                       . "'$fecgen',"
                       . "'$utf8_firxml')";
	       }

               if ($mysqli->query($strSql)) {
                  $resp = true;
               }

               # Graba Formato RIDE
               $doctmp = mysqli_real_escape_string($mysqli, $utf8_dcride);
	       $strSql = "replace into docpdf (codacc,fecdoc,detdoc) values ("
		       . "'$codacc',"
		       . "'$fecgen',"
		       . "'$doctmp')";
               
               if ($mysqli->query($strSql)) {
                  $resp = true;
               }

               # Verificacion si existe el usuario
               $strSql = "select userid from usuarios where userid = '" . $cliruc . "'";
               $crow = $mysqli->query($strSql);
               if ($crow->num_rows == 0)  {
                  # Extrae nombre del comprador desde el xml
                  # Usuario no existe lo ingreso por defecto
                  $strSql = "replace into usuarios (userid,usrnom,usrpwd,usrmail,usrfin,estado,fecact) values ("
                          . "'$cliruc',"
                          . "'$usrnom',"
                          . "'" . hash('sha512',$cliruc) . "',"
                          . "'$cliema',"
                          . "'1',0,'$fecemi')";
                  $mysqli->query($strSql);
                  fwrite($fp, $logdat . 'rcvxml - newcli: ' . $cliruc . ' - SAVE' . PHP_EOL);

               }
            }
            else {
               fwrite($fp, $logdat . 'rcvxml - ciaruc: ' . $ciaruc . ' - BAD' . PHP_EOL);
            }
            fclose($fp);
            return $resp;
        }
    }


   #$server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '');
   #$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
   if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
   $server->service($HTTP_RAW_POST_DATA);
?>
