<?php

require_once("../helper.php");
if(!isset($_GET["TO"])){
    $_GET["TO"] = 12;
}
$_GET["TO"] = intval($_GET["TO"]);
if(!isset($_GET["FROM"])){
    $_GET["FROM"] = -24;
}
$_GET["FROM"] = intval($_GET["FROM"]);
//-totalConsumption-PL1_EV*1000-PL2_EV*1000-PL3_EV*1000-PL1_EVog*1000-PL2_EVog*1000-PL3_EVog*1000+PL1_OG+PL2_OG+PL3_OG-heaterPwr AS 'UG',
$consQuery = "SELECT
UNIX_TIMESTAMP(EnergyFlow.datetime) AS time, 
pvP AS 'Solarleistung',
soc AS Ladestand,
-totalConsumption-PL1_EV*1000-PL2_EV*1000-PL3_EV*1000-PL1_EVog*1000-PL2_EVog*1000-PL3_EVog*1000+PL1_OG+PL2_OG+PL3_OG-heaterPwr-PL1_UG-PL2_UG-PL3_UG-PL1_EG-PL2_EG-PL3_EG AS 'Gemein',
(PL1_UG+PL2_UG+PL3_UG) AS 'UG',
(PL1_EG+PL2_EG+PL3_EG) AS 'EG',
-(PL1_OG+PL2_OG+PL3_OG) AS 'OG',
(PL1_EV+PL2_EV+PL3_EV)*1000 AS 'Auto UG',
(PL1_EVog+PL2_EVog+PL3_EVog)*1000 AS 'Auto OG',
heaterPwr AS 'Heizstab',
IF(battP<0, -battP, 0) AS Batterieladung,
gridPfeed AS Einspeisung
FROM solarLog.EnergyFlow 
WHERE EnergyFlow.datetime BETWEEN DATE_ADD(NOW(),INTERVAL ".($_GET["FROM"])." HOUR) and DATE_ADD(NOW(),INTERVAL ".$_GET["TO"]." HOUR) 
ORDER BY EnergyFlow.datetime";
$simQuery = "SELECT
UNIX_TIMESTAMP(simPower.period_end) AS time, 
power*1000 AS 'Vorhersage'
FROM solarLog.simPower
WHERE simPower.period_end BETWEEN DATE_ADD(NOW(),INTERVAL ".($_GET["FROM"])." HOUR) and DATE_ADD(NOW(),INTERVAL ".$_GET["TO"]." HOUR) 
ORDER BY simPower.period_end";
$linecolors["Solarleistung"] = "#FFFF00";
$linecolors["Gemein"] = "#FF9900";
$linecolors["UG"] = "#FF8800";
$linecolors["EG"] = "#FF6600";
$linecolors["OG"] = "#FF4400";
$linecolors["Auto UG"] = "#00aaFF";
$linecolors["Auto OG"] = "#0044FF";
$linecolors["Heizstab"] = "#FF0000";
$linecolors["Batterieladung"] = "#00aa00";
$linecolors["Einspeisung"] = "#b0b0b0";
$linecolors["Ladestand"] = "#00aa00";
$linecolors["Vorhersage"] = "#2222FF";



if (checkLogin()) {
    $mysql = new mysqli($mysql_server, $mysql_solarUser, $mysql_solarPass, $mysql_solarDB);
    $result = mysqli_query($mysql, $consQuery);
    $simRes = mysqli_query($mysql,$simQuery);
    if(!$result){
        echo "Error:<br>".mysqli_error($mysql)."<br />";
    }
    $obj = (object)[]; // Cast empty array to object
    $obj->labels = [];
    $obj->datasets = [];
    $i = 0;
    $filled = 0;
    if ($simRes->num_rows > 1) {
        $dataset = (object)[];
        $row1 = $simRes->fetch_assoc();
        $dataset->borderColor = $linecolors["Vorhersage"];
        $dataset->backgroundColor = $linecolors["Vorhersage"]."55";
        $dataset->borderWidth=1.5;
        $dataset->pointRadius= 0;
        $dataset->pointHoverRadius= 5;
        $dataset->tension=0.2;
        $dataset->stack = "sim";
        $dataset->fill = "none";
        $dataset->yAxisID = 'y';
        $dataset->label = "Vorhersage";
        /*$pt = (object)[];
        $pt->x = $row1["time"]*1000;
        $pt->y = $row1["Vorhersage"];
        $dataset->data[] = clone $pt;
        while ($row1 = $simRes->fetch_assoc()) {
            $pt = (object)[];
            $pt->x = $row1["time"]*1000 + 30*60*1000;
            $pt->y = $row1["Vorhersage"];
            $dataset->data[] = clone $pt;
        }*/
        $obj->datasets[] = clone $dataset;
        $rownext = $simRes->fetch_assoc();
        $nextSimTimestamp = $rownext["time"]*1000 + 30*60*1000;
    }
    if ($result->num_rows > 1) {
        $ii = 1;
        $row = $result->fetch_assoc();
        foreach ($row as $name => $value) {
            $dataset = (object)[];
            if ($name != "time") {
                $dataset->borderColor = $linecolors[$name];
                $dataset->backgroundColor = $linecolors[$name]."55";
                $dataset->borderWidth=1;
                $dataset->pointRadius= 0;
                $dataset->pointHoverRadius= 5;
                $dataset->tension=0.2;
                if ($name == "Solarleistung") {
                    $dataset->stack = "SolarPwr";
                    $dataset->fill = "none";
                    $dataset->yAxisID = 'y';
                } else if ($name == "Ladestand") {
                    $dataset->stack = "Charge";
                    $dataset->fill = "none";
                    $dataset->yAxisID = 'y1';
                } else {
                    $dataset->stack = "Consumers";
                    if ($filled == 0) {
                        $filled = 1;
                        $dataset->fill = "origin";
                    } else {
                        $dataset->fill = "-1";
                    }
                    $dataset->yAxisID = 'y';
                }
                $dataset->label = $name;

                $dataset->data[] = $value;
                $obj->datasets[] = clone $dataset;
                $ii++;
            } else {
                $obj->labels[] = $value * 1000;
            }
        }
        while ($row = $result->fetch_assoc()) {
            $ii = 1;
            foreach ($row as $name => $value) {
                if ($name != "time") {
                    $obj->datasets[$ii]->data[] = $value;
                    $ii++;
                } else {
                    if(($value * 1000) < $nextSimTimestamp){
                        $obj->datasets[0]->data[] = $row1["Vorhersage"];
                    }else{
                        $row1 = $rownext;
                        $rownext = $simRes->fetch_assoc();
                        $nextSimTimestamp = $rownext["time"]*1000 + 30*60*1000;
                        $obj->datasets[0]->data[] = $row1["Vorhersage"];
                    }
                    $obj->labels[] = $value * 1000;
                }
            }
        }
    }
    $obj->labels[] = $nextSimTimestamp; //Draw future forecast
    $obj->datasets[0]->data[] = $rownext["Vorhersage"];
    while($rownext = $simRes->fetch_assoc()){
        $obj->labels[] = $rownext["time"]*1000 + 30*60*1000;
        $obj->datasets[0]->data[] = $rownext["Vorhersage"];
    }
  

}


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