<?php

/////////////CONFIGURACIÓN////////////////////////

$apikey = '6532d6454b8aa370768e63d6ba5a832e';
$carpeta = 'wulogs';

//////////////////////////////////////////////////


$month = (isset($_GET['month'])) ? $_GET['month'] : exit('Falta month en la URL. Ejemplo http://miweb/wu.php?month=1&year=2021');
$year = (isset($_GET['year'])) ? $_GET['year'] : exit('Falta year en la URL. Ejemplo http://miweb/wu.php?month=1&year=2021');

if (strlen($month) == 1) $month = '0'.$month;
$feb = date('L', strtotime("01-01-".$year)) ? 29 : 28;

$meses = ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'];
$mesesdias = [31,$feb,31,30,31,30,31,31,30,31,30,31];

function fecha ($valor){
	$valor = explode(' ', $valor);
	return substr($valor[0], 8, 2).'/'.substr($valor[0], 5, 2).'/'.substr($valor[0], 2, 2).';'.substr($valor[1], 0, 5);
	
}

$arch = [];

for ($i = 1; $i < $mesesdias[$month-1] + 1; $i++){
	if ($i < 10) $i = '0'.$i;

array_push($arch, file('https://api.weather.com/v2/pws/history/all?stationId=IREGINDE13&format=json&units=m&date='.$year.$month.$i.'&numericPrecision=decimal&apiKey='.$apikey));
	
	
}


$valores = $temps = $hums = [];

foreach ($arch as $valor) {
	foreach($valor as $int){
	$valor = json_decode($int)->{'observations'};
	foreach ($valor as $valor2){
	
	$valores[] = fecha($valor2->{'obsTimeLocal'}).';'.$valor2->{'metric'}->{'tempAvg'}.';'.$valor2->{'humidityAvg'}.';'.$valor2->{'metric'}->{'dewptAvg'}.';'.$valor2->{'metric'}->{'windspeedHigh'}.';'.$valor2->{'metric'}->{'windgustHigh'}.';'.$valor2->{'winddirAvg'}.';'.$valor2->{'metric'}->{'precipRate'}.';'.$valor2->{'metric'}->{'precipTotal'}.';'.$valor2->{'metric'}->{'pressureMax'}.';null;null;null;'.$valor2->{'metric'}->{'windgustHigh'}.';'.($valor2->{'metric'}->{'windchillLow'}??"null").';'.($valor2->{'metric'}->{'heatindexHigh'}??"null").';'.($valor2->{'uvHigh'}??"null").';'.($valor2->{'solarRadiationHigh'}??"null").';null;null;null;null;null;'.$valor2->{'winddirAvg'}.';null;null;null;null'.PHP_EOL;
	
}
}
}
file_put_contents($carpeta.'/'.$meses[$month-1].substr($year,2,2).'log.txt',implode($valores));


echo 'Terminado !!';

?>