<?php

$codigo = $_POST["codigo"];

$data_string = array( 'user_name' => "CMVA", 'user_pin' => "rUWj3LR", "X-API-KEY" => "ec31e121e83d68f7217a22af8109007155c2518c" );
$data =  processCurlJsonrequest("https://5.dec.cl/api/v1/auth/login",$data_string);
$parametro = json_decode($data);

if($parametro->status == 200){
	$idsesion = $parametro->session_id;
	
	$data_string = array( 'institution' => "CMVA", 'code' => [$codigo], 'extra' => "file", 'session_id' => $idsesion, 'X-API-KEY' => "ec31e121e83d68f7217a22af8109007155c2518c");
	$data = processCurlJsonrequest("https://5.dec.cl/api/v1/documents",$data_string);
	$respuesta = json_decode($data);

	$data = base64_decode($respuesta->result[0]->file);
	header('Content-Type: application/pdf');
	echo $data;	

}


    function processCurlJsonrequest($URL, $fieldString){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fieldString));
        curl_setopt($ch, CURLOPT_POST, 1);
        $resulta = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        } else {
            curl_close($ch);
        }
        return $resulta;
    }

?>
