<?php
checkLogin('adm');
checkEnteService('men');

class PDF extends FPDF
{
	var $widths;
	var $aligns;
	var $line_h = 3.5;
	var $cell_padding = 1;
	var $fill = false;
	var $header_str;
	
	function setHeader($str){
		
		if($_GET['solare'] == 1)
			$w = "SOLARE ".$GLOBALS['anno'];
		else
			$w = "SCOLASTICO ".$GLOBALS['anno']."/".($GLOBALS['anno']+1);
		
		$this->header_str = entities_pdf($str.' - CONTEGGIO PASTI - ANNO '.$w);
	}
	function Header(){
		$this->SetFont('Arial','B',11);
		
		
		$this->MultiCell(0,6,$this->header_str,0,'C');
		$this->Ln(5);
	}
	
	function SetWidths($w)
	{
		//Set the array of column widths
		$this->widths=$w;
	}
	
	function SetAligns($a)
	{
		//Set the array of column alignments
		$this->aligns=$a;
	}
	
	function Row($data)
	{
		//Calculate the height of the row
		$nb=0;
		for($i=0;$i<count($data);$i++)
			$nb=max($nb, $this->NbLines($this->widths[$i], $data[$i]));
		$h=$this->line_h*$nb;
		//Issue a page break first if needed
		$this->CheckPageBreak($h);
		
		//$fill_color = $this->fill ? 'DF' : '';
		//Draw the cells of the row
		for($i=0;$i<count($data);$i++)
		{
			$w=$this->widths[$i];
			$a=isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
			//Save the current position
			$x=$this->GetX();
			$y=$this->GetY();
			//Draw the border
			$this->Rect($x - $this->cell_padding, $y - $this->cell_padding, $w + $this->cell_padding, $h + $this->cell_padding*2,'DF');
			//Print the text
			$this->MultiCell($w, $this->line_h, $data[$i], 0, $a);
			//Put the position to the right of the cell
			$this->SetXY($x+$w + $this->cell_padding, $y);
		}
		//Go to the next line
		//$this->fill = !$this->fill;
		$this->Ln($h+ $this->cell_padding*2);
	}
	
	function CheckPageBreak($h)
	{
		//If the height h would cause an overflow, add a new page immediately
		if($this->GetY()+$h>$this->PageBreakTrigger)
			$this->AddPage($this->CurOrientation);
	}
	
	function NbLines($w, $txt)
	{
		//Computes the number of lines a MultiCell of width w will take
		$cw=&$this->CurrentFont['cw'];
		if($w==0)
			$w=$this->w-$this->rMargin-$this->x;
		$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
		$s=str_replace("\r", '', $txt);
		$nb=strlen($s);
		if($nb>0 and $s[$nb-1]=="\n")
			$nb--;
		$sep=-1;
		$i=0;
		$j=0;
		$l=0;
		$nl=1;
		while($i<$nb)
		{
			$c=$s[$i];
			if($c=="\n")
			{
				$i++;
				$sep=-1;
				$j=$i;
				$l=0;
				$nl++;
				continue;
			}
			if($c==' ')
				$sep=$i;
			$l+=$cw[$c];
			if($l>$wmax)
			{
				if($sep==-1)
				{
					if($i==$j)
						$i++;
				}
				else
					$i=$sep+1;
				$sep=-1;
				$j=$i;
				$l=0;
				$nl++;
			}
			else
				$i++;
		}
		return $nl;
	}
}

$anno = intval($_GET['yyyy']);
$importo = dbFloat($_GET['costo']);

if($_GET['solare'] == 1){
	$solare = true;
	$w = "DATE_FORMAT(serv_men_presenze.date,'%Y') = ".$anno;
}else{
	$w = "(DATE_FORMAT(serv_men_presenze.date,'%Y%m') >= ".$anno."09 AND DATE_FORMAT(serv_men_presenze.date,'%Y%m') <= ".($anno+1)."06)";
}

//estraggo alunni iscritti al servizio bus
$result = $mysqli->query($q="
SELECT 
COUNT(*) AS t, CONCAT_WS(' ',anagrafiche.anagr_cognome,anagrafiche.anagr_nome) AS anagrafica,
serv_men_presenze.anagr_id,
comuni.comune,
DATE_FORMAT(serv_men_presenze.date,'%Y-%m') AS data,
serv_men_presenze.date


FROM serv_men_presenze
LEFT JOIN anagrafiche ON serv_men_presenze.anagr_id = anagrafiche.anagr_id
LEFT JOIN comuni ON serv_men_presenze.comune_id = comuni.comune_id

WHERE 

anagrafiche.ente_id = ".$_SESSION['user']['ente_id']." AND (serv_men_presenze.status = 'P' OR serv_men_presenze.status='S') AND ".$w."

GROUP BY serv_men_presenze.comune_id, DATE_FORMAT(serv_men_presenze.date,'%Y%m'), serv_men_presenze.anagr_id

ORDER BY comuni.comune, data, anagrafiche.anagr_cognome, anagrafiche.anagr_nome
");

if($result->num_rows > 0){
	while($row=$result->fetch_assoc()){
		
		$anagrafiche[$row['comune']][$row['anagr_id']][$row['data']] = array(
			'anagr'=>entities_pdf($row['anagrafica']),
			'tot'=>$row['t']
		);
	}

}else{
	header("Location: ../adm/?noprintresult");	
	die();
}


$pdf = new PDF('L','mm','A4');
$pdf->SetMargins(15,10);

//larghezza e numero colonne
if($solare){ //12 mesi
	$cols_months = array_fill(0,12,15);
	$cols_align = array_fill(0,12,'C');
	$start_date = new DateTime($anno.'-01-01');
}else{ //10 mesi
	$cols_months = array_fill(0,10,18);
	$cols_align = array_fill(0,10,'C');
	$start_date = new DateTime($anno.'-09-01');	
}

//preparo colonne con nomi dei mesi

foreach($cols_months as $k=>$v){
	$cols_header[] = mese_ita($start_date->format('m'),true).' '. $start_date->format('Y');
	$months[] = $start_date->format('Y-m');
	$start_date->modify('+ 1 month');
}

array_unshift($cols_header,'Alunno');
array_unshift($cols_months,45);
array_unshift($cols_align,'L');

array_push($cols_header,'TOT');
array_push($cols_months,10);
array_push($cols_align,'C');

array_push($cols_header,entities_pdf('€'));
array_push($cols_months,20);
array_push($cols_align,'C');


$pdf->SetWidths($cols_months);
$pdf->SetAligns($cols_align);

foreach($anagrafiche as $comune => $anagrafica){

	$pdf->setHeader('Comune di '.strtoupper($comune));
	$pdf->AddPage();
	$pdf->SetFont('Arial','B',8);
	$pdf->SetFillColor(255,232,171);
	$pdf->Row($cols_header);
	
	$pdf->SetFont('Arial','',8);
	$fill = false;
	
	foreach($anagrafica as $anagr_id=>$v){
		
		if($fill)
			$pdf->SetFillColor(224,235,255);
		else
			$pdf->SetFillColor(255,255,255);		
		
		$anagr = current($v);
		$row[] = $anagr['anagr'];
		
		foreach($months as $k=>$mese){
			//preso
			if($v[$mese]){
				$cell = $v[$mese]['tot'];
				$tot_user += $v[$mese]['tot'];
			}else{
				$cell = '';
			}
			
			$tot_month[$mese] += $v[$mese]['tot'];
			$row[] = $cell;
		}
				
		array_push($row,$tot_user);
		array_push($row,number_format(($tot_user * $importo),3,',','.'));
		$pdf->Row($row);
		unset($row, $tot_user);
		$fill = !$fill;
		
	}

	$final_row = array_values($tot_month);
	$totale = array_sum($final_row);
	array_unshift($final_row,'TOTALE');
	array_push($final_row,$totale);
	array_push($final_row,number_format(($totale * $importo),3,',','.'));
	
	
	$pdf->SetFillColor(255,232,171);
	$pdf->SetFont('Arial','B',8);
	$pdf->Row($final_row);
	unset($tot_month);
	
}


$result = $mysqli->query("SELECT date,DATE_FORMAT(date,'%Y-%m') AS mese FROM serv_men_presenze GROUP BY date ORDER BY date");
while($row2 = $result->fetch_assoc())
	$giorni_mensa[$row2['mese']]++;


//pagina mestre
$pdf->setHeader('Insegnanti');
$pdf->AddPage();
$pdf->SetFont('Arial','B',8);
$pdf->SetFillColor(255,232,171);
$cols_header[0] = '';
$pdf->Row($cols_header);
$pdf->SetFont('Arial','',8);
$pdf->SetFillColor(255,255,255);		

	
$n_insegnanti = intval($_GET['insegnanti']);

$row[] = 'Insegnanti';
foreach($months as $k=>$mese){
	if($giorni_mensa[$mese]){
		$npasti = $giorni_mensa[$mese] * $n_insegnanti;
		$tot_pasti += $npasti;
	}else{
		$npasti = '';
	}
	$row[] = $npasti;
}

array_push($row,$tot_pasti);
array_push($row,number_format(($tot_pasti * $importo),3,',','.'));
$pdf->Row($row);
		

$pdf->Output('report_pasti.pdf','D');
?>