<?php

/**
 * Dashboard module
 * 
 * The function prepare data to generate JS charts
 * 
 * @package linea21\modules\dashboard
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

/**
 * 
 * @param array $indicator // indicator info
 * @param array $obj //  parameters
 * @param array $values // array of values
 * @return array|string
 */
function prepare_chart_data($indicator, $obj, $values)
{
    
    // we check if defined colors are set for given indicator in public theme
    if(file_exists(THEME_PUBLIC_PATH.'indicators-colors.php')) include_once(THEME_PUBLIC_PATH.'indicators-colors.php');
    
    if(empty($values)) return true;

    $obj['indicator-missing-values'] = [];
    
    foreach ($values as $rec) {
        // echo print_r($rec);
        // echo "<hr>";
        // we get dates and format it based on indicator frequency
        list($day, $month, $year) = explode('-', $rec['date_p']);
        if($obj['indicator-frequency'] >= 365 ) $dateVal = $year;
        elseif($obj['indicator-frequency'] >= 30 ) $dateVal = $month. '-'.$year;
        else $dateVal = $day . '-' .$month. '-'. substr($year, 2, 2);

        array_push($obj['dates'], $dateVal);
        array_push($obj['data'], $rec['sdiv_value']);
        array_push($obj['thresholds'], $rec['sdiv_threshold']);

        // we identify empty values
        if ($indicator[0]['sdii_value_type'] == 'unique' && is_null($rec['sdiv_value'])) array_push($obj['indicator-missing-values'], $dateVal);
        if ($indicator[0]['sdii_value_type'] == 'multiple') {
            $data = unserialize($rec['sdiv_multivalue']);
            if(null_values_only($data)) array_push($obj['indicator-missing-values'], $dateVal);
        }

    }
    $obj['indicator-missing-values'] =  array_reverse($obj['indicator-missing-values']);

    // if indicator is multiple, we get the given year
    if ($indicator[0]['sdii_value_type'] == 'multiple') {

        // pie chart only - year parameter mandatory !
        if (($obj['indicator-wanted-vis'] == 'pie' || $obj['indicator-wanted-vis'] == 'treemap') && is_null($obj['indicator-wanted-year'])) die('year parameter should be passed for donut / pie charts.');

        // 1 - pie chart only - year parameter mandatory !
        if ($obj['indicator-wanted-vis'] == 'pie') {

            $arr = [];
            $colors = [];

            for ($i = 0; $i < count($values); $i ++) {

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

                if ($obj['indicator-wanted-year'] == substr(formatDate($values[$i]['date_p'], true), 0, 4)) {
                    foreach ($data as &$val) {
                        $chartvalues = array(
                            formatText($val['label'], '2HTML'),
                            $val['value']
                        );
                        if(isset($val['color'])) array_push($colors, $val['color']);
                        array_push($arr, $chartvalues);
                    }
                }
            }

            $obj['data'] = $arr;
            if(!empty($colors)) $obj['indicator-colors'] = json_encode($colors); // we set colors key if not empty
        }

        // 1 - treemap chart only - year parameter mandatory !
        elseif ($obj['indicator-wanted-vis'] == 'treemap') {

            // do not pass leading '#' character in URL
            // do not pass color as 'orange', 'blue', only hexadecimal !
            isset($_GET['color1']) ? $obj['color1'] = '#' . $_GET['color1'] : $obj['color1'] = '#E6CFF7';
            isset($_GET['color2']) ? $obj['color2'] = '#' . $_GET['color2'] : $obj['color2'] = '#BB93D8';

            $arr = [];

            for ($i = 0; $i < count($values); $i ++) {

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

                if ($obj['indicator-wanted-year'] == substr(formatDate($values[$i]['date_p'], true), 0, 4)) {

                    // we sort array before display
                    usort($data, function ($a, $b) {
                        return $a['value'] - $b['value'];
                    });
                    $cnt = 1;

                    foreach ($data as &$val) {

                        $item = [];
                        $item["name"] = formatText($val['label'], '2HTML');
                        $item["value"] = $val['value'];
                        $item["colorValue"] = $cnt;
                        array_push($arr, $item);
                        $cnt ++;
                    }
                }
            }

            $obj['data'] = json_encode($arr, JSON_NUMERIC_CHECK);
            // print_r($obj);
        }

        // stacked column charts - we prepare default view with may values (several years)
        else {

            $arr = []; // for multiple only
            $labels = []; // for multiple only
            $colors = []; // for multiple only
            $arrMean =  []; // for multiple only


            for ($i = 0; $i < count($values); $i++) {

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

                // print_r($data);
                array_push($arrMean, $data[0]['_mean']);

                // first loop to get all labels and colors if set
                foreach ($data as &$val) {
                    if (! in_array(formatText($val['label'], '2HTML'), $labels)) {

                        array_push($labels, formatText($val['label'], '2HTML'));

                    }
                    if (isset($val['color'])) array_push($colors, $val['color']);

                }
            }
            // print_r($labels);

            // second loop on labels
            for ($t = 0; $t < count($labels); $t ++) {
                $label_values = [];

                for ($i = 0; $i < count($values); $i ++) {

                    $flag = 0; // Important flag not found value = 0
                    $data = unserialize($values[$i]['sdiv_multivalue']);



                    // first loop to get all labels
                    foreach ($data as &$val) {
                        if (formatText($val['label'], '2HTML') == $labels[$t]) {
                            array_push($label_values, $val['value']);
                            $flag = 1;
                        }
                    }

                    if ($flag == 0)
                        array_push($label_values, null); // Important flag not found value = 0
                }

                $item = [];
                $item["name"] = $labels[$t];
                $item["data"] = array_reverse($label_values);
                array_push($arr, $item);
            }

            $obj['data'] = json_encode($arr, JSON_NUMERIC_CHECK);
            $obj['data-mean'] = $arrMean;
            if(!empty($colors)) $obj['indicator-colors'] = json_encode($colors); // we set colors key if not empty
            // print_r($obj['data']);
        }

        // print_r($obj);
        // exit;

        // if 'labels_on_abscissa'
        if($obj['indicator-multiple-mode'] == 'labels_on_abscissa') {

            $dataAlt = [];


            // echo '<hr>';
            // print_r(json_decode($obj['data'], true) );
            $obj['dates'] = array_reverse($obj['dates']); // we have to reverse dates
            $data = array_reverse(json_decode($obj['data'], true));

            //  [data] => [{"name":"janvier","data":[25,18,41]},{"name":"f\u00e9vrier","data":[14,25,85]},{"name":"mars","data":[35,42,21]},{"name":"avril","data":[47,35,11]},{"name":"mai","data":[12,63,66]},{"name":"juin","data":[8,14,25]}]

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

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

                $tmpa = [];
                foreach($labels as $k => $v) {
                    // echo($v). '<br>';

                    foreach ($data as $el) {
                        // echo $el['name'].'<br>';
                        // if($el['name'] == $v) array_push($dataAlt[$obj['dates'][$m]], $el['data'][$m]);

                        if($el['name'] == $v) {
                            array_push($tmpa, $el['data'][$m]);
                        }
                    }
                }
                //list($day, $month, $year)=explode('-',$obj['dates'][$m]);
                //$d_date = $year ; // $day . '-' .$month. '-'. substr($year, 0, 2);
                //array_push($dataAlt, array('name' => $d_date, 'data' => $tmpa));
                array_push($dataAlt, array('name' => $obj['dates'][$m], 'data' => $tmpa));

            }
            $obj['data'] = json_encode($dataAlt, JSON_NUMERIC_CHECK);
            $obj['dates'] = array_reverse($labels); // we set categories
            $obj['data-mean'] = $arrMean;

            /**
            echo '<hr>';
            print_r($obj);
            echo '<hr>';
             * */
        }

    } // we close indicator 'multiple' test

    // if indicator is unique but cumulative, we switch to multiple view and prepare data
    if($indicator[0]['sdii_value_type'] == 'unique' && $indicator[0]['sdii_unique_mode'] == 'cumulative') {

        $obj['data'] = array_reverse($obj['data']);
        // we overwrite indicator value
        $obj['indicator-type'] = 'multiple';
        $obj['indicator-multiple-mode'] = 'normal';
        $obj['indicator-multiple-type'] = 'none';

        $tmpa = $tmpv = $tmpc = [];
        $cumulative_value = 0;
        foreach ($obj['data'] as $key => $val) {
            $cumulative_value += $val;
            array_push($tmpv, $val);
            array_push($tmpc, $cumulative_value);
        }
        array_push($tmpa, array('name' => mb_ucfirst(_t('dashboard','multivalue_value')), 'data' => $tmpv), array('name' => mb_ucfirst(_t('dashboard','cumulative_value')), 'data' => $tmpc));
        $obj['data'] = json_encode($tmpa, JSON_NUMERIC_CHECK);
    }


    return $obj;
}