<?php
    include('../../xcrud/xcrud.php');
    header('Content-Type: text/html; charset=' . Xcrud_config::$mbencoding);
    $db = Xcrud_db::get_instance();
    $table = $_POST['table'];
    if(isset($_POST['start'])){$start = $_POST['start'];} else {$start="";}
    if(isset($_POST['end'])){$end = $_POST['end'];} else {$end="";}
     if($start > "" AND $end >""){
        $whereDatum = "WHERE (datum BETWEEN '".$_POST['start']."' AND '".$_POST['end']."')";
    } else {
        $whereDatum ="";
    }
   // $query = "SELECT SUM(`cost`) AS SUM, maincategorie FROM `ktsgk` ".$whereDatum." GROUP BY maincategorie";
   $query = "SELECT SUM(CASE WHEN cost<0 THEN cost ELSE 0 END) as NegativeTotal,
       SUM(CASE WHEN cost>=0 THEN cost ELSE 0 END) as PostiveTotal,
       maincategorie FROM ".$table." ".$whereDatum." GROUP BY maincategorie";
    $db->query($query);
    $result = $db->result();
    $options="";
     if($result > ""){
        foreach ($result as $key => $item)
        {     
            if ($table == "ktsgk"){
                $loss = $item['PostiveTotal'];
            } else {
                if (isset($item['NegativeTotal'])){
                    $loss=abs($item['NegativeTotal']);
                } else {
                    $loss= 0;
                }
            }
            $json['pie'][] = array(
                "cat" => $item['maincategorie'],
                "loss" => $loss,
              );
              
              if($item['PostiveTotal'] > '0'){
                    $PostiveTotal[$item['maincategorie']] = $item['PostiveTotal'];
                    $PostiveTotal['type'] = 'loss';
                    $json['compare']['graph'][]['labelText']= $item['PostiveTotal'];
                  
              }
            
            if($item['NegativeTotal'] < '0' AND isset($item['NegativeTotal'])){ 
                $win = abs($item['NegativeTotal']);
                $NegativeTotal[$item['maincategorie']] = $win;
                $NegativeTotal['type'] = 'win';
                 $json['compare']['graph'][]['labelText']=$win;
            } else {
                $win = 0;
                 $NegativeTotal[$item['maincategorie']] = '';
                 $NegativeTotal['type'] = 'win';
            }
             $json['compare']['graph'][] = array(
                    "balloonText" => "[[title]], [[category]]<br><span style='font-size:14px;'><b>[[value]]</b> ([[percents]]%)</span>",
                    "fillAlphas" => 0.9,
                    "fontSize" => 11,
                    "lineAlpha" => 0.5,
                    "title" => $item['maincategorie'],
                    "type" => 'column',
                    "valueField" => $item['maincategorie'],
                  );
        }
        $json['compare']['data'] = array($PostiveTotal,$NegativeTotal);
        echo json_encode($json, JSON_UNESCAPED_UNICODE);
    } else {
        echo $query;
    }
?>