<?php

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

$consEstQuery = "SELECT
  UNIX_TIMESTAMP(DATE_ADD(datetime, INTERVAL 28 DAY)) AS 'time',
  SUM(-(totalConsumption + heaterPwr)/48) AS 'Vorraussichtl. Verbrauch'
FROM EnergyFlow
WHERE
  DATE(datetime) >= DATE(DATE_SUB(NOW(),INTERVAL 28 DAY)) And DATE(datetime) != DATE(NOW())
  GROUP BY WEEKDAY(datetime)
ORDER BY datetime";

$prodEstQuery = "SELECT UNIX_TIMESTAMP(CONVERT_TZ(period_End,'GMT','Europe/Berlin')) AS 'time', 
    SUM(power*500) AS 'Vorhersage' 
    FROM simPower 
    WHERE DATE(CONVERT_TZ(period_End,'GMT','Europe/Berlin')) >= DATE(DATE_SUB(NOW(),INTERVAL 7 DAY)) 
    GROUP BY DAY(CONVERT_TZ(period_End,'GMT','Europe/Berlin')) 
    ORDER BY period_End;";

$prodRealQuery = "SELECT
  UNIX_TIMESTAMP(datetime) AS 'time',
  SUM(pvP/12)  AS 'Tatsächliche Erzeugung',
  SUM(-totalConsumption/12) AS 'Tatsächlicher Verbrauch'
FROM EnergyFlow
WHERE
  DATE(datetime) >= DATE(DATE_SUB(NOW(),INTERVAL 7 DAY))
  GROUP BY DAY(datetime)
ORDER BY datetime";


$linecolors["Tatsächliche Erzeugung"] = "#cccc00";
$linecolors["Tatsächlicher Verbrauch"] = "#EE9900";
$linecolors["Vorraussichtl. Verbrauch"] = "#BB4400";
$linecolors["Auto UG"] = "#00aaFF";
$linecolors["Auto OG"] = "#0044FF";
$linecolors["Heizstab"] = "#FF0000";
$linecolors["Batterieladung"] = "#00aa00";
$linecolors["Einspeisung"] = "#b0b0b0";
$linecolors["Ladestand"] = "#00aa00";
$linecolors["Vorhersage"] = "#4444FF";



if (checkLogin()) {
    $mysql_server = "localhost:3310";
    $mysql_user = "solarLog";
    $mysql_pass = "iZ6_ZVul0!vE2.qJ0QSc";
    $mysql_db = "solarLog";
    $mysql = new mysqli($mysql_server, $mysql_user, $mysql_pass, $mysql_db);
    $consEst = mysqli_query($mysql, $consEstQuery);
    $prodEst = mysqli_query($mysql,$prodEstQuery);
    $prodReal = mysqli_query($mysql,$prodRealQuery);
    if(!$consEst){
        echo "Error:<br>".mysqli_error($mysql)."<br />";
    }
    if(!$prodEst){
        echo "Error:<br>".mysqli_error($mysql)."<br />";
    }
    if(!$prodRealQuery){
        echo "Error:<br>".mysqli_error($mysql)."<br />";
    }

    $obj = (object)[]; // Cast empty array to object
    $obj->labels = [];
    $obj->datasets = [];
    $i = 0;
    $filled = 0;

    if($consEst->num_rows > 1){
        $row = $consEst->fetch_assoc();
        foreach ($row as $name => $value) {
            $dataset = (object)[];
            if ($name != "time") {
                $dataset->borderColor = $linecolors[$name];
                $dataset->backgroundColor = $linecolors[$name]."66";
                $dataset->borderWidth=1;
                $dataset->pointRadius= 0;
                $dataset->pointHoverRadius= 5;
                $dataset->tension=0.2;
                $dataset->stack = $name;
                //$dataset->fill = "none";
                $dataset->yAxisID = 'y';
                $dataset->label = $name;
                for($i=0;$i<7;$i++){
                    $dataset->data[] = NULL;
                }
                $dataset->data[] = $value;
                $obj->datasets[] = clone $dataset;
            } 
        }
        while ($row = $consEst->fetch_assoc()) {
            $ii = 0;
            foreach ($row as $name => $value) {
                if ($name != "time") {
                    $obj->datasets[$ii]->data[] = $value;
                    $ii++;
                } 
            }
        }
    }

    if ($prodEst->num_rows > 1) {
        $row = $prodEst->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;
                $dataset->stack = $name;
                //$dataset->fill = "none";
                $dataset->yAxisID = 'y';
                $dataset->label = $name;
                $dataset->data[] = $value;
                $obj->datasets[] = clone $dataset;
            } else {
                $obj->labels[] = $value * 1000;
            }
        }
        while ($row = $prodEst->fetch_assoc()) {
            $ii = 1;
            foreach ($row as $name => $value) {
                if ($name != "time") {
                    $obj->datasets[$ii]->data[] = $value;
                    $ii++;
                } else {
                    $obj->labels[] = $value * 1000;
                }
            }
        }
    }

    if($prodReal->num_rows > 1){
        $row = $prodReal->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;
                $dataset->stack = $name;
                //$dataset->fill = "none";
                $dataset->yAxisID = 'y';
                $dataset->label = $name;
                $dataset->data[] = $value;
                $obj->datasets[] = clone $dataset;
            } 
        }
        while ($row = $prodReal->fetch_assoc()) {
            $ii = 2;
            foreach ($row as $name => $value) {
                if ($name != "time") {
                    $obj->datasets[$ii]->data[] = $value;
                    $ii++;
                } 
            }
        }
    }
    

  

}


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