<?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
 */

ob_start();
@session_start(); // @ because session could be already started
include_once("../config/define.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';
}


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);
}


/**
 *
 * @param integer $id
 * @param integer $scale_id
 * @param string $type
 * @param string $workingpath
 */
function generateGraphic($id, $scale_id, $status, $type = 'auto', $display = false, $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, $workingpath);

	} else {

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

	}

}

function getMultivaluesGraphic($id, $scale_id, $status, $type, $display, $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();

	// 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]], $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 an 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;

	/* pChart library inclusions */
	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");
	
	/* 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(700,500, $MyData);
	//$myPicture = new pImage(500,350,$MyData);
	
	/* Set the default font properties */
	$myPicture->setFontProperties(array("FontName"=>"../lib/vendor/pChart/fonts/verdana.ttf","FontSize"=>7,"R"=>80,"G"=>80,"B"=>80));
	
	/* Draw the scale and the chart */
	$size = $myPicture->getLegendSize(array("Style"=>LEGEND_ROUND,"Mode"=>LEGEND_VERTICAL));
	$myPicture->setGraphArea($size["Width"] + 80,20,680,450);
	//$myPicture->drawScale(array("DrawSubTicks"=>TRUE,"Mode"=>SCALE_MODE_ADDALL_START0));
	/* Draw the scale */
	$scaleSettings = array(
			// grid settings
			"GridR"=>160,"GridG"=>160,"GridB"=>160,"GridTicks"=>1, "DrawSubTicks"=>true,"Mode"=>SCALE_MODE_ADDALL,
			// axis settings
			"AxisR"=>80,"AxisG"=>80,"AxisB"=>80,
			"CycleBackground"=>TRUE, 'LabelRotation'=>50,
			"DrawArrows"=>FALSE
			);
	$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,500 - ($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, $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
	for ($i=0; $i<count($value); $i++) {
		$ydata[$i]=$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);
	}
	
	
	/* pChart library inclusions */
	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");
	
	/* Create and populate the pData object */
	$MyData = new pData();
	//  $MyData->loadPalette("../lib/vendor/pChart/palettes/blind.color",TRUE);
	$MyData->setAxisName(0,$unit);
	$MyData->addPoints($ydata,$full_title);
	$MyData->addPoints($ydata2,"thresholds");
	$MyData->addPoints($months,"Dates");
	$MyData->setSerieDescription($full_title,$unit);
	$MyData->setAbscissa("Dates");
	
	/* Create the pChart object */
	$myPicture = new pImage(500,350,$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/fonts/verdana.ttf","FontSize"=>7,"R"=>80,"G"=>80,"B"=>80));
	/* Define the chart area */
	$myPicture->setGraphArea(50,20,480,300);
	
	
	/* Draw the scale */
	$scaleSettings = array(
			// grid settings
			"GridR"=>160,"GridG"=>160,"GridB"=>160,"GridTicks"=>1, "DrawSubTicks"=>TRUE,
			// axis settings
			"AxisR"=>80,"AxisG"=>80,"AxisB"=>80,
			"CycleBackground"=>TRUE, 'LabelRotation'=>50,
			"DrawArrows"=>FALSE);
	$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"=>80, "BorderG"=>80, "BorderB"=>80,
			// color and gradient settings
			"DisplayColor"=>DISPLAY_MANUAL,
			"Gradient"=>TRUE,"GradientStartR"=>207,"GradientStartG"=>228,"GradientStartB"=>252,
			"GradientEndR"=>146, "GradientEndG"=>174, "GradientEndB"=>206,"GradientAlpha"=>100,
			// 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);
			$MyData->setPalette($full_title,$valuesSettings);
	
			//$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"=>207,"G"=>228,"B"=>252);
			$MyData->setPalette($full_title,$valuesSettings);
	
	
			$myPicture->drawAreaChart($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();
			$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);
			$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;

}


?>