<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('includes/head.php'); ?>
</head>
<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
    <?php include('includes/sidebar.php'); ?> <!-- Inclusion de la barre latérale -->
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
       <?php include('includes/topbar.php'); ?> <!-- Inclusion de la barre supérieure -->
        <!-- Topbar -->

        <!-- Container Fluid-->
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Table des utilisateurs</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item">Tableaux</li>
              <li class="breadcrumb-item active" aria-current="page">Table des utilisateurs</li>
            </ol>
          </div>

          <!-- Users Table -->
          <div class="card mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
              <h6 class="m-0 font-weight-bold text-primary">Utilisateurs</h6>
            </div>
            <div class="table-responsive p-3">
              <table class="table align-items-center table-flush" id="dataTable">
                <thead class="thead-light">
                  <tr>
                    <th>Prénom</th>
                    <th>Nom</th>
                    <th>Numéro de téléphone</th>
                    <th>Email</th>
                    <th>Rôle</th>
                    <th>Statut</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Prénom</th>
                    <th>Nom</th>
                    <th>Numéro de téléphone</th>
                    <th>Email</th>
                    <th>Rôle</th>
                    <th>Statut</th>
                    <th>Actions</th>
                  </tr>
                </tfoot>
                <tbody>
                  <?php
                  // Include database connection from config/connexion.php
                  include 'config/connexion.php';

                  // Query to fetch users
                  $query = "SELECT id, first_name, last_name, phone_num, user_email, user_role, status 
                            FROM users_table";
                  $result = $conn->query($query);

                  if ($result->num_rows > 0) {
                    while ($user = $result->fetch_assoc()) {
                      $toggleClass = $user['status'] == 1 ? 'btn-success' : 'btn-danger';
                      $toggleText = $user['status'] == 1 ? 'Activé' : 'Désactivé';
                      $newStatus = $user['status'] == 1 ? 0 : 1;

                      echo "<tr>
                              <td>{$user['first_name']}</td>
                              <td>{$user['last_name']}</td>
                              <td>{$user['phone_num']}</td>
                              <td>{$user['user_email']}</td>
                              <td>{$user['user_role']}</td>
                              <td>
                                <button class='btn btn-sm $toggleClass toggle-status' data-id='{$user['id']}' data-status='$newStatus' data-role='{$user['user_role']}'>
                                  $toggleText
                                </button>
                              </td>
                              <td>
                                <a href='edit_user.php?id={$user['id']}' class='btn btn-sm btn-primary' title='Modifier l\'utilisateur'>
                                  <i class='fas fa-edit'></i> Modifier
                                </a>
                              </td>
                            </tr>";
                    }
                  } else {
                    echo "<tr><td colspan='7' class='text-center'>Aucun utilisateur trouvé</td></tr>";
                  }

                  // Close the database connection
                  // Connection is managed globally; do not close it here.
                  ?>
                </tbody>
              </table>
            </div>
          </div>
          <!-- End Users Table -->

          <!-- Modal Logout -->
          <!-- Modal Logout -->      


        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include('includes/footer.php'); ?> <!-- Inclusion du footer -->
      <!-- Footer -->
    </div>
  </div>

  <!-- Scroll to top -->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
  <script>
    $(document).ready(function () {
      $('#dataTable').DataTable(); // Initialize DataTable

      // Handle toggle status button click
      $(document).on('click', '.toggle-status', function () {
        const button = $(this);
        const userId = button.data('id');
        const newStatus = button.data('status');

        $.ajax({
          url: 'toggle_status.php',
          type: 'POST',
          data: { id: userId, status: newStatus },
          success: function (response) {
            if (response === 'success') {
              button.toggleClass('btn-success btn-danger');
              button.text(newStatus == 1 ? 'Activé' : 'Désactivé');
              button.data('status', newStatus == 1 ? 0 : 1);
            } else if(response === 'forbidden') {
              alert('Désactivation interdite: il doit rester au moins un Super admin actif.');
            } else {
              alert('Échec de la mise à jour du statut');
            }
          },
          error: function () {
            alert('Une erreur est survenue');
          }
        });
      });


    });
  </script>

</body>

</html>