<?php
/*******************************************************************************
 * Stellware - Jugendhilfe Management System                                   *
 *                                                                             *
 * Dieses Programm ist Freie Software. Sie koennen es unter den Bedingungen    *
 * der GNU General Public License (GPL), wie von der Free Software Foundation  *
 * veroeffentlicht, weitergeben und/oder modifizieren, entweder gemaess        *
 * Version 2 der Lizenz oder, wenn Sie das wuenschen, nach jeder spaeteren     *
 * Version.                                                                    *
 *                                                                             *
 * Die Veroeffentlichung dieses Programmes erfolgt in der Hoffnung, dass es    *
 * Ihnen von Nutzen sein wird, aber ohne irgendeine Garantie, auch ohne die    *
 * implizite Garantie der Marktreife oder Verwendbarkeit fuer irgendeinen      *
 * bestimmten Zweck. Details finden Sie in der GNU General Public License in   *
 * der Datei 'gpl.txt' im Verzeichnis 'doc'.                                   *
 *                                                                             *
 *  http://www.stellware.de                                                    *
 *******************************************************************************
 *
 * $Id: pdf_diagram.inc.php 2979 2019-04-15 14:37:34Z tfreudenberg $
 *
 */


/* Kopf- und Fußzeile für Standardlisten, A4 Hochformat
 *
 *******************/

// FPDF laden
require($_SESSION['basedir'] . '/inc/fpdf/fpdf.php');

class PDF extends FPDF {
    var $legends;
    var $yearlegends;
    var $wLegend;
    var $sum;
    var $NbVal;
    var $angle=0;

	function Header()
	{
		global $no_ds;
		global $header;
		$logo = $_SESSION['basedir'] . '/mandant/swe/stwlogo.jpg';
		$logo_xh = ($this->CurOrientation == 'P') ? 175 : 262;
		if($this->CurPageFormat[0] > 297) $logo_xh *= 1.5;
		$logo_y = 5;
		$logo_w = 20;

		/* Kopfzeile */
		$this->SetFont('Arial','B',12);
		$this->Text(15,13,getConf('trname'));
		if (strlen(getConf('imgLogo')) > 0){
			$this->Image($logo,$logo_xh,$logo_y,$logo_w);
		}
		$this->SetFillColor(150,150,150);
		$width = ($this->CurOrientation == 'P') ? 160 : 242;
		if($this->CurPageFormat[0] > 297) $width *= 1.55;
		$this->Rect(15,15,$width,1,'F');
		$this->SetFont('stw','',11);
		if ($no_ds == false){
			$this->Text(15,20,'Datenschutz beachten! Aktenvernichter verwenden!');
		}
		$this->Text(80,13,$header);
	}

	//Page footer
	function Footer()
	{
		global $no_footline;
		global $no_foot;
		global $footer;
		global $no_nr;
		// Fußzeile
		if ($no_footline == true){
		} else {
			$this->SetFillColor(150,150,150);
			if($this->CurPageFormat[0] > 297) {
				$this->Rect(15,275,395,1,'F');
			} elseif ($this->CurOrientation == 'P'){
				$this->Rect(15,275,180,1,'F');
			} else {
				$this->Rect(15,188,267,1,'F');
			}
		}
		$this->SetFont('Arial','',9);
		$footer1 = "Stellware Ausdruck ";
		$footer1 .= date("d.m.Y, H:i");
		$footer1 .= " Uhr";

		$footer2 = $footer;
		$footer2 .= "      Seite ";
		$footer2 .= $this->PageNo() . " / {nb}";

		if($this->CurPageFormat[0] > 297) {
			$this->SetXY(15,276);
			$breite = 198;
		} elseif ($this->CurOrientation == 'P'){
			$this->SetXY(15,276);
			$breite = 90;
		} else {
			$this->SetXY(15,189);
			$breite = 133.5;
		}

		if ($no_foot == true){
			$this->Cell($breite,5,'',0,0,'L');
		} else {
			$this->Cell($breite,5,$footer1,0,0,'L');
		}
		if ($no_nr == true){
		} else {
			$this->Cell($breite,5,$footer2,0,0,'R');
		}
	}

	function Sector($xc, $yc, $r, $a, $b, $style='FD', $cw=true, $o=90)
	{
		$d0 = $a - $b;
		if($cw){
			$d = $b;
			$b = $o - $a;
			$a = $o - $d;
		}else{
			$b += $o;
			$a += $o;
		}
		while($a<0)
			$a += 360;
		while($a>360)
			$a -= 360;
		while($b<0)
			$b += 360;
		while($b>360)
			$b -= 360;
		if ($a > $b)
			$b += 360;
		$b = $b/360*2*M_PI;
		$a = $a/360*2*M_PI;
		$d = $b - $a;
		if ($d == 0 && $d0 != 0)
			$d = 2*M_PI;
		$k = $this->k;
		$hp = $this->h;
		if (sin($d/2))
			$MyArc = 4/3*(1-cos($d/2))/sin($d/2)*$r;
		else
			$MyArc = 0;
		//first put the center
		$this->_out(sprintf('%.2F %.2F m',($xc)*$k,($hp-$yc)*$k));
		//put the first point
		$this->_out(sprintf('%.2F %.2F l',($xc+$r*cos($a))*$k,(($hp-($yc-$r*sin($a)))*$k)));
		//draw the arc
		if ($d < M_PI/2){
			$this->_Arc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a),
						$yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a),
						$xc+$r*cos($b)+$MyArc*cos($b-M_PI/2),
						$yc-$r*sin($b)-$MyArc*sin($b-M_PI/2),
						$xc+$r*cos($b),
						$yc-$r*sin($b)
						);
		}else{
			$b = $a + $d/4;
			$MyArc = 4/3*(1-cos($d/8))/sin($d/8)*$r;
			$this->_Arc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a),
						$yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a),
						$xc+$r*cos($b)+$MyArc*cos($b-M_PI/2),
						$yc-$r*sin($b)-$MyArc*sin($b-M_PI/2),
						$xc+$r*cos($b),
						$yc-$r*sin($b)
						);
			$a = $b;
			$b = $a + $d/4;
			$this->_Arc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a),
						$yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a),
						$xc+$r*cos($b)+$MyArc*cos($b-M_PI/2),
						$yc-$r*sin($b)-$MyArc*sin($b-M_PI/2),
						$xc+$r*cos($b),
						$yc-$r*sin($b)
						);
			$a = $b;
			$b = $a + $d/4;
			$this->_Arc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a),
						$yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a),
						$xc+$r*cos($b)+$MyArc*cos($b-M_PI/2),
						$yc-$r*sin($b)-$MyArc*sin($b-M_PI/2),
						$xc+$r*cos($b),
						$yc-$r*sin($b)
						);
			$a = $b;
			$b = $a + $d/4;
			$this->_Arc($xc+$r*cos($a)+$MyArc*cos(M_PI/2+$a),
						$yc-$r*sin($a)-$MyArc*sin(M_PI/2+$a),
						$xc+$r*cos($b)+$MyArc*cos($b-M_PI/2),
						$yc-$r*sin($b)-$MyArc*sin($b-M_PI/2),
						$xc+$r*cos($b),
						$yc-$r*sin($b)
						);
		}
		//terminate drawing
		if($style=='F')
			$op='f';
		elseif($style=='FD' || $style=='DF')
			$op='b';
		else
			$op='s';
		$this->_out($op);
	}

	function _Arc($x1, $y1, $x2, $y2, $x3, $y3 )
	{
		$h = $this->h;
		$this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
			$x1*$this->k,
			($h-$y1)*$this->k,
			$x2*$this->k,
			($h-$y2)*$this->k,
			$x3*$this->k,
			($h-$y3)*$this->k));
	}

    function PieChart($w, $h, $data, $format, $colors=null, $legendsTopMargin=true, $keineLegendeBei0=false)
    {
		$this->SetFont('Arial','',9);
        $this->SetLegends($data, $format, 0, $keineLegendeBei0);

        $XPage = $this->GetX();
        $YPage = $this->GetY();
        $margin = 1;
        $hLegend = 4;
        $radius = min($w - $margin * 4 - $hLegend - $this->wLegend, $h - $margin * 2);
        $radius = floor($radius / 2);
        $XDiag = $XPage + $margin + $radius;
        $YDiag = $YPage + $margin + $radius;
        if($colors == null) {
            for($i = 0;$i < $this->NbVal; $i++) {
                $gray = $i * intval(255 / $this->NbVal);
                $colors[$i] = array($gray, $gray, $gray);
            }
        }

        //Sectors
        $this->SetLineWidth(0.2);
        $angleStart = 0;
        $angleEnd = 0;
        $i = 0;
        foreach($data as $val) {
            $angle = ($this->sum==0) ? ($i==0 ? 360 : 0) : (($val * 360) / doubleval($this->sum));
			$this->SetFillColor($colors[$i][0], $colors[$i][1], $colors[$i][2]);
            if ($angle != 0) {
                $angleEnd = $angleStart + $angle;
                $this->Sector($XDiag, $YDiag, $radius, $angleStart, $angleEnd);
                $angleStart += $angle;
            }
            $i++;
        }

        //Legends
		$this->SetFont('Arial','',9);
        $x1 = $XPage + 2 * $radius + 4 * $margin;
        $x2 = $x1 + $hLegend + $margin;
        $y1 = $YDiag - $radius + (2 * $radius - $this->NbVal*($hLegend + $margin)) / 2;
		if($legendsTopMargin) $y1 = max($YPage, $y1);
		if($YPage < $y1) {
            $this->SetXY($x1, $y1-($hLegend + $margin)/2);
            $this->Cell(0, 4, $this->sum . ($this->sum==1 ? " Eintrag" : " Einträge"));
            $y1+= ($hLegend + $margin)/2;
		} else {
            $this->SetXY($XPage, $YDiag + $radius);
            $this->Cell(2*$radius+4*$margin, 4, $this->sum . ($this->sum==1 ? " Eintrag" : " Einträge"),0,0,'R');
		}
        foreach($this->legends as $i => $legend) {//($i=0; $i<$this->NbVal; $i++) {
            $this->SetFillColor($colors[$i][0], $colors[$i][1], $colors[$i][2]);
            $this->Rect($x1, $y1, $hLegend, $hLegend, 'DF');
            $this->SetXY($x2, $y1);
            $this->Cell(0, $hLegend, $legend);
            $y1+=$hLegend + $margin;
        }
    }

    function BarDiagram($w, $h, $data, $format, $color=null, $maxVal=0, $count=0, $nbDiv=4, $xaxis='', $yaxis='', $showscales = true, $showLines = true)
    {
		$this->SetFont('Arial','',9);
        $this->SetLegends($data, $format, $count);

        $XPage = $this->GetX();
        $YPage = $this->GetY();
        $margin = 1;
        $YDiag = $YPage + $margin;
        $hDiag = floor($h - $margin * 2 - 10);
        $XDiag = $XPage + $margin * 2;
        $lDiag = floor($w - $margin * 3);
        if($color == null)
            $color=array(155, 155, 155);
        if ($maxVal == 0) {
            $maxVal = empty($data) ? 1 : max($data);
        }
        $valIndRepere = ceil($maxVal / $nbDiv);
        $maxVal = $valIndRepere * $nbDiv;
        $lRepere = floor($hDiag / $nbDiv);

        $hDiag = $lRepere * $nbDiv;
        $unit = $hDiag / $maxVal;

        $lBar = ($lDiag / ($this->NbVal + 1));
        $lDiag = $lBar * ($this->NbVal + ($count==0 ? 0 : 1));
        $eBaton = ($lBar * 80 / 100);
        $this->SetLineWidth(0.2);
        if($showscales) $this->Rect($XDiag, $YDiag, $lDiag+$lBar, $hDiag);

		$this->SetFont('Arial','',9);
        $this->SetFillColor($color[0], $color[1], $color[2]);
		if($count == 0) {
		  $i = 0;
		  $fiveyears = (sizeof($data) >= 60);
		  foreach($data as $l=>$val) {
            //Bar
            $xval = $XDiag + ($i + 1) * $lBar - $eBaton / 2;
            $lval = $eBaton;
            $yval = $YDiag+$hDiag;
            $hval = -($val * $unit);
			if(!$showLines) $this->SetDrawColor($color[0], $color[1], $color[2]);
            $this->Rect($xval, $yval, $lval, $hval, 'DF');
			if(!$showLines) $this->SetDrawColor(0,0,0);
            //Legend
			if($showscales) {
				$this->SetXY($xval, $yval);
				$this->SetFont('Arial','',7);
				if(!$fiveyears || empty($this->yearlegends)) $this->Cell($lval, 4, $this->legends[$i], 0, 0, 'C');
				if(!empty($this->yearlegends)) {
					$this->SetXY($xval, $yval+($fiveyears ? 2 : 4));
					$b = $i==0 ? 'LB' : ($this->legends[$i]==12 ? 'RB' : 'B');
					$this->Cell($lBar,2,$this->yearlegends[$i],$b,0,'C');
				}
			}
			$i++;
		  }
		  if($showscales && !empty($this->yearlegends)) $this->Cell(1,2,'','L');
        } else for($i=0;$i<=$this->NbVal;$i++) {
            //Bar
            $xval = $XDiag + ($i + 1) * $lBar - $eBaton / 2;
            $lval = $eBaton;
            $yval = $YDiag+$hDiag;
            $hval = -($data[$i] * $unit);
            if(!$showLines) $this->SetDrawColor($color[0], $color[1], $color[2]);
			$this->Rect($xval, $yval, $lval, $hval, 'DF');
			if(!$showLines) $this->SetDrawColor(0,0,0);
            //Legend
			if($showscales) {
				$this->SetXY($xval, $yval);
				$this->SetFont('Arial','',7);
				$this->Cell($lval, 4, $this->legends[$i], 0, 0, 'C');
			}
        }

        //Scales
		if($showscales) {
		  $this->RotatedText($XDiag-4, $YDiag+$hDiag, $yaxis, 90);
		  $this->SetXY($XDiag+$lBar,$YDiag+$hDiag+6);
		  $this->Cell($lDiag,4,$xaxis,0,0,'R');
          for ($i = 0; $i <= $nbDiv; $i++) {
            $ypos = $YDiag+$hDiag - $lRepere * $i;
            $this->Line($XDiag, $ypos, $XDiag + $lDiag + $lBar, $ypos);
            $val = $i * $valIndRepere;
            $this->SetXY($XDiag-3*$margin, $ypos-2);
            $this->Cell(3,4,$val,0,0,'R');
		  }
        }
    }

	function Polygon($points, $style='D')
	{
		//Draw a polygon
		if($style=='F')
			$op='f';
		elseif($style=='FD' or $style=='DF')
			$op='b';
		else
			$op='s';

		$h = $this->h;
		$k = $this->k;

		$points_string = '';
		for($i=0; $i<count($points); $i+=2){
			$points_string .= sprintf('%.2f %.2f', $points[$i]*$k, ($h-$points[$i+1])*$k);
			if($i==0)
				$points_string .= ' m ';
			else
				$points_string .= ' l ';
		}
		$this->_out($points_string . $op);
	}

	function PolygonDiagram($w, $h, $data, $color=NULL, $max_value = NULL, $style = 'FD', $axes = false) {
        $YPage = $this->GetY() + $h;
        $XPage = $this->GetX() + 5;
		if(empty($max_value)) $max_value = empty($data) ? 1 : max($data);
		$max_count = sizeof($data);
		$points = array();
		if($color) {
			if($style=='D') {
				$this->SetDrawColor($color[0], $color[1], $color[2]);
				$this->SetLineWidth('0.5');
			} else $this->SetFillColor($color[0], $color[1], $color[2]);
		}
		foreach($data as $l=>$val) {
			$y = $YPage - $val * $h / $max_value;
			$x = $l * $w / $max_count + $XPage;
			$points[] = $x;
			$points[] = $y;
		}
		$points[] = $x;
		$points[] = $YPage;
		$this->Polygon($points, $style);

		$this->SetDrawColor(0);
		if($axes) {
			$this->SetLineWidth('0.5');
			$this->Line($x, $YPage, $XPage, $YPage);
			$this->Line($XPage, $YPage-$h, $XPage, $YPage);
			$this->SetLineWidth('0.2');
			$this->Line($XPage, $YPage-$h-1, $XPage-1, $YPage-$h+2);
			$this->Line($XPage, $YPage-$h-1, $XPage+1, $YPage-$h+2);
			$this->Line($x+1, $YPage, $x-2, $YPage-1);
			$this->Line($x+1, $YPage, $x-2, $YPage+1);
			$this->SetFont('Arial','',6);
			$this->SetXY($XPage-3,$YPage-$h-1);
			$this->Cell(3,3,round($max_value,0),0,0,'R');
			$this->SetXY($XPage-3,$YPage-($h/2)-1);
			$this->Cell(3,3,round($max_value/2,0),0,0,'R');
			$this->SetXY($XPage,$YPage+2);
		}
	}

	function LineDiagram($w, $h, $data)
    {
		$XPage = $this->GetX();
		$YPage = $this->GetY();
		$max_value = 0;
		$max_count = 0;
		foreach($data as $l=>$val) {
			if($max_value < $l) $max_value = $l;
			if($max_count < $val) $max_count = $val;
		}
		$refY = $y = $this->GetY()+$h+5;
		$refX = $x = $this->GetX()+3;

		$this->SetFont('Arial','',6);
		$this->Cell(3,10,"$max_count",0,0,'R');
		$this->Cell($w+5,$h+5,'','LB',1);
		$this->SetX($XPage);
		$this->Cell($w/2+5,3,$max_value/2,0,0,'R');
		$this->Cell($w/2,3,$max_value,0,1,'R');
		$this->Line($x, $y-$h-5, $x-1, $y-$h-2);
		$this->Line($x, $y-$h-5, $x+1, $y-$h-2);
		$this->Line($x+$w+5, $y, $x+$w+2, $y-1);
		$this->Line($x+$w+5, $y, $x+$w+2, $y+1);

		foreach($data as $l=>$val) {
			$newX = $refX + ($l * $w) / $max_value;
			$newY = $refY - ($val * $h) / $max_count;
			$this->Line($x, $y, $newX, $newY);
			$x = $newX; $y = $newY;
		}
    }

    function SetLegends($data, $format, $count=0, $keineLegendeBei0=false)
    {
        $this->legends=array();
        $this->wLegend=0;
        $this->sum = array_sum($data);
		if($count > 0) {
			$this->NbVal=$count;
			for($l=0;$l<=$this->NbVal;$l++) {
				$val = $data[$l];
				$p=($this->sum==0) ? "0.00%" : sprintf('%.2f', $val/$this->sum*100).'%';
				$legend=str_replace(array('%l', '%v', '%p'), array($l, $val, $p), $format);
				$this->legends[] = ($l % ($this->NbVal>100 ? 10 : 5) == 0) ? $legend : '';
				$this->wLegend=max($this->GetStringWidth($legend), $this->wLegend);
			}
		} else {
			if($keineLegendeBei0) {
				$this->NbVal = 0;
				foreach($data as $l=>$val) if($val > 0) $this->NbVal++;
			} else $this->NbVal=count($data);
			$this->yearlegends=array();
			$pos = false;
			$jahr = '';
			$monat1 = 1;
			$l = 1;
			$I = -1;
			foreach($data as $l=>$val) {
				$I++;
				if($keineLegendeBei0 && $val == 0) continue;
				$pos = strpos($l,'.');
				if($pos!==false) {
					$y = substr($l,$pos+1);
					$l = substr($l,0,$pos);
					if($y != $jahr) {
						if(!empty($jahr)) {
							$i = sizeof($this->legends) - ceil((12-$monat1)/2) - 1;
							$this->yearlegends[$i] = $jahr;
						}
						$jahr = $y;
						$monat1 = $l;
					}
				}
				$p=($this->sum==0) ? "0.00%" : sprintf('%.2f', $val/$this->sum*100).'%';
				$legend=str_replace(array('%l', '%v', '%p'), array($l, $val, $p), $format);
				$this->legends[$I]=$legend;
				$this->wLegend=max($this->GetStringWidth($legend), $this->wLegend);
			}
			if($pos!==false) {
				$i = sizeof($this->legends) - ceil(($l-$monat1)/2);
				$this->yearlegends[$i] = $jahr;
			}
		}
    }

	function Rotate($angle, $x=-1, $y=-1){
		if($x==-1)
			$x=$this->x;
		if($y==-1)
			$y=$this->y;
		if($this->angle!=0)
			$this->_out('Q');
		$this->angle=$angle;
		if($angle!=0)
		{
			$angle*=M_PI/180;
			$c=cos($angle);
			$s=sin($angle);
			$cx=$x*$this->k;
			$cy=($this->h-$y)*$this->k;
			$this->_out(sprintf('q %.5f %.5f %.5f %.5f %.2f %.2f cm 1 0 0 1 %.2f %.2f cm', $c, $s, -$s, $c, $cx, $cy, -$cx, -$cy));
		}
	}

	function RotatedText($x, $y, $txt, $angle){
		//Text rotated around its origin
		$this->Rotate($angle, $x, $y);
		$this->Text($x, $y, $txt);
		$this->Rotate(0);
	}

	function _endpage(){
		if($this->angle!=0)
		{
			$this->angle=0;
			$this->_out('Q');
		}
		parent::_endpage();
	}

}
?>
