<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');
require('../librerias/PHPExcel/Classes/PHPExcel.php');


$archivo = $_FILES['file']['tmp_name'];



$inputFileType = PHPExcel_IOFactory::identify($archivo);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($archivo);
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();

for ($row = 2; $row <= $highestRow; $row++){

    if(empty($sheet->getCell("B".$row)->getValue()) || $sheet->getCell("B".$row)->getValue() == null){ continue; }	

	$Fecha_excel = $sheet->getCell('A'.$row);
	$Conversion = $Fecha_excel->getValue();
	if(PHPExcel_Shared_Date::isDateTime($Fecha_excel)){
	  $Conversion = date($format = "Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($Conversion));
	}
 

	$ch = curl_init('http://200.24.13.60/~program1/power-time-api/public/obtenerpersonarut'); //create a new cURL resource
	$payload = json_encode(array('rut' => rut($sheet->getCell("B".$row)->getValue())));
	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;
	$rut = $array[0]->rut;	
	$nombre = strtoupper(utf8_decode($array[0]->nombre ." ".$array[0]->apellido));		

	$ch2 = curl_init('http://200.24.13.60/~program1/power-time-api/public/validaingresofalta'); //create a new cURL resource
	$payload2 = json_encode(array('id_persona' => $id, 'fecha' => $Conversion));
	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);
		
	$mensaje = "";
	$cantidad = 0;
	$codigo = 0;
	
	$cantidad = $array2[0]->cantidad;	
	$codigo = $array2[0]->codigo;		
	if($cantidad > 0) { $mensaje = "<span class='badge badge-danger'>".utf8_encode($array2[0]->mensaje)."</span>"; }
    else { $mensaje = "<span class='badge badge-success'>". utf8_encode($array2[0]->mensaje) ."</span>"; }	
		
	$vetor[] = array(
		'rut' => ($rut),
		'nombre' => $nombre,	
		'id' => $id,			
		'fecha' => $Conversion,			
		'mensaje' => $mensaje,			
		'cantidad' => $cantidad,			
		'codigo' => $codigo	 			
	); 		
	
}


function rut( $rut ) {
	$rut = str_replace(".","",$rut);
	$rut = str_replace("-","",$rut);
	
    return number_format( substr ( $rut, 0 , -1 ) , 0, "", ".") . '-' . substr ( $rut, strlen($rut) -1 , 1 );
}

echo json_encode($vetor);


?>