<?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");
include_once("../languages/fr/lang_dashboard.utf-8.php");
include_once("../dashboard/common.php");

// CAUTION : do not Turn on output buffering to prevent error on PDF / Word exports
// ob_start();

use CpChart\Data;
use CpChart\Draw;
use CpChart\Image;

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

/**
 * Return max value for aggregated indicators
 * @param $data
 * @return mixed
 *
 */
function get_max_value($data) {

    $maxArray = [];

    foreach ($data as $k => $valA) {

        for ($j = 0; $j < count($valA); $j++) {
            if(!isset($maxArray[$j])) $maxArray[$j] = $valA[$j];
            else $maxArray[$j] += $valA[$j];
        }

    }
    return max($maxArray);

}


function is_threshold_visible($thresholds) {

    foreach ($thresholds as $threshold) {
        if ($threshold != 0.123456789) return true;
    }
    return false;
}
// 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, $display, $width, $height, $workingpath ='') {

	global $sql_object;

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

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

	    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;
	global $lang;

    // weg et indicator
    $req_sdii=SQL_getInfoSdi($id);
    $result_sdii = $sql_object->DBSelect($req_sdii);

	// we get values
    $value = $sql_object->DBSelect(SQL_getAllValue($status, $scale_id, $id, 'ASC'));
    $value = add_cumulative_value($value, $result_sdii[0]); // we add 'sdiv_cumulative_value' attribute if needed

	$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'];
	}

    $scaleMinVal = $scaleMaxVal = 0;
    $months = [];
	$a_labels = [];
	$stacked_data = [];
	$thresholds = [];
    $meandata = []; // used only if $result_sdii[0]['sdii_multiple_type'] == 'mean'

    $missing_values = [];

    // print_r($result_sdii);
    // echo "<hr>";
    //print_r($value);
    // echo "<hr>";

    // we handle unique indicators with cumulative values
    if($result_sdii[0]['sdii_value_type'] == 'unique' &&  $result_sdii[0]['sdii_unique_mode'] == 'cumulative') {

        // IMPORTANT !!! We overwrite $result_sdii[0]['sdii_multiple_type'] with 'none' value because 'sum' will display stacked Chart !
        $result_sdii[0]['sdii_multiple_type'] = 'none';

        $tmpv = $tmpc = [];
        $cumulative_value = 0;
        foreach ($value as $key => $val) {
            $cumulative_value += $val['sdiv_value'];

            array_push($tmpv, $val['sdiv_value']);
            array_push($tmpc, $cumulative_value);

            // we set threshold
            if (!is_null($val['sdiv_threshold'])) {
                array_push($thresholds, $val['sdiv_threshold']);
            } else {
                array_push($thresholds, VOID); // http://wiki.pchart.net/doc.missing.points.html
            }


            // we get dates and format it based on indicator frequency
            list($day, $month, $year) = explode('-', $val['date_p']);
            if ($result_sdii[0]['sdii_frequency'] >= 365) $dateVal = $year;
            elseif ($result_sdii[0]['sdii_frequency'] >= 30) $dateVal = $month. '-'.$year;
            else $dateVal = $day . '-' .$month. '-'. substr($year, 2, 2);
            array_push($months, $dateVal);

            // we identify empty values
            // IMPORTANT keep that test, because 'unique' values indicator with cumulative behavior enter that case !
            if ($result_sdii[0]['sdii_value_type'] == 'unique' && is_null($val['sdiv_value'])) array_push($missing_values, $dateVal);
            if ($result_sdii[0]['sdii_value_type'] == 'multiple') {
                $data = unserialize($val['sdiv_multivalue']);
                if(null_values_only($data)) array_push($missing_values, $dateVal);
            }
        }
        array_push($a_labels, _t('dashboard', 'multivalue_value'), _t('dashboard', 'cumulative_value'));

        $stacked_data[_t('dashboard', 'multivalue_value')] = $tmpv;
        $stacked_data[_t('dashboard', 'cumulative_value')] = $tmpc;
    }


    // we handle multiple indicators
    if($result_sdii[0]['sdii_value_type'] == 'multiple') {

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

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

            // we get dates and format it based on indicator frequency
            list($day, $month, $year) = explode('-', $value[$i]['date_p']);
            if ($result_sdii[0]['sdii_frequency'] >= 365) $dateVal = $year;
            elseif ($result_sdii[0]['sdii_frequency'] >= 30) $dateVal = $month . '-' . $year;
            else $dateVal = $day . '-' . $month . '-' . substr($year, 2, 2);
            $months[$i] = $dateVal;

            // we identify empty values
            if(null_values_only($data)) {
                array_push($missing_values, $dateVal);
            }

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

            // if set, we get it from the table
            if (isset($data[0]['_mean'])) {
                $meandata[$i] = $data[0]['_mean'];
            }


            // if set, we get it from the table
            if (!is_null($value[$i]['sdiv_threshold'])) {
                $thresholds[$i] = $value[$i]['sdiv_threshold'];
            } else {
                $thresholds[$i] = VOID; // http://wiki.pchart.net/doc.missing.points.html
            }

        }


        // 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($stacked_data);

        if ($result_sdii[0]['sdii_multiple_mode'] == 'labels_on_abscissa') {

            $stacked_dataAlt = [];

            $arrMean = [];
            // we iterate on $data to compute mean by labels
            //for($i = 0; $i < count($stacked_data); $i ++) {
            foreach ($stacked_data as $key => $value) {
                array_push($arrMean, array_sum($value) / count($value));
            }


            // we prepare data as wanted
            for ($m = 0; $m < count($months); $m++) {
                // echo $months[$m].'<br>';

                // we define the key as an array is not defined yet
                $stacked_dataAlt[$months[$m]] = array(); // we have to init entry

                foreach ($a_labels as $k => $v) {
                    // echo $months[$m]. ' - '.$stacked_data[$v][$m].'<br>';
                    array_push($stacked_dataAlt[$months[$m]], $stacked_data[$v][$m]);
                }
            }
            // then we changes values to use the same piece of code to generate chart
            $tmp = $a_labels;
            $a_labels = $months;
            $months = $tmp;
            $stacked_data = $stacked_dataAlt;
            $meandata = $arrMean;

        }
    }

    /**
    print_r($result_sdii);
    echo "<hr>";
    echo "<br><br>Labels<br>";
 	print_r($a_labels);
    echo "<br><br>Thresholds<br>";
    print_r($thresholds);
    echo "<br><br>Dates<br>";
 	print_r($months);
    echo "<br><br>";
    echo "<br><br>Meandata<br>";
    print_r($meandata);
    echo "<br><br>Stacked data<br>";
 	print_r($stacked_data);
    echo "<br><br>Stacked data ALT<br>";
    print_r($stacked_dataAlt);
    echo "<br><br>Stacked data var dump<br>";
	var_dump($stacked_data);
    exit;
     * */


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

	// 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]);

	}

	$MyData->setAxisName(0,$unit);
	$MyData->addPoints($months,"Labels");
	$MyData->setSerieDescription("Labels","Months");
	$MyData->setAbscissa("Labels");
	
	
	/* Create the pChart object */
	$myPicture = new Image($width, $height, $MyData);

	/* Set the default font properties */
	$myPicture->setFontProperties(array("FontName"=>"../lib/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, 40, $width - 20, $height - 60);
	//$myPicture->drawScale(array("DrawSubTicks"=>TRUE,"Mode"=>SCALE_MODE_ADDALL_START0));
	/* Draw the scale */



    // we define $scaleMinVal / $scaleMaxVal based on data
    foreach ($stacked_data as $k => $v) {
       $tmpPos = max($v);
       $tmpNeg = min($v);
       if ($tmpNeg < $scaleMinVal) $scaleMinVal = $tmpNeg; // we define the min value to set scale boundaries
       if ($tmpPos > $scaleMaxVal) $scaleMaxVal = $tmpPos; // we define the max value to set scale boundaries
    }
    // if 'sdii_multiple_type'] == 'sum' we overwrite max computation !
    if($result_sdii[0]['sdii_multiple_type'] == 'sum') {
        $tmpPos = get_max_value($stacked_data);
        if ($tmpPos > $scaleMaxVal) $scaleMaxVal = $tmpPos; // we define the max value to set scale boundaries
    }

    if($scaleMinVal < 0) $scaleMinVal = floor($scaleMinVal/10)*10;
    else $scaleMinVal = 0;
    if(count($thresholds) > 0 && max($thresholds) > $scaleMaxVal) $scaleMaxVal = max($thresholds);
    if(count($thresholds) > 0 && min($thresholds) < $scaleMinVal) $scaleMinVal = min($thresholds);

    $AxisBoundaries = array(0=>array("Min"=> $scaleMinVal,"Max"=> ceil($scaleMaxVal * 1.1 /10)*10 ) );

    // finally we override min value if specified in indicator definition
    if(is_numeric($result_sdii[0]['sdii_force_chart_min'])) $AxisBoundaries = array(0=>array("Min"=> cast_number($result_sdii[0]['sdii_force_chart_min']),"Max"=> ceil($scaleMaxVal * 1.1 /10)*10 ) );


    $scaleSettings = array(
        // grid settings
        "GridR" => 180,
        "GridG" => 180,
        "GridB" => 180,
        "GridTicks" => 1,
        "DrawSubTicks" => false, // ne pas afficher les entre ticks
	    "Mode" => SCALE_MODE_MANUAL, // SCALE_MODE_ADDALL // SCALE_MODE_FLOATING does not display all values because is not able to calculate sum values
        "ManualScale" => $AxisBoundaries,
	    // 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);

    $settings = array("Surrounding" => -15, "InnerSurrounding" => 15,
        "Rounded" => false,
        // "Interleave" =>.5,
        "DisplayValues" => true, "DisplayR" => 80, "DisplayG" => 80, "DisplayB" => 80,
    );

    if($result_sdii[0]['sdii_multiple_type'] == 'sum') {
        $myPicture->drawStackedBarChart($settings);
    } else {
        /*
        $MyData = new Data();
        foreach ($stacked_data as $k => $v)  {
            $MyData->addPoints($v,$k);
        }
        */

        if($type == 'column') $myPicture->drawBarChart($settings);
        if($type == 'line') $myPicture->drawSplineChart($settings);
        if($type == 'area') $myPicture->drawAreaChart($settings);
    }

    // print_r($meandata);
    //exit;
    if($result_sdii[0]['sdii_multiple_type'] == 'mean') {
        $MyData->addPoints($meandata,_t('dashboard', 'multivalue_mean'));
        $meanSettings = array("R"=>1,"G"=>1,"B"=>1);
        $MyData->setPalette(_t('dashboard', 'multivalue_mean'), $meanSettings);

        $MyData->setSerieDrawable(_t('dashboard', 'multivalue_mean'),TRUE);
        for ($k=0; $k<count($a_labels); $k++) {
            $MyData->setSerieDrawable($a_labels[$k],FALSE);
        }
        $MyData->setSerieTicks(_t('dashboard', 'multivalue_mean'),3);
        $MyData->setSerieWeight(_t('dashboard', 'multivalue_mean'), 0.2);
        // $MyData->setSerieDrawable($meandata,FALSE);
        $myPicture->drawSplineChart();
        $myPicture->drawPlotChart();
    }

// We display threshold
if(count($thresholds) > 0) {
        $thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
        $MyData->addPoints($thresholds,_t('dashboard', 'threshold_value'));
        $MyData->setPalette(_t('dashboard', 'threshold_value'), $thresholdsSettings);
        // $MyData->setSerieWeight(_t('dashboard', 'threshold_value'), 0.2);
        $MyData->setSerieDrawable(_t('dashboard', 'threshold_value'), TRUE);
        $MyData->setSerieDrawable(_t('dashboard', 'multivalue_mean'), FALSE);
// we loop on labels
        for ($k = 0; $k < count($a_labels); $k++) {
            $MyData->setSerieDrawable($a_labels[$k], FALSE);
        }
    }
	$myPicture->drawSplineChart();
	$myPicture->drawPlotChart();

    /* Make sure all series are drawable before writing the legend */
    $MyData->drawAll();
    if(count($thresholds) == 0 || !is_threshold_visible($thresholds)) $MyData->setSerieDrawable(_t('dashboard', 'threshold_value'), FALSE);
    if($result_sdii[0]['sdii_multiple_type'] != 'mean') $MyData->setSerieDrawable(_t('dashboard', 'multivalue_mean'),FALSE);
	
	/* 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, ""));

    // we display a notice regarding missing values

    if(count($missing_values) > 0) {
        $notice = sprintf(_t('dashboard', 'no_data_notice'), join(', ', $missing_values));
        $myPicture->setFontProperties(array("FontName"=>"../lib/fonts/verdana.ttf"));
        $TextSettings = array("DrawBox"=>false,"R"=>255,"G"=>76,"B"=>76,"Angle"=>0,"FontSize"=>10, "Align" => TEXT_ALIGN_TOPLEFT);
        $myPicture->drawText(55,15,$notice,$TextSettings);
    }
	
	/* 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;

    $missing_values = [];
	
	// 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'];
	}
	
	$thresholds = array();
	
	for ($i=0; $i<count($value); $i++) {
        // if set, we get it from the table
        if(!is_null($value[$i]['sdiv_value'])) {
            $ydata[$i]=(float) $value[$i]['sdiv_value'];
        } else {
            $ydata[$i]=VOID; // if is null we replace by VOID to create discontinuous representation
        }

		// if set, we get it from the table
		if(!is_null($value[$i]['sdiv_threshold'])) {
			$thresholds[$i]=$value[$i]['sdiv_threshold'];
		} else {
		    $thresholds[$i]=VOID; // http://wiki.pchart.net/doc.missing.points.html
		}
	
        list($day, $month, $year) = explode('-', $value[$i]['date_p']);
        if ($result_sdii[0]['sdii_frequency'] >= 365) $dateVal = $year;
        elseif ($result_sdii[0]['sdii_frequency'] >= 30) $dateVal = $month. '-'.$year;
        else $dateVal = $day . '-' .$month. '-'. substr($year, 2, 2);
        $months[$i] = $dateVal;

        // we identify empty values
        // IMPORTANT keep that test, because 'unique' values indicator with cumulative behavior enter that case !
        if (is_null($value[$i]['sdiv_value'])) array_push($missing_values, $dateVal);
	}
	
// 	print_r($thresholds); // debug thresholds
// 	exit;
	
	
	/* Create and populate the pData object */
	$MyData = new Data();
	//  $MyData->loadPalette("../lib/vendor/pChart-php7/palettes/blind.color",TRUE);
	$MyData->setAxisName(0,$unit);
	$MyData->addPoints($ydata,$full_title);
	$MyData->addPoints($thresholds,_t('dashboard', 'threshold_value'));
	$MyData->addPoints($months,"Dates");
	$MyData->setSerieDescription($full_title,$unit);
	$MyData->setAbscissa("Dates");
	
	/* Create the pChart object */
	$myPicture = new Image($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/fonts/verdana.ttf","FontSize"=>8,"R"=>120,"G"=>120,"B"=>120));
	/* Define the chart area */
	$myPicture->setGraphArea(50,40,$width-20,$height-60);

    // we define $scaleMinVal / $scaleMaxVal based on data
    $scaleMinVal = $scaleMaxVal = 0;
    $scaleMaxVal = max($ydata);
    if( min($ydata) < 0) $scaleMinVal = min($ydata);
    if(max($thresholds) > $scaleMaxVal) $scaleMaxVal = max($thresholds);
    if(min($thresholds) < $scaleMinVal) $scaleMinVal = min($thresholds);

    $AxisBoundaries = array(0=>array("Min"=> $scaleMinVal, "Max"=> ceil($scaleMaxVal * 1.1 /10)*10 ) );

    // finally we override min value if specified in indicator definition
    if(is_numeric($result_sdii[0]['sdii_force_chart_min'])) $AxisBoundaries = array(0=>array("Min"=> cast_number($result_sdii[0]['sdii_force_chart_min']), "Max"=> ceil($scaleMaxVal * 1.1 /10)*10 ) );
        
        /* 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_MANUAL, // SCALE_MODE_FLOATING // SCALE_MODE_ADDALL prevent "non-numeric input" error with pChart-php7 see aroune line 2005 in /class/pDraw.class.php
        "ManualScale" => $AxisBoundaries,
        // 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(_t('dashboard', 'threshold_value'),FALSE);
	
			// $thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64); // Hexa : #FE9440
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_tcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$thresholdsSettings = array("R"=>$r,"G"=>$g,"B"=>$b);
			$MyData->setPalette(_t('dashboard', 'threshold_value'),$thresholdsSettings);
// 			$valuesSettings = array("R"=>36,"G"=>47,"B"=>74); // bleu foncé
// 			$valuesSettings = array("R"=>74,"G"=>192,"B"=>242); // bleu clair Hexa : #4AC0F2
			
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_mcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$valuesSettings = array("R"=>$r,"G"=>$g,"B"=>$b);
			
			$MyData->setPalette($full_title,$valuesSettings);
			/**
			 * Do not activate because it creates aliasing
			$MyData->setSerieTicks(_t('dashboard', 'threshold_value'),4);
			$MyData->setSerieWeight(_t('dashboard', 'threshold_value'), 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 */
	

		    $MyData->setSerieDrawable(_t('dashboard', 'threshold_value'),TRUE);

			$MyData->setSerieDrawable($full_title,FALSE);
			$myPicture->drawSplineChart();
			// $myPicture->drawLineChart($settings);
			// $myPicture->drawPlotChart();
	
			break;
		case 'area':
			$MyData->setSerieDrawable($full_title,TRUE);
			$MyData->setSerieDrawable(_t('dashboard', 'threshold_value'),FALSE);
			
// 			$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_tcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$thresholdsSettings = array("R"=>$r,"G"=>$g,"B"=>$b);
			
			$MyData->setPalette(_t('dashboard', 'threshold_value'),$thresholdsSettings);
// 			$valuesSettings = array("R"=>137,"G"=>214,"B"=>244, "Alpha"=>100); // bleu clair
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_mcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$valuesSettings = array("R"=>$r,"G"=>$g,"B"=>$b);
  			$MyData->setPalette($full_title,$valuesSettings);
			
			// il faut utiliser les seuils pour choisir la couleur de remplissage
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_mcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			//$Threshold[0] = array("Min"=>-9999,"Max"=>99999999999,"R"=>$r,"G"=>$g,"B"=>$b,"Alpha"=>80);
			$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 */
	
		    $MyData->setSerieDrawable(_t('dashboard', 'threshold_value'),TRUE);

			$MyData->setSerieDrawable($full_title,FALSE);
			$myPicture->drawSplineChart();
			//$myPicture->drawLineChart();
			$myPicture->drawPlotChart();
	
			break;
		default: // 'column' type
			$MyData->setSerieDrawable($full_title,TRUE);
			$MyData->setSerieDrawable(_t('dashboard', 'threshold_value'),FALSE);
	
// 			$thresholdsSettings = array("R"=>254,"G"=>148,"B"=>64);

			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_tcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$thresholdsSettings = array("R"=>$r,"G"=>$g,"B"=>$b);
			
			$MyData->setPalette(_t('dashboard', 'threshold_value'),$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
			
			list($r, $g, $b) = sscanf($result_sdii[0]['sdii_mcolor'], "#%02x%02x%02x"); // convert hexadecimal to RGB
			$valuesSettings = array("R"=>$r,"G"=>$g,"B"=>$b, "Alpha"=> 90);
			$MyData->setPalette($full_title,$valuesSettings);
	
			$myPicture->drawBarChart($settings);
	
			/* Draw the line and plot chart */
			$myPicture->setShadow(FALSE); /* Turn off shadow computing */
	
			$MyData->setSerieDrawable(_t('dashboard', 'threshold_value'),TRUE);

			$MyData->setSerieDrawable($full_title,FALSE);
			$myPicture->drawSplineChart();
			$myPicture->drawPlotChart();
			break;
	}

    // we display a notice regarding missing values
    if(count($missing_values) > 0) {
        $notice = sprintf(_t('dashboard', 'no_data_notice'), join(', ', $missing_values));
        $myPicture->setFontProperties(array("FontName"=>"../lib/fonts/verdana.ttf"));
        $TextSettings = array("DrawBox"=>false,"R"=>255,"G"=>76,"B"=>76,"Angle"=>0,"FontSize"=>10, "Align" => TEXT_ALIGN_TOPLEFT);
        $myPicture->drawText(55,15,$notice,$TextSettings);
    }

	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;

}

?>