<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include ('include/header.php');
$page_title = WEB_NAME . " | Admin Users";

// Fetch admin users
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE is_admin = 1 ORDER BY id DESC");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $users = [];
    error_log("Error fetching admin users: " . $e->getMessage());
}
?>
  <title>Admin Users - <?php echo $site_data['web_name']; ?></title>
  
  <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
             <!-- 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">Admin Users</h1>
                <ol class="breadcrumb">
                  <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                  <li class="breadcrumb-item"><a href="all_users.php">All Users</a></li>
                  <li class="breadcrumb-item active" aria-current="page">Admin Users</li>
                </ol>
              </div>

              <!-- Row -->
              <div class="row">
                <div class="col-lg-12">
                  <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">All Admin Users</h6>
                      <a href="all_users.php" class="btn btn-sm btn-primary">
                        <i class="fas fa-arrow-left"></i> Back to All Users
                      </a>
                    </div>
                    <div class="table-responsive p-3">
                      <table class="table align-items-center table-flush table-hover" id="dataTable">
                        <thead class="thead-light">
                          <tr>
                            <th>#</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Main Balance</th>
                            <th>Referral Balance</th>
                            <th>Register Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php
                          $i = 1;
                          foreach ($users as $data) {
                            $user_id = $data['id'];
                            $is_current_user = ($user_id == $_SESSION['user_id']);
                            
                            // Determine status - handle NULL status as active
                            $user_status = isset($data['status']) ? $data['status'] : 1;
                            if ($user_status == "1" || $user_status === null) {
                              $status = "badge badge-success";
                              $status1 = "Active";
                            } elseif ($user_status == "0") {
                              $status = "badge badge-warning";
                              $status1 = "Blocked";
                            } else {
                              $status = "badge badge-danger";
                              $status1 = "Banned";
                            }
                            ?>
                            <tr>
                              <td><?php echo $i; ?></td>
                              <td>
                                <strong><?php echo htmlspecialchars($data['username']); ?></strong>
                                <span class="badge badge-primary ml-1">Admin</span>
                                <?php if($is_current_user): ?>
                                  <span class="badge badge-info ml-1">You</span>
                                <?php endif; ?>
                              </td>
                              <td><?php echo htmlspecialchars($data['email']); ?></td>
                              <td><strong>NGN<?php echo number_format($data['main_balance'], 2); ?></strong></td>
                              <td>NGN<?php echo number_format($data['referral_balance'], 2); ?></td>
                              <td>
                                <small><?php echo date('M d, Y', strtotime($data['created_at'])); ?></small>
                              </td>
                              <td><span class="<?php echo $status; ?>"><?php echo $status1; ?></span></td>
                              <td>
                                <?php if(!$is_current_user): ?>
                                  <button type="button" 
                                          class="btn btn-sm btn-warning" 
                                          onclick="removeAdmin(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')"
                                          title="Remove Admin Privileges">
                                    <i class="fas fa-user-minus"></i> Remove Admin
                                  </button>
                                <?php else: ?>
                                  <button type="button" 
                                          class="btn btn-sm btn-secondary" 
                                          disabled
                                          title="Cannot remove yourself">
                                    <i class="fas fa-shield-alt"></i> Current User
                                  </button>
                                <?php endif; ?>
                              </td>
                            </tr>
                            <?php
                            $i++;
                          }
                          ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
              
          <script src="vendor/datatables/jquery.dataTables.min.js"></script>
          <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
          <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
          
          <script>
            $(document).ready(function () {
              $('#dataTable').DataTable({
                ordering: true,
                pageLength: 25
              });
            });
            
            // Remove admin function
            function removeAdmin(userId, userName) {
              Swal.fire({
                title: 'Remove Admin Privileges?',
                html: `Remove admin privileges from <strong>${userName}</strong>?<br><small>User will become a regular user.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f6c23e',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Remove Admin'
              }).then((result) => {
                if (result.isConfirmed) {
                  Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                  });
                  
                  $.ajax({
                    url: 'ajax/remove_admin.php',
                    type: 'POST',
                    data: { user_id: userId },
                    dataType: 'json',
                    success: function(data) {
                      Swal.close();
                      if(data.status == '1') {
                        Swal.fire({
                          title: 'Success!',
                          text: data.msg,
                          icon: 'success',
                          confirmButtonColor: '#1cc88a'
                        }).then(() => { location.reload(); });
                      } else {
                        Swal.fire('Error!', data.msg, 'error');
                      }
                    },
                    error: function() {
                      Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                    }
                  });
                }
              });
            }
          </script>

<?php
include ('include/footer.php');
?>