<?php

$servername = "localhost";

$dbname = "power_meter";

$username = "admin";

$password = "raspberry";

$api_key_value = "tPmAT5Ab3j7F9";

$api_key= $sensor = $value1 = $value2 = $value3 = $value4 = $loadSend = $relay = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $sensor = $_POST["sensor"];
        $value1 = $_POST["value1"];
        $value2 = $_POST["value2"];
        $value3 = $_POST["value3"];
        $value4 = $_POST["value4"];
        $loadSend = $_POST["loadSend"];
        $relay = $_POST["relay"];
        
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 
        
        $sql4 = "SELECT value4 FROM PowerData ORDER BY id DESC LIMIT 1";

         $result1 = $conn->query($sql4);

             while($row = mysqli_fetch_array($result1)) {
                $value4 += $row['value4'];
             }

        $sql = "INSERT INTO PowerData (sensor, value1, value2, value3, value4)
        VALUES ('" . $sensor . "', '" . $value1 . "', '" . $value2 . "', '" . $value3 . "', '" . $value4 . "')";

        if ($conn->query($sql) === TRUE) {
            //echo "New record created successfully";
        } 
            
        if ($loadSend == "1")
        {
            $sql3 = "INSERT INTO RelayControll (relay)
            VALUES ('" . $relay . "')";
            if ($conn->query($sql3) === TRUE) {
                //echo "New record created successfully";
            }
        }
    
         $sql2 = "SELECT relay FROM RelayControll ORDER BY id DESC LIMIT 1";

         $result = $conn->query($sql2);

             while($row = mysqli_fetch_array($result)) {
             echo "$" . $row['relay'];
             //echo "<br>"; 
             }
             
        $conn->close();
    }
}

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