<?php
require_once ('../librerias/dompdf/autoload.inc.php');
use Dompdf\Dompdf;

$meses = array(1 => 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');


$url = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpermiso';
$ch = curl_init($url); //create a new cURL resource

$payload = json_encode(array('id' => 12507));



curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result = curl_exec($ch); //execute the POST request
$array = json_decode($result);

$id = $array[0]->id;
$fecha_inicio = $array[0]->fecha_inicio;
$fecha_termino = $array[0]->fecha_termino;
$fecha_retorno = $array[0]->fecha_retorno;
$cantidad = $array[0]->cantidad;
$jornada = $array[0]->jornada;
$hora_inicio = date("H:i", strtotime($array[0]->hora_inicio));
$hora_termino = date("H:i", strtotime($array[0]->hora_termino));
$id_tipo_permiso = $array[0]->id_tipo_permiso;
$id_persona = $array[0]->id_persona;	
$id_autoriza = $array[0]->id_autoriza;
$observacion = $array[0]->observacion;
$id_estado = $array[0]->id_estado;

$cadena = explode("-", date("Y-m-d", strtotime($array[0]->created_at)));
$fecha_inicio_titulo = $cadena[2]." de ".$meses[intval($cadena[1])]. " de ". $cadena[0];
	
curl_close($ch); 

$ch5 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerdepartamentoprimarioasignado'); //create a new cURL resource
//$payload5 = json_encode(array('id_persona' => $id_autoriza));
$payload5 = json_encode(array('id_persona' => $id_persona));
curl_setopt($ch5, CURLOPT_POSTFIELDS, $payload5);//attach encoded JSON string to the POST fields
curl_setopt($ch5, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result5 = curl_exec($ch5); //execute the POST request
$array5 = json_decode($result5);

$idsucursal = $array5[0][0]->id_sucursal;
$iddepartamento = $array5[0][0]->id; 

/***************************************************************************/
$url2 = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpersona';
$ch2 = curl_init($url2); //create a new cURL resource
$payload2 = json_encode(array('id' => $id_persona));
curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result2 = curl_exec($ch2); //execute the POST request
$array2 = json_decode($result2);

$nombrePersona = $array2[0]->nombre ." ". $array2[0]->apellido;
$rut = $array2[0]->rut;
$email = $array2[0]->email;
curl_close($ch2);


/***************************************************************************/	

$url2 = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpermisoestado';
$ch2 = curl_init($url2); //create a new cURL resource
$payload2 = json_encode(array('id' => $id_estado));
curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result2 = curl_exec($ch2); //execute the POST request
$array2 = json_decode($result2);

$estado = $array2[0]->descripcion;

curl_close($ch2);

/***************************************************************************/	

$url2 = 'http://200.24.13.60/~program1/power-time-api/public/obtenerpersona';
$ch2 = curl_init($url2); //create a new cURL resource
$payload2 = json_encode(array('id' => $id_autoriza));
curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result2 = curl_exec($ch2); //execute the POST request
$array2 = json_decode($result2);

$nombreAutoriza = $array2[0]->nombre ." ". $array2[0]->apellido;
$rutAutoriza = $array2[0]->rut;
curl_close($ch2);

/***************************************************************************/	
$ch3 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenertipopermiso'); //create a new cURL resource
$payload3 = json_encode(array('id' => $id_tipo_permiso));
curl_setopt($ch3, CURLOPT_POSTFIELDS, $payload3);//attach encoded JSON string to the POST fields
curl_setopt($ch3, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result3 = curl_exec($ch3); //execute the POST request
$array3 = json_decode($result3);

$tipopermiso = $array3[0]->descripcion;
$ley = $array3[0]->ley;
$observacion_ley = $array3[0]->observacion;
$hora = $array3[0]->hora;
curl_close($ch3);	

/***************************************************************************/	
 
$ch4 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenercargoasignado'); //create a new cURL resource
$payload4 = json_encode(array('id_persona' => $id_autoriza));
curl_setopt($ch4, CURLOPT_POSTFIELDS, $payload4);//attach encoded JSON string to the POST fields
curl_setopt($ch4, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch4, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result4 = curl_exec($ch4); //execute the POST request
$array4 = json_decode($result4);

$cargoAutoriza = $array4[0]->descripcion;			

curl_close($ch4); 	



/***************************************************************************/	

$ch4 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenercargoasignado'); //create a new cURL resource
$payload4 = json_encode(array('id_persona' => $id_persona));
curl_setopt($ch4, CURLOPT_POSTFIELDS, $payload4);//attach encoded JSON string to the POST fields
curl_setopt($ch4, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch4, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result4 = curl_exec($ch4); //execute the POST request
$array4 = json_decode($result4);

$cargo = $array4[0]->descripcion;			

curl_close($ch4); 	

/***********************************************************************/

$ch5 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerdepartamentoprimarioasignado'); //create a new cURL resource
$payload5 = json_encode(array('id_persona' => $id_persona));
curl_setopt($ch5, CURLOPT_POSTFIELDS, $payload5);//attach encoded JSON string to the POST fields
curl_setopt($ch5, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result5 = curl_exec($ch5); //execute the POST request
$array5 = json_decode($result5);

$departamento = "";
$departamento .= '<tr>';	
$departamento .= "<td style='background:#eceaea; width:49%'><center><b>AREA</b></center></td>"; 
$departamento .= "<td style='background:#eceaea; width:49%'><center><b>CENTRO</b></center></td>";
$departamento .= '</tr>';	
$departamento .= '<tr>';	
$departamento .= "<td style='width:49%'><center>". utf8_decode($array5[0][0]->sucursal) ."</center></td>"; 
$departamento .= "<td style='width:49%'><center>".utf8_decode($array5[0][0]->departamento) ."</center></td>";
$departamento .= '</tr>';	
		

curl_close($ch5); 


/***********************************************************************/

$ch5 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerdepartamentoprimarioasignado'); //create a new cURL resource
$payload5 = json_encode(array('id_persona' => $id_autoriza));
curl_setopt($ch5, CURLOPT_POSTFIELDS, $payload5);//attach encoded JSON string to the POST fields
curl_setopt($ch5, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result5 = curl_exec($ch5); //execute the POST request
$array5 = json_decode($result5);

//$departamento_autorizador = utf8_decode($array5[0][0]->sucursal) ." (".utf8_decode($array5[0][0]->departamento) ." )";	
$departamento_autorizador = utf8_decode($array5[0][0]->departamento);		

curl_close($ch5); 

$tbl_hora = '';


if($id_tipo_permiso == 22){
	if($hora > 0){

		if($jornada > 2) { 
			$tbl_hora .= '<tr>';
			$tbl_hora .= '<td style="background:#eceaea;width:49%;"><center><b>HORA INICIO :</b></center></td>';
			$tbl_hora .= '<td style="background:#eceaea;width:49%;"><center><b>HORA T&Eacute;RMINO :</b></center></td>';				
			$tbl_hora .= '</tr>';    
			$tbl_hora .= '<tr>';
			$tbl_hora .= '<td style="width:49%"><center>'.$hora_inicio.'</center></td>';
			$tbl_hora .= '<td style="width:49%"><center>'.$hora_termino.'</center></td>';				
			$tbl_hora .= '</tr>';
		}

		
	}
}


if($id_tipo_permiso == 22){
	if($jornada == 2) { $cantidad = "MEDIO D&Iacute;A AM"; }
	if($jornada == 3) { $cantidad = "MEDIO D&Iacute;A PM"; }
}

$html = '
<style>
body{
	font-size:10px;
}
.tbl-trabajador table{
	border:solid 1px #000000;	
}
.tbl-trabajador tr td{
	border:solid 1px #000000;	
}
.hora-permiso table{
	border:solid 1px #000000;	
}
.hora-permiso tr td{
	border:solid 1px #000000;	
}
</style>

<div style="width:80%; margin: 0 AUTO;">

    <div>
		<table style="width:100%;">
			<tr>
				<td style="width:50%;"><img style="max-height:90px;" src="../img/002.png" /></td>				
				<td style="width:50%; text-align:right; font-size:16px;"> <h4 style="display:inline;"> FOLIO : '.str_pad( $id, 10, "0", STR_PAD_LEFT).'</h4> <br /> <h4 style="display:inline;">'.$fecha_inicio_titulo.' </h4> </td>			
			</tr>	
		</table>       

	</div>
	<div>    
	    <div><center><h4 style="display:inline; font-size:16px;">  '.utf8_decode($tipopermiso).'</h4></center></div>
		<br />
		
		<table style="width:100%;">
			<tr>
				<td style="width:20%;"><b>NOMBRE </b></td>		
				<td style="width:1%;"><b> :</b></td>					
				<td style="width:79%;" style="text-align:left;"> SR(A) '.utf8_decode($nombrePersona).'</td>	
			</tr>	
			<tr>
				<td style="width:20%;"><b>RUT </b></td>	
				<td style="width:1%;"><b> :</b></td>					
				<td style="width:79%;" style="text-align:left;">'.$rut.'</td>			
			</tr>				
			<tr>
				<td style="width:20%;"><b>CARGO :</b></td>			
				<td style="width:1%;"><b> :</b></td>					
				<td style="width:79%;" style="text-align:left;"> '.utf8_decode($cargo).'</td>			
			</tr>			
			<tr>
				<td style="width:20%;"><b>COMPA&Ntilde;IA :</b> </td>	
				<td style="width:1%;"><b> :</b></td>				
				<td style="width:79%;" style="text-align:left;">CORPORACI&Oacute;N MUNICIPAL DE VILLA ALEMANA</td>	
				</tr>				
			<tr>
				<td style="width:20%;"><b>RUT COMPA&Ntilde;IA </b></td>
				<td style="width:1%;"><b> :</b></td>					
				<td style="width:79%;" style="text-align:left;">70.983.600-5</td>
			</tr>			
		</table>				
						
		<br />
		<table style="width:100%;" class="tbl-trabajador">				
			
		    '.$departamento.'
			<tr>
				<td style="background:#eceaea;width:49%;"><center><b>FECHA INICIO :</b></center></td>
				<td style="background:#eceaea;width:49%;"><center><b>FECHA T&Eacute;RMINO :</b></center></td>				
			</tr>		    
			<tr>
				<td style="width:49%"><center>'.date("d-m-Y", strtotime($fecha_inicio)).'</center></td>
				<td style="width:49%"><center>'.date("d-m-Y", strtotime($fecha_termino)).'</center></td>				
			</tr>
			<tr>
				<td style="background:#eceaea;width:49%;"><center><b>FECHA RETORNO :</b></center></td>
				<td style="background:#eceaea;width:49%;"><center><b>CANTIDAD DE D&Iacute;AS:</b></center></td>				
			</tr>	
			<tr>
				<td style="width:49%"><center>'.date("d-m-Y", strtotime($fecha_retorno)).'</center></td>
				<td style="width:49%"><center>'.$cantidad.'</center></td>				
			</tr>
		
            '.$tbl_hora.'
			<tr>
				<td style="background:#eceaea;" colspan="2"><center><b>OBSERVACI&Oacute;N :</b></center></td>			
			</tr>            
			<tr>
				<td colspan="2" style="height:75px;"><center>'.utf8_decode($observacion).'</center></td>			
			</tr>
			
		</table>	
		<br />
		<br />
		<table style="width:100%;">				
			<tr>
				<td style="width:20%;"><b>ELABORADO POR </b> </td>
				<td style="width:1%;"><b> :</b></td>	
				<td style="width:79%;" style="text-align:left;">'.utf8_decode($nombreAutoriza).'</td>				
			</tr>
			<tr>
				<td style="width:20%;"><b>RUT </b></td>
				<td style="width:1%;"><b> :</b></td>	
				<td style="width:79%;" style="text-align:left;"> '.$rutAutoriza.'</td>				
			</tr>
			<tr>
				<td style="width:20%;"><b>CENTRO</b></td>
				<td style="width:1%;"><b> :</b></td>	
				<td style="width:79%;" style="text-align:left;">'.$departamento_autorizador.'</td>
			</tr>
			<tr>
				<td style="width:20%;"><b>CARGO </b> </td>
				<td style="width:1%;"><b> :</b></td>	
				<td style="width:79%;" style="text-align:left;">'.utf8_decode($cargoAutoriza).'</td>				
			</tr>		
			
		</table>				
		<br /> <br />
	</div>

	<img src="../img/Generator.jpg" style="min-width:99%;" />
	<img src="../img/Sign.jpg" style="min-width:99%;" />
	<img src="../img/Sign.jpg" style="min-width:99%;" />
	<img src="../img/Sign.jpg" style="min-width:99%;" />
	<img src="../img/Sign.jpg" style="min-width:99%;" />
 
</div>	
';

/* 
$pdf = new DOMPDF();
$pdf->set_paper("A4", "portrait");
$pdf->load_html(utf8_encode($html));
$pdf->render();
$pdf->stream("marcajes.pdf", array("Attachment" => false));
exit(0);
*/ 
 
$pdf = new DOMPDF();
$pdf->set_option('isHtml5ParserEnabled', true);
$pdf->set_paper("A4", "portrait");
$pdf->load_html(utf8_encode($html));
$pdf->render();

$output = $pdf->output();
file_put_contents($id.".pdf", $output);	
 
$b64Doc = base64_encode(file_get_contents($id.".pdf"));
//echo $b64Doc;	

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;
}	
 
$rut = str_replace(".", "", $rut);

$ch5 = curl_init('http://200.24.13.60/~program1/power-time-api/public/listarfirmantesucursal'); //create a new cURL resource
$payload5 = json_encode(array('idsucursal' => $idsucursal, 'iddepartamento' => $iddepartamento));
curl_setopt($ch5, CURLOPT_POSTFIELDS, $payload5);//attach encoded JSON string to the POST fields
curl_setopt($ch5, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
$result5 = curl_exec($ch5); //execute the POST request
$array5 = json_decode($result5);

$arrayrut=array($rut);
$arrayroles=array($rut);
$arrayinstitucion=array($rut);
$arrayemail=array($email);
$arraytipofirma=array(0);

$arrayorden=array(1);
$arraynotifica=array(1);

foreach($array5[0] as $firmante){
	array_push($arrayrut, $firmante->rut);
	array_push($arrayroles, $firmante->rut);
	array_push($arrayinstitucion, $firmante->rut);	
	array_push($arrayemail, $firmante->email);	
	array_push($arrayorden, 2);	
	array_push($arraynotifica, 1);		
	array_push($arraytipofirma, 0);		
}
array_push($arrayrut, "ANY");
array_push($arrayroles, "SECRETARIO_GENERAL");
array_push($arrayinstitucion, "CMVA");
array_push($arrayemail, "ANY");
array_push($arrayorden, 3);	
array_push($arraynotifica, 1);	
array_push($arraytipofirma, 0);	

array_push($arrayroles, "VISUALIZADOR");
array_push($arrayinstitucion, "CMVA");
array_push($arrayrut, "ANY");
array_push($arraytipofirma, 5);	
array_push($arraynotifica, 0);	
array_push($arrayemail, "ANY");

array_push($arrayorden, 1);	

$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);
$idsesion = $parametro->session_id;
 
$data_string = array("X-API-KEY" => "ec31e121e83d68f7217a22af8109007155c2518c",
  "session_id" => $idsesion, //
  "type_code" => "PE2020373275156", // Codigo del tipo de documento configurado en dec
  "institution" => "CMVA", // institución creada en DEC 5
  "name" => "PERMISO", //Nombre del documento a crear 
  "signers_roles" => $arrayroles, // Roles y rut del documento 
  "signers_institutions" => $arrayinstitucion, // Instituciones de los roles y rut
  "signers_rut" => $arrayrut, // any (cualquier usuario con el rol puede firmar)
  "signers_type" => $arraytipofirma, // Tipos de firma 
  "signers_order" => $arrayorden, // Orden de los firmantes 
  "signers_notify" => $arraynotifica, // Tipos de notificaciones 
  "signers_emails" => $arrayemail, // correos usuarios 
  "tags" => ["PERMISO"], // etiquetas fijas del documento 
  "comment" => "PERMISO", //
  //"file" => " ",
  "file" => $b64Doc, //
  "file_mime" => "application/pdf");

$data =  processCurlJsonrequest("https://5.dec.cl/api/v1/documents/create",$data_string);
$parametro = json_decode($data);

 
if($parametro->status == 200){

	$codigo_unico = $parametro->result->code; // codigo unico de documento en acepta
	
		$ch2 = curl_init('http://200.24.13.60/~program1/power-time-api/public/permisodigital'); //create a new cURL resource
		$payload2 = json_encode(array('id' => $id , 'pdfacepta' => $codigo_unico ));
		curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);//attach encoded JSON string to the POST fields
		curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); //set the content type to application/json
		curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); //return response instead of outputting
		$result2 = curl_exec($ch2); //execute the POST request
		$array2 = json_decode($result2);	
		
	echo "1";		
}else{
	echo "0";
} 



?>
