<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Pipscart - User Management</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="assets/css/style.css">
    <!-- End layout styles -->
  </head>
  <body>
    <div class="container-scroller">
      <!-- partial:partials/_navbar.html -->
      <?php include "header.php"; ?>
      <!-- partial -->
      <div class="container-fluid page-body-wrapper">
        <!-- partial:partials/_sidebar.html -->
        <?php include "sidebar.php"; ?>
        <!-- partial -->
        <div class="main-panel">
          <div class="content-wrapper">
            <div class="row g-1">
              <div class="col-md-4">
                <div class="card">
                  <div class="card-body">
                    <h4 class="card-title">Manage Accounts</h4>
                    <form class="forms-sample" action="" method="POST">
                      <input type="hidden" name="user_id" id="user_id" value="">
                      <div class="form-group">
                          <div class="form-floating">
                        <input type="text" class="form-control" name="username" id="username" placeholder="Username" required>
                    <label for="floatingPassword">Username</label>
                    </div>
                      </div>
                      <div class="form-group">
                          <div class="form-floating">
                        <input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
                    <label for="floatingPassword">Email</label>
                    </div>
                      </div>
                       <div class="form-group">
                          <div class="form-floating"><input type="password" class="form-control" name="password" id="password" placeholder="Password" required>
                    <label for="floatingPassword">Password</label>
                    </div>
                      </div>
                      <div class="form-group">
                          <div class="form-floating">
                        <input type="password" class="form-control" name="re_password" id="re_password" placeholder="Re-enter Password" required>
                    <label for="floatingPassword">Reenter Password</label>
                    </div>
                      </div>
                      <button type="submit" name="submit" class="btn btn-gradient-primary w-100" id="submitBtn">Add User</button>
                    </form>
                  </div>
                </div>
              </div>
              <div class="col-md-8">
                <div class="card">
                  <div class="card-body">
                    <div class="div d-flex justify-content-between">
                      <h4 class="card-title">Accounts</h4>
                    </div>
                    <div class="table-responsive">
                      <table class="table">
                        <thead>
                          <tr>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                         include 'config.php';

                          // Handle form submission
                          if ($_SERVER["REQUEST_METHOD"] == "POST") {
                            if (isset($_POST['submit'])) {
                              // Add or Update user
                              $user_id = $_POST['user_id'];
                              $username = $_POST['username'];
                              $email = $_POST['email'];
                              $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                              
                              if (empty($user_id)) {
                                // Add new user
                                $sql = "INSERT INTO tbl_users (username, email, password) VALUES ('$username', '$email', '$password')";
                                $message = "User added successfully!";
                              } else {
                                // Update existing user
                                if (!empty($_POST['password'])) {
                                  $sql = "UPDATE tbl_users SET username='$username', email='$email', password='$password' WHERE id=$user_id";
                                } else {
                                  $sql = "UPDATE tbl_users SET username='$username', email='$email' WHERE id=$user_id";
                                }
                                $message = "User updated successfully!";
                              }
                              
                              if ($con->query($sql) === TRUE) {
                                echo "<script>alert('$message');</script>";
                                echo "<script>window.location.href = window.location.href;</script>";
                              } else {
                                echo "<script>alert('Error: " . $sql . "\\n" . $con->error . "');</script>";
                              }
                            }
                          }

                          // Handle delete action
                          if (isset($_GET['delete'])) {
                            $id = $_GET['delete'];
                            $sql = "DELETE FROM tbl_users WHERE id=$id";
                            
                            if ($con->query($sql) === TRUE) {
                              echo "<script>alert('User deleted successfully!');</script>";
                              echo "<script>window.location.href = window.location.href;</script>";
                            } else {
                              echo "<script>alert('Error deleting user: " . $con->error . "');</script>";
                            }
                          }

                          // Fetch all users
                          $sql = "SELECT * FROM tbl_users";
                          $result = $con->query($sql);

                          if ($result->num_rows > 0) {
                            while($row = $result->fetch_assoc()) {
                              echo "<tr>
                                      <td>{$row['username']}</td>
                                      <td>{$row['email']}</td>
                                      <td>
                                        <span style='display:flex;gap: 5px;align-items: center;'>
                                          <a href='javascript:void(0);' onclick='editUser({$row['id']}, \"{$row['username']}\", \"{$row['email']}\")'>
                                            <i class='fa fa-edit text-warning'></i>
                                          </a>
                                          <a href='?delete={$row['id']}' onclick='return confirm(\"Are you sure you want to delete this user?\")'>
                                            <i class='fa fa-trash-o text-danger'></i>
                                          </a>
                                        </span>
                                      </td>
                                    </tr>";
                            }
                          } else {
                            echo "<tr><td colspan='3'>No users found</td></tr>";
                          }
                          $con->close();
                          ?>
                        </tbody>
                      </table>
                    </div>
                    <nav aria-label="Page navigation example">
                      <ul class="pagination">
                        <li class="page-item"><a class="page-link" href="#"><i class="fa fa-angle-left"></i></a></li>
                        <li class="page-item"><a class="page-link" href="#">1</a></li>
                        <li class="page-item"><a class="page-link" href="#">2</a></li>
                        <li class="page-item"><a class="page-link" href="#">3</a></li>
                        <li class="page-item"><a class="page-link" href="#"><i class="fa fa-angle-right"></i></a></li>
                      </ul>
                    </nav>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- content-wrapper ends -->
          <!-- partial:partials/_footer.html -->
          <?php include "footer.php"; ?>
          <!-- partial -->
        </div>
        <!-- main-panel ends -->
      </div>
      <!-- page-body-wrapper ends -->
    </div>

    <script>
      function editUser(id, username, email) {
        document.getElementById('user_id').value = id;
        document.getElementById('username').value = username;
        document.getElementById('email').value = email;
        document.getElementById('password').required = false;
        document.getElementById('re_password').required = false;
        document.getElementById('submitBtn').innerHTML = 'Update User';
        
        // Scroll to the form
        document.querySelector('.forms-sample').scrollIntoView({
          behavior: 'smooth'
        });
      }
    </script>

    <!-- plugins:js -->
    <script src="assets/vendors/js/vendor.bundle.base.js"></script>
    <!-- endinject -->
    <!-- Plugin js for this page -->
    <script src="assets/vendors/chart.js/chart.umd.js"></script>
    <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
    <!-- End plugin js for this page -->
    <!-- inject:js -->
    <script src="assets/js/off-canvas.js"></script>
    <script src="assets/js/misc.js"></script>
    <script src="assets/js/settings.js"></script>
    <script src="assets/js/todolist.js"></script>
    <script src="assets/js/jquery.cookie.js"></script>
    <!-- endinject -->
    <!-- Custom js for this page -->
    <script src="assets/js/dashboard.js"></script>
    <!-- End custom js for this page -->
  </body>
</html>
