<?php
set_time_limit(0);
ini_set('memory_limit', '-1');

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

$html = '';
$html .='
<style>
body{
	font-family:Arial;
}
	table {
	font-size:11px;
	}
	.tbl-marcaje{
		text-align: center;
	}
    .tbl-marcaje th {
      color: #000000;
	  background-color: #CCCCCC;
	  border:solid 1px #000000;
	}
    .tbl-marcaje td {
		border:solid 1px #000000;
	  }	
	.total-semana td{
		color: #000000;
		background-color: #CCCCCC;	
		border:solid 1px #000000;			
	}

    .tbl-marcaje tr {
        background-color: #eee;
    }
    .tbl-marcaje tr:nth-child(2) {
        background-color: #eee;
    }
    .tbl-marcaje tr:nth-child(even) {
        background-color: #eee;
    }
     
    .tbl-marcaje tr:nth-child(odd) {
        background-color: #fff;
    }
    .tbl-cabecera{
		width:100%;
	}
</style>';
setlocale(LC_TIME, "spanish");

$listado_personas;		
if($_POST["txtDepartamento"] > 0){
	$ch2 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerpersonadepartamento');
	$payload2 = json_encode(array('id_departamento' => $_POST["txtDepartamento"]));
	curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);
	curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); 
	curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); 
	$result2 = curl_exec($ch2); 
	$listado_personas = json_decode($result2);			
	curl_close($ch2);
}else{
	$ch2 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerpersonasucursal');
	$payload2 = json_encode(array('id_sucursal' => $_POST["txtSucursal"]));
	curl_setopt($ch2, CURLOPT_POSTFIELDS, $payload2);
	curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); 
	curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); 
	$result2 = curl_exec($ch2); 
	$listado_personas = json_decode($result2);
	curl_close($ch2);			
}

foreach ($listado_personas[0] as $row_persona) {

/*****************************************************************/	
		$ch2 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerpersonarut'); //create a new cURL resource
		$payload2 = json_encode(array('rut' => $row_persona->rut));
		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);
 
		$rut = $array2[0]->rut;	
		$nombre = $array2[0]->nombre ." ". $array2[0]->apellido;
        $id = $array2[0]->id;

        curl_close($ch2); 	

		$ch3 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerdeptopersona'); //create a new cURL resource
		$payload3 = json_encode(array('id' => $row_persona->id));
		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);

		$departamento = $array3[0][0]->departamento;

		
		curl_close($ch3); 
		
		$ch5 = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerdepartamentoasignado'); //create a new cURL resource
		$payload5 = json_encode(array('id_persona' => $row_persona->id));
		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 = "";
		foreach ($array5[0] as $row) {
			$departamento .= '<tr>';	
			$departamento .= "<td><b>SUCURSAL :</b>".strtoupper($row->sucursal) ."</td>"; 
			$departamento .= "<td><b>DEPARTAMENTO :</b>".strtoupper($row->descripcion) ."</td>";
			$departamento .= '</tr>';		
		}
		curl_close($ch5); 


		$html .= "<table class='tbl-cabecera' style='border-bottom: 2px solid #000000;'>";
		$html .= "<tr>";
		$html .= "<td width='30%;'><img src='../img/002.png' style='max-height:45px;' /></td>";
		$html .= "<td width='50%;'><h3 style='display:inline;'>REPORTE DE ASISTENCIA LABORAL</h3></td>";
		$html .= "</tr>";			
		$html .= "</table>";	
		
		$html .= "<table class='tbl-cabecera'>";	
		$html .= "<tr>";
		$html .= "<td><b>NOMBRE TRABAJADOR :</b> ".$nombre."</td>";
		$html .= "<td></td>";			
		$html .= "<td><b>FECHA EMISION :</b> ".date("d-m-Y")."</td>";
		$html .= "</tr>";
		$html .= "<tr>";
		$html .= "<td><b>RUT TRABAJADOR :</b> ".$rut."</td>";	
		$html .= "<td><b>PERIODO DESDE :</b> ". $_POST["txtFecha_inicio"]."</td>";	
		$html .= "<td><b>PERIODO HASTA :</b> ". $_POST["txtFecha_termino"]."</td>";				
		$html .= "</tr>";
		$html .= "<tr>";
		$html .= "<td><b>COMPA&Ntilde;IA :</b> CORP MUNICIPAL PARA EL DESARROLLO SOCIAL</td>";				
		$html .= "<td colspan='2'><b>RUT :</b> 70.983.600-5</td>";	
		$html .= "</tr>";	
		$html .= $departamento;		
		$html .= "</table><br />";		

			$sum_programado_total = "00:00:00";
			$sum_real_total = "00:00:00";		
			$sum_permanencia_total = "00:00:00";	
			$sum_desct_total = "00:00:00";			
			$sum_hora_extra_total = "00:00:00";	
			$sum_atraso_total = "00:00:00";	
			$sum_ent_ant_total = "00:00:00";	
			$sum_sal_ant_total = "00:00:00";
			$sum_sal_dep_total = "00:00:00";	
			$sum_trabaja_total = 0;
			$sum_no_trabaja_total = 0;	

            $num_table = 0;
			
               
			$url = 'http://200.24.13.60/~program1/power-time-api/public/informemarcatrabajador';
			$ch = curl_init($url); 
			$payload = json_encode(array('fecha_inicio' => $_POST["txtFecha_inicio"], 'fecha_termino' => $_POST["txtFecha_termino"], 'rut' => $row_persona->rut, 'id_persona' => $row_persona->id));

			curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
			$result = curl_exec($ch); 
			$array = json_decode($result);	

			$ultima_semana = "";
			/*********** SUMATORIA SEMANA ++++++++++*/
			$sum_programado = "00:00:00";
			$sum_real = "00:00:00";		
			$sum_permanencia = "00:00:00";	
			$sum_desct = "00:00:00";			
			$sum_hora_extra = "00:00:00";	
			$sum_atraso = "00:00:00";	
			$sum_ent_ant = "00:00:00";	
			$sum_sal_ant = "00:00:00";
			$sum_sal_dep = "00:00:00";	

			$sum_trabaja = 0;  $sum_no_trabaja = 0;				
			$cantidad = 0;
				
			foreach ($array[0] as $row) {

				if(substr(strftime("%A", strtotime($row->fecha)), 0, 3) != "lun" && $cantidad == 0){
				$html .= "<table class='tbl-marcaje' style='width:100%;'>";
				$html .= "<thead>";
				$html .= "<tr>";
				$html .= "<th>Fecha</th>";						
				$html .= "<th colspan='2'>Horario Program.</th>";
				$html .= "<th colspan='2'>Jornada Real</th>";	
				$html .= "<th colspan='2'>Total Horas</th>";
				$html .= "<th colspan='2'>Total Horas</th>";					
				$html .= "<th colspan='4'>Desgloce Horas</th>";	
			//	$html .= "<th colspan='2'>Desgloce D&iacute;as</th>";
				$html .= "<th></th>";			
				$html .= "</tr>";
				$html .= "<tr>";
				$html .= "<th>D&iacute;a</th>";						
				$html .= "<th>Entrada</th>";
				$html .= "<th>Salida</th>";	
				$html .= "<th>Entrada</th>";	
				$html .= "<th>Salida</th>";
				$html .= "<th>Prog</th>";	
				$html .= "<th>Real</th>";						
				$html .= "<th>Ent. Ant</th>";	
				$html .= "<th>Atraso</th>";		
				$html .= "<th>Sal. Ant</th>";	
				$html .= "<th>Sal. Desp</th>";	
				$html .= "<th>Horas Perm.</th>";
				$html .= "<th>Horas Ext. Auto.</th>";	
			//	$html .= "<th>Trabaja</th>";	
			//	$html .= "<th>Falta</th>";	
				$html .= "<th>Observaci&oacute;n.</th>";				
				$html .= "</tr>";
				$html .= "</thead>";
				$html .= "<tbody>";
			   }
			   $cantidad++;					   

				if(substr(strftime("%A", strtotime($row->fecha)), 0, 3) == "lun"){
				$html .= "<table class='tbl-marcaje' style='width:100%;'>";
				$html .= "<thead>";
				$html .= "<tr>";
				$html .= "<th>Fecha</th>";						
				$html .= "<th colspan='2'>Horario Program.</th>";
				$html .= "<th colspan='2'>Jornada Real</th>";	
				$html .= "<th colspan='2'>Total Horas</th>";
				$html .= "<th colspan='2'>Total Horas</th>";					
				$html .= "<th colspan='4'>Desgloce Horas</th>";	
			//	$html .= "<th colspan='2'>Desgloce D&iacute;as</th>";
				$html .= "<th></th>";			
				$html .= "</tr>";
				$html .= "<tr>";
				$html .= "<th>D&iacute;a</th>";						
				$html .= "<th>Entrada</th>";
				$html .= "<th>Salida</th>";	
				$html .= "<th>Entrada</th>";	
				$html .= "<th>Salida</th>";
				$html .= "<th>Prog</th>";	
				$html .= "<th>Real</th>";						
				$html .= "<th>Ent. Ant</th>";	
				$html .= "<th>Atraso</th>";		
				$html .= "<th>Sal. Ant</th>";	
				$html .= "<th>Sal. Desp</th>";	
				$html .= "<th>Horas Perm.</th>";
				$html .= "<th>Horas Ext. Auto.</th>";	
			//	$html .= "<th>Trabaja</th>";	
			//	$html .= "<th>Falta</th>";	
				$html .= "<th>Observaci&oacute;n.</th>";				
				$html .= "</tr>";
				$html .= "</thead>";
				$html .= "<tbody>";
			   }
			   
					    /**********ENTRADA***********/
		                $en = explode(".", $row->entradar);
						$chMI = curl_init('http://200.24.13.60/~program1/power-time-api/public/validarmarcajemanual'); 
						$payloadMI = json_encode(array(
						'fecha' => $row->fecha, 
						'hora' => $en[0], 
						'id_tipo_marcaje' => 0, 
						'rut' => $rut, 
						'id_estado' => 2
						));	
						curl_setopt($chMI, CURLOPT_POSTFIELDS, $payloadMI);
						curl_setopt($chMI, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
						curl_setopt($chMI, CURLOPT_RETURNTRANSFER, true); 
						$resultMI = curl_exec($chMI); 
						$arrayMI = json_decode($resultMI);

						$caracterIngreso = "";
						if($arrayMI[0] > 0) { $caracterIngreso = "*"; }		

					    /**********SALIDA***********/
			            $sa = explode(".", $row->salidar);
						$chMS = curl_init('http://200.24.13.60/~program1/power-time-api/public/validarmarcajemanual'); 
						$payloadMS = json_encode(array(
						'fecha' => $row->fecha, 
						'hora' => $sa[0], 
						'id_tipo_marcaje' => 1, 
						'rut' => $rut, 
						'id_estado' => 2
						));	
						curl_setopt($chMS, CURLOPT_POSTFIELDS, $payloadMS);
						curl_setopt($chMS, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
						curl_setopt($chMS, CURLOPT_RETURNTRANSFER, true); 
						$resultMS = curl_exec($chMS); 
						$arrayMS = json_decode($resultMS);
						
						$caracterSalida = "";
						if($arrayMS[0] > 0) { $caracterSalida = "*"; }					

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

			
			   $obs = $row->obs;
				if(!empty($row->obs)) { 
					$row->falta = 0; $row->falta = 0; $obs = $row->obs;
					if (strpos($row->obs, 'FERIADO') !== false) { $obs ="FERIADO"; }
				}
				else{
					if($row->trabaja == 0){ $obs ="Libre"; }
					if(empty($row->entradar) && !empty($row->salidar)){ $obs ="No Registra Ingreso"; }  							
					if(!empty($row->entradar) && empty($row->salidar)){ $obs ="No Registra Salida"; }  						                      
					if(empty($row->entradar) && empty($row->salidar) && $row->falta == 1){ $obs ="Ausente"; }  						
					if (strpos($row->obs, 'FERIADO') !== false) { $obs ="FERIADO"; }
				}
				
				$html .= "<tr>";
				$html .= "<td>". substr(strftime("%A", strtotime($row->fecha)), 0, 3) ." ". formatearFecha($row->fecha) ."</td>";												
				$html .= "<td>".cortarCadena($row->entradap) ."</td>";
				$html .= "<td>".cortarCadena($row->salidap) ."</td>";	
				$html .= "<td>". $caracterIngreso." " .cortarCadena($row->entradar) ."</td>";	
				$html .= "<td>". $caracterSalida." " .cortarCadena($row->salidar) ."</td>";
				$html .= "<td>".cortarCadena($row->trabajoprogramado) ."</td>";	
				$html .= "<td>".cortarCadena($row->trabajoreal) ."</td>";						
				$html .= "<td>".cortarCadena($row->entradaanticipada) ."</td>";	
				$html .= "<td>".cortarCadena($row->atraso) ."</td>";		
				$html .= "<td>".cortarCadena($row->salidaanticipada) ."</td>";	
				$html .= "<td>".cortarCadena($row->salidadespues) ."</td>";	
				$html .= "<td>".cortarCadena($row->permanencia) ."</td>";		
				$html .= "<td>".cortarCadena($row->hora_extra) ."</td>";

				if (strpos($obs, 'FERIADO') !== false) {
				   $row->trabaja = 0;
				}
			//	$html .= "<td>".$row->trabaja ."</td>"; 
				if (strpos($obs, 'FERIADO') !== false) {
				   $row->falta = 0;
				}
				$fecha_actual = strtotime(date("Y-m-d"));
				$fecha_sistema = strtotime($row->fecha);
				if($fecha_sistema > $fecha_actual){
					$row->falta = 0;
					$obs = ".";
				}
				
				
				//$html .= "<td>".$row->falta ."</td>";	
				$html .= "<td>".$obs ."</td>";					
				$html .= "</tr>";
				
		
				$sum_trabaja += $row->trabaja;
				$sum_no_trabaja += $row->falta;										
				if(!empty($row->trabajoprogramado)) { $sum_programado = suma_horas($sum_programado, $row->trabajoprogramado); }
				if(!empty($row->trabajoreal)) { $sum_real = suma_horas($sum_real, $row->trabajoreal); }				
				if(!empty($row->permanencia)) { $sum_permanencia = suma_horas($sum_permanencia, $row->permanencia); }	
				if(!empty($row->faltante)) { $sum_desct = suma_horas($sum_desct, $row->faltante); }					
				if(!empty($row->hora_extra)) { $sum_hora_extra = suma_horas($sum_hora_extra, $row->hora_extra); }	
				if(!empty($row->atraso)) { $sum_atraso = suma_horas($sum_atraso, $row->atraso); }	
				if(!empty($row->entradaanticipada)) { $sum_ent_ant = suma_horas($sum_ent_ant, $row->entradaanticipada); }	
				if(!empty($row->salidaanticipada)) { $sum_sal_ant = suma_horas($sum_sal_ant, $row->salidaanticipada); }					
				if(!empty($row->salidadespues)) { $sum_sal_dep = suma_horas($sum_sal_dep, $row->salidadespues); }		
				
				/*********** FIN SUMATORIA SEMANAL **************/	
				
				/*********** SUMATORIA TOTAL **************/

				$sum_trabaja_total += $row->trabaja;
				$sum_no_trabaja_total += $row->falta;										
				
				if(!empty($row->trabajoprogramado)) { $sum_programado_total = suma_horas($sum_programado_total, $row->trabajoprogramado); }
				if(!empty($row->trabajoreal)) { $sum_real_total = suma_horas($sum_real_total, $row->trabajoreal); }				
				if(!empty($row->permanencia)) { $sum_permanencia_total = suma_horas($sum_permanencia_total, $row->permanencia); }	
				if(!empty($row->faltante)) { $sum_desct_total = suma_horas($sum_desct_total, $row->faltante); }					
				if(!empty($row->hora_extra)) { $sum_hora_extra_total = suma_horas($sum_hora_extra_total, $row->hora_extra); }	
				if(!empty($row->atraso)) { $sum_atraso_total = suma_horas($sum_atraso_total, $row->atraso); }	
				if(!empty($row->entradaanticipada)) { $sum_ent_ant_total = suma_horas($sum_ent_ant_total, $row->entradaanticipada); }	
				if(!empty($row->salidaanticipada)) { $sum_sal_ant_total = suma_horas($sum_sal_ant_total, $row->salidaanticipada); }					
				if(!empty($row->salidadespues)) { $sum_sal_dep_total = suma_horas($sum_sal_dep_total, $row->salidadespues); }		
				
				/*********** FIN SUMATORIA TOTAL **************/

				if(substr(strftime("%A", strtotime($row->fecha)), 0, 3) == "dom"){
					$html .= "<tr class='total-semana'>";
					$html .= "<td colspan='3'><b>Total Semana: </b></td>";							
					$html .= "<td></td>";	
					$html .= "<td></td>";
					$html .= "<td><b>". cortarCadena($sum_programado) ."</b></td>";	
					$html .= "<td><b>". cortarCadena($sum_real) ."</b></td>";						
					$html .= "<td><b>". cortarCadena($sum_ent_ant)."</b></td>";	
					$html .= "<td><b>". cortarCadena($sum_atraso)."</b></td>";		
					$html .= "<td><b>". cortarCadena($sum_sal_ant)."</b></td>";	
					$html .= "<td><b>". cortarCadena($sum_sal_dep)."</b></td>";	
					$html .= "<td><b>". cortarCadena($sum_permanencia) ."</b></td>";	
					$html .= "<td><b>". cortarCadena($sum_hora_extra) ."</b></td>";	
				//	$html .= "<td><b>". $sum_trabaja ."</b></td>";	
			//		$html .= "<td><b>". $sum_no_trabaja ."</b></td>";	
					$html .= "<td></td>";				
					$html .= "</tr>";			
					$html .= "</tbody>";
					$html .= "</table><br />";	
					
					
					$sum_programado = "00:00:00";
					$sum_real = "00:00:00";		
					$sum_permanencia = "00:00:00";	
					$sum_desct = "00:00:00";			
					$sum_hora_extra = "00:00:00";	
					$sum_atraso = "00:00:00";	
					$sum_ent_ant = "00:00:00";	
					$sum_sal_ant = "00:00:00";
					$sum_sal_dep = "00:00:00";	

					$sum_trabaja = 0;  $sum_no_trabaja = 0;		
					
					 $num_table = $num_table + 1;
					 if($num_table == 2){
						 $html .= "<div style='page-break-after: always;'></div>";
						 $num_table = 0;
					 }
					
				 }
					
			}

			curl_close($ch);


			$html .= "<table class='tbl-marcaje' style='width:100%;'>";
			$html .= "<thead>";
			$html .= "<tr>";
			$html .= "<th colspan='5'>&nbsp;</th>";						
			$html .= "<th>Prog</th>";	
			$html .= "<th>Real</th>";						
			$html .= "<th>Ent. Ant</th>";	
			$html .= "<th>Atraso</th>";		
			$html .= "<th>Sal. Ant</th>";	
			$html .= "<th>Sal. Desp</th>";	
			$html .= "<th>Horas Perm.</th>";
			$html .= "<th>Horas Ext. Auto.</th>";	
		//	$html .= "<th>Trabaja</th>";	
		//	$html .= "<th>Falta</th>";					
			$html .= "</tr>";
			$html .= "</thead>";
			$html .= "<tbody>";			
			$html .= "<tr class='total-semana'>";
			$html .= "<td colspan='5'><b>Total Periodo: </b></td>";							
			$html .= "<td><b>". cortarCadena($sum_programado_total) ."</b></td>";	
			$html .= "<td><b>". cortarCadena($sum_real_total) ."</b></td>";						
			$html .= "<td><b>". cortarCadena($sum_ent_ant_total)."</b></td>";	
			$html .= "<td><b>". cortarCadena($sum_atraso_total)."</b></td>";		
			$html .= "<td><b>". cortarCadena($sum_sal_ant_total)."</b></td>";	
			$html .= "<td><b>". cortarCadena($sum_sal_dep_total)."</b></td>";	
			$html .= "<td><b>". cortarCadena($sum_permanencia_total) ."</b></td>";	
			$html .= "<td><b>". cortarCadena($sum_hora_extra_total) ."</b></td>";	
		//	$html .= "<td><b>". $sum_trabaja_total ."</b></td>";	
		//	$html .= "<td><b>". $sum_no_trabaja_total ."</b></td>";			
			$html .= "</tr>";			
			$html .= "</tbody>";
			$html .= "</table>";
			
            $html .= "<div style='page-break-after: always;'></div>";			
/*****************************************************************/	
	
	
}
		

		
function formatearFecha($fecha){
	 $fecha = date("d-m-Y", strtotime($fecha));
	 $fecha = substr($fecha, 0, 5);
	 return $fecha;
}			
		
function cortarCadena($hora){	
	if($hora != null) { $hora = str_replace("-","", $hora); $hora = substr($hora, 0, 5); return $hora; } else return $hora;
}		

function Contains($mystring, $word){
	if(strpos($mystring, $word) !== false){
		return true;
	} else{
		return false;
	}
}

function suma_horas($hora1,$hora2){
	
	$hora1 = str_replace("-","", $hora1);
	$hora2 = str_replace("-","", $hora2);	
		
    $hora1=explode(":",$hora1);
    $hora2=explode(":",$hora2);
	
    $temp=0;
    $segundos=(int)$hora1[2]+(int)$hora2[2];
    while($segundos>=60){
        $segundos=$segundos-60;
        $temp++;
    }
    $minutos=(int)$hora1[1]+(int)$hora2[1]+$temp;
    $temp=0;
    while($minutos>=60){
        $minutos=$minutos-60;
        $temp++;
    }


    $horas=(int)$hora1[0]+(int)$hora2[0]+$temp;
    if($horas<10){ $horas= '0'.$horas; }
    if($minutos<10){ $minutos= '0'.$minutos; }
    if($segundos<10){ $segundos= '0'.$segundos; }

    $sum_hrs = $horas.':'.$minutos.':'.$segundos;
    return ($sum_hrs);

}


//echo utf8_encode($html);

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