<?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 and furthermore, we check if their level is equal to "Admin".
Even if the navigation bar does not allow users other than Admin to access the link,
it is necessary to counter attempts to access it through direct URL.
*/
if (!isset($_SESSION['username']) || $_SESSION['level'] != 'Admin') {
  header("Location: index.php");
  exit;
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
  <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 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">
          <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 active">
            <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="d-flex justify-content-center flex-column align-items-center">
    <button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#new_user_modal">
      Create a new user
    </button>

    <button type="button" class="btn btn-primary my-2" data-toggle="modal" data-target="#bdd_space_modal">
      Database size
    </button>
  </div>


  <!-- Modal for New User -->
  <div class="modal fade" id="new_user_modal" tabindex="-1" role="dialog" aria-labelledby="newUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="new_user_modal">New user</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form method="POST" action="user_add.php">
            <div class="form-group row">
              <label for="username" class="col-sm-2 col-form-label">Username:</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="username" name="username" required pattern="[a-zA-Z0-9]+">
              </div>
            </div>
            <div class="form-group row">
              <label for="email" class="col-sm-2 col-form-label">Email:</label>
              <div class="col-sm-10">
                <input type="email" class="form-control" id="email" name="email" required>
              </div>
            </div>

            <div class="form-group row">
              <label for="password" class="col-sm-2 col-form-label">Password:</label>
              <div class="col-sm-10">
                <input type="password" class="form-control" id="password" name="password" required>
              </div>
            </div>

            <div class="form-group row">
              <label for="level" class="col-sm-2 col-form-label">Level:</label>
              <div class="col-sm-10">
                <select class="form-control" id="level" name="level" required>
                  <option value="">Select a level</option>
                  <option value="Admin">Admin</option>
                  <option value="Team">Team</option>
                  <!-- Add other levels if necessary but keep 'Admin' because it is used in the security system design-->
                </select>
              </div>
            </div>

            <div class="form-group row">
              <div class="col-sm-10">
                <button type="submit" class="btn btn-primary">Add this new user</button>
              </div>
            </div>
          </form>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Modal for the database size -->
  <div class="modal fade" id="bdd_space_modal" tabindex="-1" role="dialog" aria-labelledby="bddspaceLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="bdd_space_modal">Database size</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <?php
          // Connecting to the database
          require_once '/my_custom_url/PRIVATE/db_config.php';
          $conn = new mysqli($servername, $username, $password, "dbs12345678");

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

          // Query to get the database size
          $sql = "SELECT table_schema AS 'Database',
          ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)'
          FROM information_schema.TABLES
          WHERE table_schema = 'dbs12345678'
          GROUP BY table_schema";

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

          // If there are results
          if ($result->num_rows > 0) {
            // Get back the database size
            $row = $result->fetch_assoc();
            echo "<p>Size of the database: " . $row['Size (MB)'] . " MB (" . number_format($row['Size (MB)'] / 1024, 6) . " GB)</p>";
          } else {
            echo "<p>Unable to retrieve the database size.</p>";
          }

          // Close the connection
          $conn->close();
          ?>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>



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