<?php
$servername = "localhost";
$dbname = "energy";
$username = "root";
$password = "Stelmat2@22";
// Keep this API Key value to be compatible with the ESP32 code provided in the project page. 
// If you change this value, the ESP32 sketch needs to match

$api_key_value = "tPmAT5Ab3j7F9";

$api_key = $timestamp = $esp_timestamp = $local = $pz_id = $fase = $voltage = $current = $power = $energy = $frequency = $pf = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        
        $esp_timestamp = test_input($_POST["esp_timestamp"]);
        $local = test_input($_POST["local"]);
        $pz_id = test_input($_POST["pz_id"]);        
        $fase = test_input($_POST["fase"]);
        $voltage = test_input($_POST["voltage"]);
        $current = test_input($_POST["current"]);
        $energy = test_input($_POST["energy"]);
        $power = test_input($_POST["power"]);
        $frequency = test_input($_POST["frequency"]);
        $pf = test_input($_POST["pf"]);
                
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        // Ler o ultimo valor acumulado da Fase ( Implementar novo ajuste em 13-03-2025) 
        $sql1 = "SELECT  id, pz_id, fase, energy FROM energy WHERE pz_id = '{$pz_id}' ORDER BY id DESC LIMIT 1";


        if ($result1 = $conn->query($sql1)) {
            while ($row1 = $result1->fetch_assoc()) {
                $row_id1 = $row1["id"];
                $row_pz_id1 = $row1["pz_id"];
                $row_fase1 = $row1["fase"];
                $row_energy1 = $row1["energy"];
            }
            // Se o valor for menor que 0.25 entao ele vai zerar
            if ($row_energy1 > 0.25 ){
                $newEnergy = $energy - $row_energy1;
                if ($newEnergy < 0 ){
                    $newEnergy = 0;
                }
            }else{
                $newEnergy = 0;
            }

        // Verifica se o valor de energia é maior que zero antes de inserir
        if ($energy > 0 && $newEnergy > 0) {
            $sql = "INSERT INTO energy (esp_timestamp, local, pz_id, fase, voltage, current, energy, energy_p, energy_ac, power, frequency, pf ) 
                    VALUES ('" . $esp_timestamp . "','" . $local . "', '" . $pz_id . "', '" . $fase . "', '" . $voltage . "', '" . $current . "', '" . $energy . "', '" . $newEnergy . "', $newEnergy, '" . $power . "', '" . $frequency . "', '" . $pf . "')";

            if ($conn->query($sql) === TRUE) {
                echo nl2br("<< New record created successfully >>\n");
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        } else {
            echo nl2br("Nenhum dado relevante para inserção (valores zerados ou negativos).\n");
        }

        $result1->free();
        }   // Fim Ler ultimo valor
        
        
        // Inserir dados a cada 06 Horas - para fazer a tabela energy_6h
        
        $sql2 = "SELECT  id, timestamp, pz_id, fase, energy FROM energy_6h WHERE pz_id = '{$pz_id}' ORDER BY id DESC LIMIT 1";
        echo nl2br("SQL energy_6h: $sql2 \n");

        if ($result2 = $conn->query($sql2)) {
            while ($row2 = $result2->fetch_assoc()) {
                $row_id2 = $row2["id"];
                $row_tm2 = $row2["timestamp"];
                $row_pz_id2 = $row2["pz_id"];
                $row_fase2 = $row2["fase"];
                $row_energy2 = $row2["energy"];
            }
            
            // Se o valor for menor que 0.50 entao ele vai zerar
            if ($row_energy2 > 0.50 ){
                $newEnergy2 = $energy - $row_energy2;
                echo nl2br("Valor Energy2: $newEnergy2 \n");
                if ($newEnergy2 < 0 ){
                    $newEnergy2 = 0;
                }
            }else{
                $newEnergy2 = 0;
            }

        $result2->free();
        }
    
        // Calculate the current timestamp
        $currentTimestamp = time();
        echo nl2br("Current TimeStamp: $currentTimestamp \n");
        
        // Calculate the time difference in seconds
        $timeDifference = $currentTimestamp - strtotime($row_tm2);
        echo nl2br("Time Difference: $timeDifference \n");
        
        // Check if the time difference is more than 6 hours (6 hours * 3600 seconds)
        if ($timeDifference > 6 * 3600) {       // fazer a cada 6 Horas 

            // Perform the insertion into the datacenter_6h table here
            echo nl2br("Last Timestamp: $row_tm2 \n");
            
            $sqlInsert = "INSERT INTO energy_6h (esp_timestamp, local, pz_id, fase, voltage, current, energy, energy_p, energy_ac, power, frequency, pf ) 
            VALUES ('" . $esp_timestamp . "','" . $local . "', '" . $pz_id . "', '" . $fase . "', '" . $voltage . "', '" . $current . "', '" . $energy . "', '" . $newEnergy2 . "', $newEnergy2, '" . $power . "', '" . $frequency . "', '" . $pf . "')";
            echo nl2br("SQL Insert: $sqlInsert \n");
            
            if ($conn->query($sqlInsert) === TRUE) {
                // Insertion was successful
                echo nl2br("Last TimeStamp: $row_tm2 \n");
                echo nl2br("Esp_TimeStamp: $esp_timestamp \n");
                echo nl2br("Local: $local \n");
                echo nl2br("fase: $pz_id \n");
                echo nl2br("fase: $fase \n");
                echo nl2br("Voltage: $voltage \n");
                echo nl2br("Current: $current \n");
                echo nl2br("Energy: $energy \n");
                echo nl2br("EngeryP: $energy_p \n");
                echo nl2br("Frequency: $frequency \n");
                echo nl2br("pf: $pf \n");
                echo "New record inserted into datacenter_6h.";
            } else {
                // Insertion failed
                echo "Error inserting record into datacenter_6h: " . $conn->error;
            }
        }        
        
        // fim da nova tabela teste 
        // Fim Teste 06 horas 
        
        
        $sql = "INSERT INTO energy (esp_timestamp, local, pz_id, fase, voltage, current, energy, energy_p, energy_ac, power, frequency, pf ) 
        VALUES ('" . $esp_timestamp . "','" . $local . "', '" . $pz_id . "', '" . $fase . "', '" . $voltage . "', '" . $current . "', '" . $energy . "', '" . $newEnergy . "', $newEnergy, '" . $power . "', '" . $frequency . "', '" . $pf . "')";
        
        
        if ($conn->query($sql) === TRUE) {
            echo nl2br("Esp_TimeStamp: $esp_timestamp \n");
            echo nl2br("Local: $local \n");
            echo nl2br("fase: $pz_id \n");
            echo nl2br("fase: $fase \n");
            echo nl2br("Voltage: $voltage \n");
            echo nl2br("Current: $current \n");
            echo nl2br("Energy: $energy \n");
            echo nl2br("EngeryP: $energy_p \n");
            echo nl2br("Frequency: $frequency \n");
            echo nl2br("pf: $pf \n");
            echo nl2br("<< New record created successfully >>\n");
            echo "New record created successfully";
        } 
        else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
    
        $conn->close();
        echo nl2br("Conexão encerrada com sucesso !\n");
        echo nl2br("Close connection ... sucess \n");
        echo "<< WGirardi Ti 2022 - wgirardi.com - @wgirardi >> \n";

    }
    else {
        echo nl2br("User not recognize ... fail \n");
        echo nl2br ("Wrong API Key provided. \n");

    }

}
else {
        echo nl2br("No data posted with HTTP POST \n");
        echo "<< WGirardi Ti 2022 - wgirardi.com - @wgirardi >> \n";
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>
