<?php
// Start or resume the session
session_start();

/*
Used to enhance security by preventing browsers and proxies from caching pages.
When a user logs out of a web application, you wouldn't want the next person using the same device to simply press the back button in the browser
and access the previous user's session or sensitive information.
This is particularly important in scenarios like shared devices, where multiple users might use the same browser sequentially.
However, it's noted that this method does not work for iOS users, which is be due to iOS's handling of cache control headers and
its aggressive caching strategies to improve user experience and performance.
*/
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

// We verify that the user is logged in, if not we redirect the user to index.php the log in page.
if (!isset($_SESSION['username'])) {
  header("Location: index.php");
  exit;
}
?>

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>LeanC IOT | MES</title>
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css'>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css'>
  <link rel="stylesheet" href="./style.css">
    <!-- If you plan to use this page to animate a dashboard for your workshop, I suggest refreshing this page every minute (at the same rate as the database updates from your sensors). -->
  <meta http-equiv="refresh" content="60">
</head>
<body>
  <!-- NAV -->
  <nav class="navbar navbar-expand-custom navbar-mainbg">
    <a class="navbar-brand navbar-logo" href="dashboard.php">LeanC IOT | MES</a>
    <button class="navbar-toggler" type="button" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <i class="fas fa-bars text-white"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <div class="hori-selector"><div class="left"></div><div class="right"></div></div>

        <li class="nav-item active">
          <a class="nav-link" href="dashboard.php"><i class="fas fa-tachometer-alt"></i>Dashboard</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="monitoring.php"><i class="far fa-chart-bar"></i>Monitoring</a>
        </li>
        <!-- We check if the user's level is equal to "Admin". -->
        <?php if ($_SESSION['level'] == 'Admin') : ?>
          <li class="nav-item">
            <a class="nav-link" href="admin.php"><i class="fas fa-sign-out-alt"></i>Administration</a>
          </li>
        <?php endif; ?>
        <li class="nav-item">
          <a class="nav-link" href="logout.php"><i class="fas fa-sign-out-alt"></i>Log Out (<?php echo htmlspecialchars($_SESSION['username']); ?>)</a>
        </li>

      </ul>
    </div>
  </nav>
  <!-- NAV -->
  <div class="wrapper">
    <?php
    // Connecting to the database
    require_once '/my_custom_url/PRIVATE/db_config.php';
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Checking the connection
    if ($conn->connect_error) {
      die("Connection failure:" . $conn->connect_error);
    }

    // This SQL query lists all the sensors in your database. Thus, each time a new sensor is configured, it is automatically added to the dashboard.
    $sql = "SELECT DISTINCT Sensor FROM ACTIVITY ORDER BY Sensor ASC";
    $result = $conn->query($sql);

    //For each result of the query, we display a graphical area containing the key information of this sensor.
    if ($result->num_rows > 0) {
      while ($row = $result->fetch_assoc()) {
        $SensorUrl = urlencode($row["Sensor"]);

        /*
        We will display two important pieces of information on the dashboard for each sensor:

        1. The connectivity status "Connected" or "Offline"
            To check this, we verify if the last 'reading_time' is less than 61 seconds old.
            Normally, 60 seconds would be enough, but we add 1 second to account for the latency delay associated with data recording on the server.
        2. The production flow status "Production" or "Stopped"
            To determine this, we will compare the last two 'counter' values, ensuring that the counter increments
            AND that the most recent recording is less than 61 seconds old (using the same logic as before).
    */
        $lastTwoValuesSql = "SELECT counter FROM ACTIVITY WHERE Sensor = '" . $row["Sensor"] . "' ORDER BY reading_time DESC LIMIT 2";
        $lastTwoValuesResult = $conn->query($lastTwoValuesSql);
        $lastTwoValues = array();

        while ($valueRow = $lastTwoValuesResult->fetch_assoc()) {
          $lastTwoValues[] = $valueRow["counter"];
        }

        $lastReadingSql = "SELECT MAX(reading_time) AS last_reading_time FROM ACTIVITY WHERE Sensor = '" . $row["Sensor"] . "'";
        $lastReadingResult = $conn->query($lastReadingSql);
        $lastReadingRow = $lastReadingResult->fetch_assoc();
        $lastReadingTime = strtotime($lastReadingRow["last_reading_time"]);

        $currentTime = time();
        $timeDifference = $currentTime - $lastReadingTime; // Duration in seconds

        if (count($lastTwoValues) === 2 && $lastTwoValues[0] != $lastTwoValues[1] && $timeDifference < 61) {
          /* If there are exactly two last values, and they are different, and the time difference is less than 61 seconds, set the status to 'PRODUCTION'
          and display a green dot for visual indication.
          */
          $prod_or_stop = "PRODUCTION <span class='dot dot-green'></span>";
        } else {
          // Otherwise, set the status to 'STOPPED' and display a red dot as a visual indicator of the stoppage.
          $prod_or_stop = "STOPPED <span class='dot dot-red'></span>";
        }
        // Logic for the connectivity status : checks if the time difference is less than 61 seconds.
        $connexion = ($timeDifference < 61) ? "CONNECTED <span class='dot dot-green'></span>" : "OFFLINE <span class='dot dot-red'></span>";

        /* Date formatting depending on whether it is today's date.
            This line checks if the date of the last reading ($lastReadingTime) is the same as today's date.
            If the dates match (meaning the last reading was today), it sets the format to show only the time ("H:i").
            If the dates do not match (meaning the last reading was on a different day), it sets the format to show the date and the time ("d/m/Y H:i").
            This approach allows a user-friendly date display logic.
            If the event occurred today, the user sees only the time of the event, providing immediate context that it was recent.
        */
        $dateFormat = (date("Y-m-d", $lastReadingTime) == date("Y-m-d")) ? "H:i" : "d/m/Y H:i";
        $formattedDate = date($dateFormat, $lastReadingTime);

        $SensorUrl = urlencode($row["Sensor"]);

        // Generating a card for each Sensor.
        // We provide a direct link to the 'stats.php' page, which allows for viewing information related to this sensor for the current day.
        echo '<div class="card">
        <h3 class="card-title">' . htmlspecialchars($row["Sensor"]) . '</h3>
        <p class="card-content"> ' . $connexion . '</p>
        <p class="card-content">' . $prod_or_stop . '</p>
        <p class="card-content"><b>LAST UPDATE :</b></p>
        <p class="card-content"> ' . $formattedDate . '</p>

        <form class="row" method="post" action="stats.php">
        <input type="hidden" name="nameoftheSensor" value="' . htmlspecialchars($row["Sensor"]) . '">
        <input type="hidden" name="startDate" value="' . date('Y-m-d') . '">
        <input type="hidden" name="ceaseDate" value="' . date('Y-m-d', strtotime('+1 day')) . '">
        <button type="submit" class="card-btn">DAILY REPORT</button>
        </form>
        </div>';

      }
    } else {
      // In case there is no sensor
      echo "<p>No sensor found.</p>";
    }

    $conn->close();
    ?>
  </div>
  <!-- CARDS END -->

  <script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
  <script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/popper.min.js'></script>
  <script src='https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js'></script>
  <script src="./script.js"></script>

</body>
</html>
