<?php
    ini_set( 'display_errors', 'On' ); 
    error_reporting( E_ALL ); 
    if(isset($_GET['key'])&&$_GET['key']=="brt6k11t"&&$_GET['date_range']!=""){
        require_once('../connect.php');
    
        $conn = new mysqli($host, $user, $pass, $database);
    
        // Ustawienie strefy czasowej na "Europe/Warsaw"
        date_default_timezone_set('Europe/Warsaw');
    
        // Pobieramy aktualną datę i godzinę w formacie "Y-m-d H:i:s"
        $currentDate = $_GET['date_range'];
        // $currentDate = date("Y-m-d");
    
        $sql_all_energy = "SELECT SUM(`total_energy`) as `total_energy_all` FROM `energy`";
        $query_all_energy = mysqli_query($conn, $sql_all_energy);
        $row_all_energy = mysqli_fetch_assoc($query_all_energy);
        $total_energy_all = $row_all_energy['total_energy_all'];
        $sql4 = "SELECT `id`, `date`, `total_energy`, `grid_energy`, `pv_energy`, `battery_energy`,`battery_chg`,`battery_dhg` FROM `energy` WHERE `date` = '{$currentDate}'";
        $query1 = mysqli_query($conn, $sql4);
        if(mysqli_num_rows($query1)>0){
            $row1 = mysqli_fetch_assoc($query1);
            $total_energy = $row1['total_energy'];
            $grid_energy = $row1['grid_energy'];
            $pv_energy = $row1['pv_energy'];
            $battery_chg = $row1['battery_chg'];
            $battery_dhg = $row1['battery_dhg'];
            // if($r217>0){
            //     $battery_energy = $row1['battery_energy']+($r217/3600000);
            // }
            // $total_energy = floatval($row1['total_energy'])+(floatval($r223/1000)/3600);
            $response = array(
                'success' => 'yes',
                'total_energy_all' => round($total_energy_all,4),
                'total_energy' => round($total_energy,4),
                'grid_energy' => round($grid_energy,4),
                'pv_energy' => round($pv_energy,4),
                "battery_chg" => round($battery_chg,4),
                "battery_dhg" => round($battery_dhg,4)
            );
        }else{
            $response = array(
                'success' => 'no',
                'message' => 'Brak danych w wybranym dniu'
            );
        }
        $conn->close();

        // $response = array(
        //     'success' => 'no',
        //     'message' => 'Brak danych w wybranym dniu'
        // );
    
        // echo "ok - Time: $currentTime \n Device status: $device \n Total energy: ".round($total_energy,4)."kWh";
        header('Content-Type: application/json');
        echo json_encode($response);
    }
?>