<?php

  //ini_set('display_errors',1);
  
  //error_reporting(E_ALL);
  

session_start();
require_once ("../config/Cado.php");

require_once ("../app/comunicacionbaja/cComunicacionbaja.php");
$oComunicacionbaja = new cComunicacionbaja();

date_default_timezone_set('America/Lima');
//$service = 'https://www.sunat.gob.pe/ol-ti-itemision-otroscpe-gem-beta/billService?wsdl'; //comprobante de percepcion
/* $service = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl'; */
/* $service = 'https://e-beta.sunat.gob.pe/ol-ti-itemision-otroscpe-gem-beta/billService?wsdl'; */
//$service = 'FACTURA_PRODUCCION.wsdl';
//echo 'tip -'.$_POST['tipcom'];

//$service = 'https://e-factura.sunat.gob.pe/ol-it-wsconscpegem/billConsultService?wsdl';
//$service = 'https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService?wsdl';

//$service = 'FACTURA_PRODUCCION.wsdl';

$headers = new CustomHeaders('20602247075PERU2021','Peru1076'); 

$client = new SoapClient($service, ['cache_wsdl' => WSDL_CACHE_NONE, 'trace' => true , 'soap_version' => SOAP_1_1 ]);

$client->__setSoapHeaders([$headers]);

$ticket = $_POST['doc_tick'];
$filname  = $_POST['numdoc'].'.zip';
$nomxml  = $_POST['numdoc'];


	
try {
	
	$params = array('ticket' => $ticket);
	$client->getStatus($params);
	
	$leer = $client->__getLastResponse();
	//$status = $client->content;
	
	$xml = new DOMDocument('1.0', 'ISO-8859-1');
	
	$xml->loadxml($leer, LIBXML_NOWARNING | LIBXML_NOERROR);
			            // DOCUMENTO DE RESPUESTA SUNAT
			            $DocumentResponse = $xml->getElementsByTagName('getStatusResponse');
			            $itemsDocumentResponse = $DocumentResponse->item(0)->childNodes;
			            $ResponseValue = null;
			            if ($itemsDocumentResponse->length > 0) {
			                for ($DocRes = 0; $DocRes < $itemsDocumentResponse->length; $DocRes++) {
			                    $Response = $itemsDocumentResponse->item($DocRes);
			                    if (isset($Response->tagName)) {
			                        $valtag = $Response->tagName;
			                        if ($valtag == 'status') {
			                            $ResponseValue = $itemsDocumentResponse->item($DocRes);
			                            break;
			                        }
			                    }
			                }
			            }
						
						
	if (!empty($ResponseValue) && $ResponseValue->childNodes->length > 0) {
			                $ResNodes = $ResponseValue->childNodes;
			                for ($res = 0; $res < $ResNodes->length; $res++) {
			                    if (isset($ResNodes->item($res)->tagName)) {
			                        $tagResnNodes = $ResNodes->item($res)->tagName;
			                        if ($tagResnNodes == 'content') {
			                            $contenido = $ResNodes->item($res)->nodeValue;
			                        }
			                        if ($tagResnNodes == 'statusCode') {
			                            $codigo= $ResNodes->item($res)->nodeValue;
			                        }
			                        
			                    }
			                }
			            }
	
	
	$status=base64_decode($contenido);
	
	file_put_contents('../doccdr/R-'.$filname,$status);

	
	$zip = new ZipArchive();
	$zip->open('../doccdr/R-'.$filname);
	$zip->extractTo('../doccdrfiles/');
	$zip->close();
	
	
	$xml1 = new DOMDocument();
	$xml1->preserveWhiteSpace = FALSE;
	$xml1->load('../doccdrfiles/R-20602247075-'.$nomxml.'.xml');
	
	
	$s= $xml1->getElementsByTagName("Description");
	foreach($s as $node1){
		$descrip =  $node1->nodeValue;
	}
	
	$c= $xml1->getElementsByTagName("ResponseCode");
	foreach($c as $node2){
		$code =  $node2->nodeValue;
	} 
	
	//$pro = '::/ DESDE EL SERVIDOR DE PRODUCCION /::';

	$data['msj'] = 'MENSAJE SUNAT : '.$code.' :: '.$descrip;

	
	if($code=='0'){
		$est = '1';
		$oComunicacionbaja->act_sunat($_POST['doc_id'],$est);
	}else if($code=='99'){
		
	}else{
		$est = '2';
		$oComunicacionbaja->act_sunat($_POST['doc_id'],$est);
	}
	
	
	unlink('../doccdrfiles/R-'.$nomxml.'.xml');

	$data['est'] = '1';
	echo json_encode($data);
	
} catch(Exception $e) {
	/* echo 'Error: ' . $e->getCode() . ', ' . utf8_decode($e->getMessage()); */
	$data['msj'] = '' . utf8_decode($e->getMessage());
	$data['est'] = '0';
	echo json_encode($data);
}
 
class CustomHeaders extends SoapHeader {
	private $wss_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';
	
	function __construct($user, $pass, $ns = null) {
		if($ns){
			$this->wss_ns = $ns;
		}
		
		$auth = new stdClass();
		$auth->Username = new SoapVar($user, XSD_STRING, null, $this->wss_ns, null, $this->wss_ns);
		$auth->Password = new SoapVar($pass, XSD_STRING, null, $this->wss_ns, null, $this->wss_ns);
		
		$username_token = new stdClass();
		$username_token->UsernameToken = new SoapVar($auth, SOAP_ENC_OBJECT, null, $this->wss_ns, 'UsernameToken', $this->wss_ns);
		$security_sv = new SoapVar(new SoapVar($username_token, SOAP_ENC_OBJECT, null, $this->wss_ns, 'UsernameToken', $this->wss_ns)
								 , SOAP_ENC_OBJECT, null, $this->wss_ns, 'Security', $this->wss_ns);
		
		parent::__construct($this->wss_ns, 'Security', $security_sv, true);
	}
}

?>
