<?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</title>
  <meta charset="UTF-8">
  <title>LeanC IOT | SaaS 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 href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans'>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css'>
  <link rel="stylesheet" href="./style.css">
  <link rel="stylesheet" href="./style_res_tbl.css">

</head>
<body>
  <!-- NAV -->
  <nav class="navbar navbar-expand-custom navbar-mainbg">
    <a class="navbar-brand navbar-logo" href="dashboard.php">LeanC IOT | SaaS 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">
          <a class="nav-link" href="dashboard.php"><i class="fas fa-tachometer-alt"></i>Dashboard</a>
        </li>
        <li class="nav-item active">
          <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="content-container">
    <table>
      <thead>
        <tr>
          <th scope="col">Sensor</th>
          <th scope="col">Start Time</th>
          <th scope="col">End Time</th>
          <th scope="col">Duration</th>
          <th scope="col">Ishikawa Cat.</th>
        </tr>
      </thead>
      <tbody>
        <?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);
        }


        $Beginning_activity_id = isset($_POST['Beginning_activity_id']) ? $_POST['Beginning_activity_id'] : 'default_value';
        $Cease_activity_id = isset($_POST['Cease_activity_id']) ? $_POST['Cease_activity_id'] : 'default_value';


        $sql = "SELECT STOPS.id_activ, A1.reading_time AS reading_time_id_activ, STOPS.type, STOPS.id_activ2, A2.reading_time AS reading_time_id_activ2, A1.Sensor
        FROM STOPS
        JOIN ACTIVITY AS A1 ON STOPS.id_activ = A1.id
        JOIN ACTIVITY AS A2 ON STOPS.id_activ2 = A2.id
        WHERE STOPS.id_activ = ? AND STOPS.id_activ2 = ?";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $Beginning_activity_id, $Cease_activity_id);

        $stmt->execute();
        $result = $stmt->get_result();

        while($row = $result->fetch_assoc()) {
          echo "<tr>";
          echo "<td data-label='Sensor'>" . $row['Sensor'] . "</td>";
          echo "<td data-label='Start Time'>" . date('Y-m-d H:i', strtotime($row['reading_time_id_activ'])) . "</td>";
          echo "<td data-label='End Time'>" . date('Y-m-d H:i', strtotime($row['reading_time_id_activ2'])) . "</td>";
          $start = new DateTime($row['reading_time_id_activ']);
          $end = new DateTime($row['reading_time_id_activ2']);
          $interval = $start->diff($end);

          $minutes = $interval->days * 24 * 60;
          $minutes += $interval->h * 60;
          $minutes += $interval->i;

          echo "<td data-label='Duration'>" . $minutes . " min</td>";
          echo "<td data-label='Ishikawa Cat.'>" . $row['type'] . "</td>";
          echo "</tr>";
        }
        $stmt->close();
        ?>
      </tbody>
    </table>
  </div>

  <?php
  $sql = "SELECT content, reading_time, initials FROM MESSAGES WHERE id_activ = ? ORDER BY id DESC";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param("i", $Beginning_activity_id);
  $stmt->execute();
  $result = $stmt->get_result();

  echo "<div class=\"chat\"><div class=\"chat-history\"><ul>";

  if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
      // Here, we integrate each message into the desired HTML structure
      echo "<li>";
      echo "<div class=\"message-data\">";
      echo "<span class=\"message-data-name\">" . htmlspecialchars($row['initials']) . "</span>";
      echo "<span class=\"message-data-time\">" . date('Y-m-d H:i', strtotime(htmlspecialchars($row['reading_time']))) . "</span>";
      echo "</div>";
      echo "<div class=\"message my-message\">" . htmlspecialchars($row['content']) . "</div>";
      echo "</li>";
    }
  } else {
    echo "<li><div class='message'>No messages found for this stop.</div></li>";
  }

  echo "</ul></div></div>";

  $stmt->close();
  $conn->close();
  ?>

  <div class="chat">
    <div class="chat-message clearfix">
      <form id="messageForm" action="message_send.php" method="post">
          <textarea name="message-to-send" id="message-to-send" placeholder="Your message here" rows="3" required></textarea>

          <input type="hidden" name="initials" id="initials" placeholder="Your initials" required
                 value="<?php echo htmlspecialchars(isset($_SESSION['username']) ? $_SESSION['username'] : ''); ?>" />

          <input type="hidden" name="Beginning_activity_id" id="Beginning_activity_id" />
          <input type="hidden" name="Cease_activity_id" id="Cease_activity_id" />
          <button type="submit">Send</button>
      </form>



  </div>
</div>

<script>
document.getElementById('messageForm').addEventListener('submit', function(e) {
  e.preventDefault();
  var Beginning_activity_id = "<?php echo htmlspecialchars($Beginning_activity_id); ?>";
  var Cease_activity_id = "<?php echo htmlspecialchars($Cease_activity_id); ?>";
  document.getElementById('Beginning_activity_id').value = Beginning_activity_id;
  document.getElementById('Cease_activity_id').value = Cease_activity_id;
  document.getElementById('messageForm').submit();
});
</script>



<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>
