<?php
$servername = "elegantwork.co.za";
$username = "elegaysv_Code2";
$password = "EWG2Cod!@#";
$dbname = "elegaysv_water_sysie_str";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
// UPDATE QUERIES
if(isset($_POST['submit'])){
  $conn->query('UPDATE `actions` SET `threshold` = ' . $_POST['threshold'] . ' WHERE `unit_id` = 1');
}





// SELECT QUERIES
$total_count = $conn->query('SELECT * FROM `water` WHERE unit_id = 1');
$total = 0;
while($row = $total_count->fetch_assoc()){
  $total += $row['count'];
}
if (isset($_POST["date_time_start"]) && isset($_POST["date_time_end"])) {

  $results = $conn->query("SELECT * FROM water WHERE date_time BETWEEN '{$_POST['date_time_start']}' AND '{$_POST['date_time_end']}'");
  $start_date = $_POST['date_time_start'];
  $end_date = $_POST['date_time_end'];

} else {
  $date_of_24_hours_ago = date("Y-m-d H:i:s", strtotime("-1435 minutes"));
  $results = $conn->query("SELECT * FROM water WHERE date_time >= '$date_of_24_hours_ago'");
  $start_date = '';
  $end_date = '';
}

$action_res = $conn->query("SELECT * FROM `actions` WHERE unit_id = 1");
$action = $action_res->fetch_assoc();



?>


<html>

<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', { 'packages': ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['DateTime', 'Literes'],
        <?php
        if ($results->num_rows > 0) {
          // output data of each row
          while ($row = $results->fetch_assoc()) {
            echo "['" . str_replace("2024-", "", $row['date_time']) . "'," . (($row['count'] * 2.2) / 1000) . "],";
          }
        }
        ?>
      ]);

      var options = {
        title: 'Literes recorded in the last 24 hours',
        legend: { position: 'none' },
        hAxis: { title: 'Date', titleTextStyle: { color: '#333' } },
        vAxis: { title: 'Literes', titleTextStyle: { color: '#333' } }
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  </script>
</head>

<body>
  <div style="padding: 20px; border: 1px solid #ccc; border-radius: 5px; width: 50%; margin: auto;">
    <h3>Search by date</h3>
    <form action="" method="POST"
      style="display: flex;flex-direction: row;align-items: center;align-content: space-around;justify-content: space-evenly;">
      <label for="date_time_start">Start date</label>
      <input type="datetime-local" required name="date_time_start" style="margin-bottom: 10px;"
        value="<?php echo $start_date; ?>">
      <label for="date_time_end">End date</label>
      <input type="datetime-local" required name="date_time_end" style="margin-bottom: 10px;"
        value="<?php echo $end_date; ?>">
      <input type="submit" name="submit" value="Submit"
        style="background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
    </form>
  </div>
  <div id="chart_div" style="width: 100%; height: 500px;"></div>


  <form action="" method="POST" style="display: flex;flex-direction: row;align-items: center;align-content: space-around;justify-content: space-evenly;margin-top: 20px;">
    <label for="threshold" style="margin-right: 10px;">Threshold</label>
    <input type="number" name="threshold" style="margin-right: 10px;" value="<?php echo $action['threshold']; ?>"/>
    <label for="count" style="margin-right: 10px;">Count</label>
    <input type="number" name="count" value="<?php echo $total; ?>" style="margin-right: 10px;" />
    <input type="submit" name="submit" value="save" style="background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;"/>
  </form>

  <script>
    // refresh
    setInterval(() => {
      location.reload();
    }, 10000);
  </script>