<?php

require_once("../helper.php");

$waterQuery = "SELECT UNIX_TIMESTAMP(datetime) AS time, rate AS 'Wasserverbrauch' 
FROM solarLog.wasser 
WHERE wasser.datetime BETWEEN DATE_SUB(NOW(),INTERVAL 24 HOUR) and NOW()
ORDER BY wasser.datetime";

$linecolors["Speicher oben"] = "#FF5500";
$linecolors["Speicher mitte"] = "#FFaa00";
$linecolors["Speicher unten"] = "#FFFF00";
$linecolors["Therme Vorlauf Fußboden"] = "#bb0000";
$linecolors["Therme Rücklauf"] = "#ee0000";
$linecolors["Heizstab Vorlauf"] = "#9900bb";
$linecolors["Heizstab Rücklauf"] = "#8800aa";
$linecolors["Fußboden Vorlauf"] = "#00FF00";
$linecolors["Fußboden Rücklauf"] = "#00aa00";
$linecolors["Wasserverbrauch"] = "#2222FF";



if (checkLogin()) {
    $mysql = new mysqli($mysql_server, $mysql_solarUser, $mysql_solarPass, $mysql_solarDB);
    $waterRes = mysqli_query($mysql,$waterQuery);
    if(!$waterRes){
        echo "Error:<br>".mysqli_error($mysql)."<br />";
    }
    $obj = (object)[]; // Cast empty array to object
    $obj->labels = [];
    $obj->datasets = [];
    $i = 0;
    $filled = 0;
    if ($waterRes->num_rows > 1) {
        $dataset = (object)[];
        $row = $waterRes->fetch_assoc();
        $dataset->borderColor = $linecolors["Wasserverbrauch"];
        $dataset->backgroundColor = $linecolors["Wasserverbrauch"]."00";
        $dataset->borderWidth=2;
        $dataset->pointRadius= 0;
        $dataset->pointHoverRadius= 5;
        $dataset->tension=0.2;
        $dataset->fill = "none";
        $dataset->yAxisID = 'y1';
        $dataset->label = "Wasserverbrauch";
        $pt = (object)[];
        $pt->x = $row["time"]*1000;
        $pt->y = $row["Wasserverbrauch"];
        $dataset->data[] = clone $pt;
        while ($row = $waterRes->fetch_assoc()) {
            $pt = (object)[];
            $pt->x = $row["time"]*1000;
            $pt->y = $row["Wasserverbrauch"];
            $dataset->data[] = clone $pt;
        }
        $obj->datasets[] = clone $dataset;
    }
  

}


//header('Content-Type: application/json');
echo json_encode($obj);
//echo '{"labels":[1761322682000,1761322782000,1761322882000,1761322982000,1761323082000,1761323182000,1761323282000],"datasets":[{"stack": "Stack 0","cubicInterpolationMode":"monotone","fill":"origin","label":"Acquisitions by year","data":[10,20,50,20,10,5,70]},{"fill": "false","stack": "Stack 1","cubicInterpolationMode": "monotone","label": "Acquisitions by year","data": [10,20,50,20,10,5,70]}]}';
