<?php
date_default_timezone_set('Europe/Madrid');
/////////////////////////CONEX/////////////////////////////////////////////////
include("../../../assets/conn/conexion.php"); 
include("funcSignLogalty.php");
$bd_conn = new connexion($host_avanws,$user_avanws,$pass_avanws,$name_avanws,$port_avanws);
$bd_conn->query("SET NAMES 'utf8'");
/////////////////////////VARIABLES/////////////////////////////////////////////
$cli_user = $_SERVER["HTTP_CLIENT_ID"];
$fecha = date("YmdHis");
$error = 0;
/////////////////////////ACCIONES//////////////////////////////////////////////
$host = 'https://www.logalty.es/lgt/lgtbus/public/DataService?wsdl'; 
chdir('system/controllers/signs/');
/////////////////////////CONSTRUCCION XML//////////////////////////////////
include("xmlStateLogalty.php");
if ( $control_docs > 0 ) {
    /////////////////////////CERTIFICADO DEL XML///////////////////////////////
    shell_exec( 'xmlsec1  --sign --output signed.xml --pkcs12 ./certificado/certificado.p12 --pwd logalty request_sign.xml');
    //se elimina primera línea del XML que contiene <?xml version="1.0" encoding="utf-8"?\>
    shell_exec( 'sed \'1d\' signed.xml > signed_send.xml');
    shell_exec( 'rm signed.xml');
    //se añade cabeceras SOAP
    shell_exec( 'echo \'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body>\' > SOAP.xml ');
    shell_exec( 'cat SOAP.xml signed_send.xml > signed_SOAP.xml');
    shell_exec( 'rm signed_send.xml');
    shell_exec( 'rm SOAP.xml');
    shell_exec( 'sed -e \'$a </soapenv:Body> </soapenv:Envelope>\' signed_SOAP.xml > signed_SOAP_send.xml');
    shell_exec( 'rm signed_SOAP.xml');
    //se obtiene el XML firmado
    $input_data = file_get_contents("signed_SOAP_send.xml");
    //HAGO EL POST DE LA FIRMA=================================================
    $request = 'POST';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL ,$host);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER,array('User-Agent: curl/7.15.5','Accept: */*','Content-Type: text/xml; charset=UTF-8','Content-Length: '.strlen($input_data)));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,5);
    curl_setopt($curl, CURLOPT_TIMEOUT,30);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST,$request);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $input_data);
    $result = curl_exec($curl);
    //print_r($result);
    //INTERPRETO LA RESPUESTA=======================================================
    $reader = new XMLReader();
    $doc = new DOMDocument();
    $xml_response = 'xml_state.log';
    $handle = fopen($xml_response, 'w');
    if ( $handle ){
        $writelog = fwrite($handle, $result) ;
        fclose($handle);
    }  
    if (!$reader->open($xml_response)) {
        die("Failed to open 'interface_ejemplo.xml'");
    }
    libxml_use_internal_errors(true);
    $doc->loadHTML($result);
    libxml_clear_errors();
    $xml = $doc->saveXML($doc->documentElement);
    $xml = simplexml_load_string($xml);
    $test = '';
    while($reader->read()) {
        if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'states') {
            $node = simplexml_import_dom($doc->importNode($reader->expand(), true));
            for ($i=0; $i < count($node->state); $i++) { 
                $result_xml =  $result;
                $guid = $node->state[$i]['guid'];
                $resultado_logalty = $node->state[$i]['value'];
                $estado_logalty =  $node->state[$i]["substate_value"];
                $estado_p0 = consultarEquivalenciaEstados($bd_conn, $estado_logalty);
                updateEstadosFirma($bd_conn, $estado_logalty, $resultado_logalty, $estado_p0, $guid, $result_xml );
                //DESCARGO LOS DOCUMENTO FINALIZADOS
                if ( $estado_logalty == '12' ) {
                    //DESCARGO EL CERTIFICADO
                    include("xmlDescCertf.php");
                    //BUCAR LOS DOCUMENTOS ASOCIADOS AL GUID///////////////////
                    $array_docs = consultarDocumentosGrupo($bd, $guid);
                    while ($docs = $array_docs->fetch_object()){
                        //DESCARGO EL DOCUMENTO
                        include("xmlDescDoc.php");
                    }
                    
                }     
            }           
        }
    }
    $data[] = array ( 
        "status" => "OK",
        "message" => 'completado con éxito',
        "test" => $result
    );
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data); 
    /*
    //VALIDO QUE EL LLAMADO FUE EXITOSO============================================
    if ( isset($xml->body->envelope->body->data_state_response->main) AND  ( $xml->body->envelope->body->data_state_response->main == "0000" OR $xml->body->envelope->body->data_state_response->main == "12" ) ) {
        $test = (string)$xml->body->envelope->body->data_state_response->reason->states->state[0]->guid;
        print_r($test);
        
        $i = 0;
        //RECORRO LOS DOCS=========================================================
        while( $i <= $control_docs  ){ 
            //HAGO EL UPDATE DE LOS ESTADOS DE LOGALTY=============================
            $result_xml = (string)$xml->body;
            $guid = (string)$xml->body->envelope->body->data_state_response->states->state[$i]["guid"];
            $estado_logalty = (string)$xml->body->envelope->body->data_state_response->states->state[$i]["substate_value"];
            $resultado_logalty = (string)$xml->body->envelope->body->data_state_response->states->state[$i]["value"];
            $estado_p0 = consultarEquivalenciaEstados($bd_conn, $estado_logalty);
            updateEstadosFirma($bd_conn, $estado_logalty, $resultado_logalty, $estado_p0, $guid, $result_xml );
            //DESCARGO LOS DOCUMENTO FINALIZADOS
            if ( $estado_logalty == 12 ) {
                //DESCARGO EL DOCUMENTO
                include("xmlDescDoc.php");
                //DESCARGO EL CERTIFICADO
                include("xmlDescCertf.php");
            }     
            $i ++;
        }
        if ( $error == 0 ) {
            $data[] = array ( 
                "status" => "OK",
                "message" => 'completado con éxito',
                "test" => $result
            );
            header("Content-type: application/json; charset=utf-8");
            echo json_encode($data);   
        }else{
            $data[] = array ( 
                "status" => "NO OK",
                "message" => 'error al descargar el documento y/o certificado'
            );
            header("Content-type: application/json; charset=utf-8");
            echo json_encode($data);   
        }
        
    }else{
        $data[] = array ( 
            "status" => "NOT OK",
            "message" => 'error'
        );
        header("Content-type: application/json; charset=utf-8");
        echo json_encode($data);
    }
    */
}else{
    $data[] = array ( 
        "status" => "NOT OK",
        "message" => 'no existen documentos pendientes por firma.'
    );
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
}
?>