<?php
/**
 * Dashboard module
 * 
 * Generate charts displayed in both admin and public UIs
 * Can either display them inline or save them into given folder
 * 
 * @package linea21\modules\dashboard
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */


/**
 * Warning : If a trailing whitespace is present in any embedded file (for example, a plugin file), this graph won't display
 */


include_once("../config/define.php");



ob_start();
@session_start(); // @ because session could be already started

/* pChart library inclusions based on PHP version */
if(num_phpversion() >= 700) $pchart = 'pChart-php7';
else $pchart = 'pChart';

include_once("../lib/vendor/".$pchart."/class/pData.class.php");
include_once("../lib/vendor/".$pchart."/class/pDraw.class.php");
include_once("../lib/vendor/".$pchart."/class/pImage.class.php");


//////////// Check Inclusion de pages ////////////
if (!class_exists('auth')){
	include_once("../lib/lib_common.php");
	ReloadIndex('admin');
}
////////////

// necessary because the file can be called with URL parameters or using a function (exports)
if(isset($_GET['scale_id'])) $scale_id=$_GET['scale_id'];
if(isset($_GET['id'])) $id=$_GET['id'];

if(isset($_GET['type'])) {
	$type = $_GET['type'];
} else {
	$type = 'auto';
}

// getting chart sizes from config file
list($width, $height) = explode('x', CHART_DEFAULT_SIZE);

// getting width and height if passed to url
if(isset($_GET['w'])) {
    $width = $_GET['w'];
    isset($_GET['h']) ? $height = $_GET['h'] : $height = round($width/1.4);
}

include_once("../class/class.sdi.php");
include_once(SQL.".inc.php");

// if display is passed to url we display it now
if(isset($_GET['display'])) {
    generateGraphic($id, $scale_id, 'SCP', $type, true, $width, $height);
}


/**
 *
 * @param integer $id
 * @param integer $scale_id
 * @param string $type
 * @param string $workingpath
 */
function generateGraphic($id, $scale_id, $status, $type = 'auto', $display = false, $width, $height, $workingpath ='') {

	global $sql_object;

	$data = $sql_object->DBSelect(SQL_getInfoSdi($id));

	if($data[0]['sdii_value_type'] == 'unique' ) {

	    return getSinglevalueGraphic($id, $scale_id, $status, $type, $display, $width, $height, $workingpath);

	} else {

	    return getMultivaluesGraphic($id, $scale_id, $status, $type, $display, $width, $height, $workingpath);

	}

}

function getMultivaluesGraphic($id, $scale_id, $status, $type, $display, $width, $height, $workingpath ='') {

	global $sql_object;
	
	// we get values
	$req_sdiav=SQL_getAllValue($status, $scale_id, $id, 'ASC');
	$value = $sql_object->DBSelect($req_sdiav);
	$req_sdii=SQL_getInfoSdi($id);
	$result_sdii = $sql_object->DBSelect($req_sdii);
	
	$unit=$result_sdii[0]['sdii_unit'];
	$full_title=formatText($result_sdii[0]['sdii_name']);
	$title=cutText($full_title, 50, 0);
	
	// visualization type
	if($type == 'auto') {
		$type = $result_sdii[0]['sdii_detail_viz'];
	}
	
	$is_null_threshold = true; // is the threshold null or not? to know if we display it

	$a_labels = array();
	$stacked_data = array();
	$ydata2 = array();

	// we get all distinct labels
	for ($i=0; $i<count($value); $i++) {

		$data = unserialize($value[$i]['sdiv_multivalue']);

		foreach($data as &$val) {
			if(!in_array($val['label'], $a_labels)) {
				array_push($a_labels, $val['label']);
			}
		}

		
		// setting $threshold_value
		// By default initial value
		$ydata2[$i]=$result_sdii[0]['sdii_threshold_value'];
		// if set, we get it from the table
		if(!is_null($value[$i]['sdiv_threshold'])) {
			$ydata2[$i]=$value[$i]['sdiv_threshold'];
		}
		// if at least one numeric value is there test is false
		if(is_numeric($ydata2[$i])) $is_null_threshold = false;

		// we get dates
		list($day, $month, $year)=explode('-',$value[$i]['date_p']);
		$months[$i] = $day . '-' .$month. '-'. substr($year, 2, 2);
	}


	// we loop on labels to prepare data for each of them
	for ($k=0; $k<count($a_labels); $k++) {

		// we loop on values values
		for ($i=0; $i<count($value); $i++) {
		
			$data = unserialize($value[$i]['sdiv_multivalue']);

			$is_set = false; // flag to know id label is present or not
		
			foreach($data as &$val) {
				
				if($val['label'] == $a_labels[$k]) {

					// we define the key as an array is not defined yet
					if(!isset($stacked_data[$a_labels[$k]])) {
						$stacked_data[$a_labels[$k]] = array();
					}
					// and we push the value into the nested array
					array_push($stacked_data[$a_labels[$k]], (float) $val['value']);

// 					echo "<br>adding " . $val['value'] . " to " . $a_labels[$k]. " array <br><BR>";

					$is_set = true;
				}
			}
			// if label is not found we set VOID value

			if($is_set === false) {
				// we define the key as the array is not defined yet
				if(!isset($stacked_data[$a_labels[$k]])) {
					$stacked_data[$a_labels[$k]] = array();
				}
				array_push($stacked_data[$a_labels[$k]], VOID);
			}
			//echo "<br>---------------<br>";
		}

	}


// 	print_r($a_labels);
// 	print_r($stacked_data);
// 	var_dump($stacked_data);
// 	exit;


	
	/* Create and populate the pData object */
	$MyData = new pData();

	$MyDataThreshold = new pData();

	// ability for user to specify a palette for each individual indicator
	$palette = override('../dashboard/palettes/'.$id. '.color');
	if(file_exists($palette)) {
		$MyData->loadPalette($palette, TRUE);
	} else {
		$MyData->loadPalette(override('../dashboard/palettes/default.color'), TRUE);
	}

	// we loop on labels
	for ($k=0; $k<count($a_labels); $k++) {
		// echo join(', ', $stacked_data[$a_labels[$k]]).' - '. $a_labels[$k].'<br>';
		$MyData->addPoints($stacked_data[$a_labels[$k]], $a_labels[$k]);

	}
	// uncomment to display threshold - Be careful, add threshold values to scale
// 	$MyData->addPoints($ydata2,"thresholds");
	$MyData->setAxisName(0,$unit);
	$MyData->addPoints($months,"Labels");
	$MyData->setSerieDescription("Labels","Months");
	$MyData->setAbscissa("Labels");
	
	
	/* Create the pChart object */
	$myPicture = new pImage($width, $height, $MyData);
	//$myPicture = new pImage(500,350,$MyData);
	
	/* Set the default font properties */
	$myPicture->setFontProperties(array("FontName"=>"../lib/vendor/pChart-php7/fonts/verdana.ttf","FontSize"=>8,"R"=>120,"G"=>120,"B"=>120));
	
	/* Draw the scale and the chart */
	$size = $myPicture->getLegendSize(array("Style"=>LEGEND_ROUND,"Mode"=>LEGEND_VERTICAL));
	$myPicture->setGraphArea($size["Width"] + 80, 20, $width - 20, $height - 50);
	//$myPicture->drawScale(array("DrawSubTicks"=>TRUE,"Mode"=>SCALE_MODE_ADDALL_START0));
	/* Draw the scale */
	$scaleSettings = array(
            // grid settings
        "GridR" => 180,
        "GridG" => 180,
        "GridB" => 180,
        "GridTicks" => 1,
        "DrawSubTicks" => false, // ne pas afficher les entre ticks
	    "Mode" => SCALE_MODE_ADDALL, // SCALE_MODE_FLOATING does not display all values because is not able to calculate sum values
	    // axis color
	    "AxisR" => 200,
	    "AxisG" => 200,
	    "AxisB" => 200,
	    "CycleBackground" => true,
	    // background color 2
	    "BackgroundR2" => 240,
	    "BackgroundG2" => 240,
	    "BackgroundB2" => 240,
	    'LabelRotation' => 50,
        "DrawArrows" => FALSE,
	    "GridAlpha" => 30,
	    "TickAlpha" => 40
    );
	$myPicture->drawScale($scaleSettings);
	$myPicture->setShadow(FALSE);
	$MyData->setSerieDrawable("thresholds",FALSE);
	$myPicture->drawStackedBarChart(array("Surrounding"=>-15,"InnerSurrounding"=>15,
			"Rounded"=>false,
			// "Interleave" =>.5,
			"DisplayValues"=>true, "DisplayR"=>80, "DisplayG"=>80, "DisplayB"=>80,
			));

// uncomment to display threshold
// 	$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
// 	$MyData->setPalette("thresholds",$thresholdsSettings);
// 	// if at least one threshold is there we display the serie on graph
// 	if(!$is_null_threshold) {
// 		$MyData->setSerieDrawable("thresholds",TRUE);
// 	}
// 	// we loop on labels
// 	for ($k=0; $k<count($a_labels); $k++) {
// 		$MyData->setSerieDrawable($a_labels[$k],FALSE);
// 	}
	
// 	$myPicture->drawSplineChart();
// 	$myPicture->drawPlotChart();
	
	/* Write a label */
// 	 $myPicture->writeLabel(array("Frontend #1","Frontend #2","Frontend #3"),2,array("DrawVerticalLine"=>TRUE));
	
	/* Write the chart legend */
	$myPicture->drawLegend(20, $height - ($size["Height"] + 50),array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_VERTICAL,"Style"=>LEGEND_ROUND, "Alpha"=>20, ""));
	
	/* Render the picture (choose the best way) */
	if($display == true) {
			/* Render the picture - display it */
			$myPicture->autoOutput("simple.png");
		} else {
			/* Save the picture */
			if(!file_exists($workingpath)) mkdir($workingpath);
			$myPicture->render($workingpath.'/'.$id.'_'.$scale_id.'.png');
		}
}

function getSinglevalueGraphic($id, $scale_id, $status, $type, $display, $width, $height, $workingpath) {

	global $sql_object;
	
	// we get values
	$req_sdiav=SQL_getAllValue($status, $scale_id, $id, 'ASC');
	$value = $sql_object->DBSelect($req_sdiav);
	$req_sdii=SQL_getInfoSdi($id);
	$result_sdii = $sql_object->DBSelect($req_sdii);
	
	$unit=$result_sdii[0]['sdii_unit'];
	$full_title=formatText($result_sdii[0]['sdii_name']);
	$title=cutText($full_title, 50, 0);
	
	// visualization type
	if($type == 'auto') {
		$type = $result_sdii[0]['sdii_detail_viz'];
	}
	
	$is_null_threshold = true; // is the threshold null or not? to know if we display it
	$ydata2 = array();
	
	for ($i=0; $i<count($value); $i++) {
	    //$ydata[$i]=$value[$i]['sdiv_value'];
	    $ydata[$i]=(float) $value[$i]['sdiv_value'];
		// setting $threshold_value
		// By default initial value
		$ydata2[$i]=$result_sdii[0]['sdii_threshold_value'];
		// if set, we get it from the table
		if(!is_null($value[$i]['sdiv_threshold'])) {
			$ydata2[$i]=$value[$i]['sdiv_threshold'];
		}
		// if at least one numeric value is there test is false
		if(is_numeric($ydata2[$i])) $is_null_threshold = false;
	
		list($day, $month, $year)=explode('-',$value[$i]['date_p']);
		$months[$i] = $day . '-' .$month. '-'. substr($year, 2, 2);
	}
	
	
	/* Create and populate the pData object */
	$MyData = new pData();
	//  $MyData->loadPalette("../lib/vendor/pChart-php7/palettes/blind.color",TRUE);
	$MyData->setAxisName(0,$unit);
	$MyData->addPoints($ydata,$full_title);
	if(!$is_null_threshold) $MyData->addPoints($ydata2,"thresholds");
	$MyData->addPoints($months,"Dates");
	$MyData->setSerieDescription($full_title,$unit);
	$MyData->setAbscissa("Dates");
	
	/* Create the pChart object */
	$myPicture = new pImage($width,$height,$MyData);
	/* Turn of Antialiasing */
	$myPicture->Antialias = TRUE;
	/* Add a border to the picture */
	// $myPicture->drawRectangle(0,0,499,349,array("R"=>180,"G"=>180,"B"=>180));
	/* Set the default font */
	$myPicture->setFontProperties(array("FontName"=>"../lib/vendor/pChart-php7/fonts/verdana.ttf","FontSize"=>8,"R"=>120,"G"=>120,"B"=>120));
	/* Define the chart area */
	$myPicture->setGraphArea(50,20,$width-20,$height-50);
        
        /* Draw the scale */
    $scaleSettings = array(
        // grid settings
        "GridR" => 180,
        "GridG" => 180,
        "GridB" => 180,
        "GridTicks" => 1,
        "DrawSubTicks" => false, // ne pas afficher les entre ticks 
        "Mode" => SCALE_MODE_FLOATING, // SCALE_MODE_ADDALL prevent "non-numeric input" error with pChart-php7 see aroune line 2005 in /class/pDraw.class.php
        // axis color
        "AxisR" => 200,
        "AxisG" => 200,
        "AxisB" => 200,
        "CycleBackground" => true,
        // background color 2
        "BackgroundR2" => 240,
        "BackgroundG2" => 240,
        "BackgroundB2" => 240,
        'LabelRotation' => 50,
        "DrawArrows" => FALSE,
        "GridAlpha" => 30,
        "TickAlpha" => 40
    );
	$myPicture->drawScale($scaleSettings);
	
	
	
	/* Draw the chart */
	$myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10)); /* Turn on shadow computing */
	$settings = array(
			//"InnerBorderR"=>80, "InnerBorderG"=>80, "InnerBorderB"=>80,
	        //"BorderR"=>210, "BorderG"=>210, "BorderB"=>210,
			// color and gradient settings
// 			"Rounded"=>true,
			"DisplayColor"=> DISPLAY_MANUAL,
	        "DisplayR"=> 98, "DisplayG"=> 194,"DisplayB" => 204,
// 			"Gradient"=>TRUE,"GradientStartR"=>207,"GradientStartG"=>228,"GradientStartB"=>252,
	        "Gradient"=>FALSE,
			// label settings
			"DisplayValues"=>FALSE, "DisplayPos"=>LABEL_POS_OUTSIDE,"DisplayR"=>115,"DisplayG"=>115,"DisplayB"=>115,"DisplayOrientation"=>ORIENTATION_AUTO,
			"DisplayShadow"=>FALSE,
			"Draw0Line"=>FALSE,
			//"Rounded"=>TRUE, // not working with gradient
			"Surrounding"=>-30,
			"InnerSurrounding"=>0);
	
	/* Write the chart legend */
	//$myPicture->drawLegend(50,5,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL));
	
	
	
	
	switch ($type) {
		case 'line':
			$MyData->setSerieDrawable($full_title,TRUE);
			$MyData->setSerieDrawable("thresholds",FALSE);
	
			$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
			$MyData->setPalette("thresholds",$thresholdsSettings);
			$valuesSettings = array("R"=>36,"G"=>47,"B"=>74); // bleu foncé
			$valuesSettings = array("R"=>74,"G"=>192,"B"=>242); // bleu clair
			$MyData->setPalette($full_title,$valuesSettings);
			/**
			 * Do not activate beacause it creates aliasing
			$MyData->setSerieTicks("thresholds",4);
			$MyData->setSerieWeight("thresholds", 0.5);
			$MyData->setSerieWeight($full_title, 1);
			*/
	
			//$MyData->setSerieWeight($full_title, 0.5); // will draw a 1px curve - not nice with drawSplineChart
			//$myPicture->drawLineChart($settings);
			$myPicture->drawSplineChart($settings);
			$myPicture->drawPlotChart($settings);
	
			/* Draw the line and plot chart */
			$myPicture->setShadow(FALSE); /* Turn off shadow computing */
	
			// if at least one threshold is there we display the serie on graph
			if(!$is_null_threshold) {
				$MyData->setSerieDrawable("thresholds",TRUE);
			}
			$MyData->setSerieDrawable($full_title,FALSE);
			$myPicture->drawSplineChart();
			// $myPicture->drawLineChart($settings);
			// $myPicture->drawPlotChart();
	
			break;
		case 'area':
			$MyData->setSerieDrawable($full_title,TRUE);
			$MyData->setSerieDrawable("thresholds",FALSE);
			
			$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
			$MyData->setPalette("thresholds",$thresholdsSettings);
// 			$valuesSettings = array("R"=>137,"G"=>214,"B"=>244, "Alpha"=>100); // bleu clair
// 			$MyData->setPalette($full_title,$valuesSettings);
			
			// il faut utiliser les seuils pour choisir la couleur de remplissage
			$Threshold[0] = array("Min"=>-9999,"Max"=>99999999999,"R"=>137,"G"=>214,"B"=>244,"Alpha"=>80);
			
			$myPicture->drawAreaChart(array("Threshold"=>$Threshold));
	
			/* Draw the line and plot chart */
			$myPicture->setShadow(FALSE); /* Turn off shadow computing */
	
			// if at least one threshold is there we display the serie on graph
			if(!$is_null_threshold) {
				$MyData->setSerieDrawable("thresholds",TRUE);
			}
			$MyData->setSerieDrawable($full_title,FALSE);
			//$myPicture->drawSplineChart();
			$myPicture->drawLineChart();
			$myPicture->drawPlotChart();
	
			break;
		default: // 'column' type
			$MyData->setSerieDrawable($full_title,TRUE);
			$MyData->setSerieDrawable("thresholds",FALSE);
	
			$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
			$MyData->setPalette("thresholds",$thresholdsSettings);
			
			$valuesSettings = array("R"=>207,"G"=>228,"B"=>252);
			$valuesSettings = array("R"=>98,"G"=>194,"B"=>204); # azur
			$valuesSettings = array("R"=>74,"G"=>192,"B"=>242, "Alpha"=> 100); // bleu clair
			$valuesSettings = array("R"=>137,"G"=>214,"B"=>244, "Alpha"=> 100); // bleu clair
			$MyData->setPalette($full_title,$valuesSettings);
	
			$myPicture->drawBarChart($settings);
	
			/* Draw the line and plot chart */
			$myPicture->setShadow(FALSE); /* Turn off shadow computing */
	
			// if at least one threshold is there we display the serie on graph
			if(!$is_null_threshold) {
				$MyData->setSerieDrawable("thresholds",TRUE);
			}
			$MyData->setSerieDrawable($full_title,FALSE);
			$myPicture->drawSplineChart();
			$myPicture->drawPlotChart();
			break;
	}
	
	if($display == true) {
		/* Render the picture - display it */
		$myPicture->autoOutput("simple.png");
	} else {
		/* Save the picture */
		if(!file_exists($workingpath)) mkdir($workingpath);
		$myPicture->render($workingpath.'/'.$id.'_'.$scale_id.'.png');
	}
	
	return true;

}


?>