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

// Fetch all users - adjusted query to work with your database structure
try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE (status IS NULL OR status != 2) ORDER BY id DESC");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $users = [];
    error_log("Error fetching users: " . $e->getMessage());
}
?>
  <title>All 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">All Users</h1>
                <ol class="breadcrumb">
                  <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
                  <li class="breadcrumb-item active" aria-current="page">All Users</li>
                </ol>
              </div>

              <!---Container Fluid-->
              <!-- Row -->
              <div class="row">
                <!-- Datatables -->
                <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 Active Users</h6>
                      <div>
                        <a href="blocked_users.php" class="btn btn-sm btn-warning">
                          <i class="fas fa-ban"></i> Blocked Users
                        </a>
                        <a href="banned_users.php" class="btn btn-sm btn-danger">
                          <i class="fas fa-user-slash"></i> Banned Users
                        </a>
                        <a href="admin_users.php" class="btn btn-sm btn-info">
                          <i class="fas fa-user-shield"></i> Admin Users
                        </a>
                      </div>
                    </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>Full Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Main Balance</th>
                            <th>Referral Balance</th>
                            <th>Total Referred</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'];
                            
                            // 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";
                            }
                            
                            // Check if user is admin
                            $is_admin = ($data['is_admin'] == 1);
                            $is_current_user = ($user_id == $_SESSION['user_id']);
                            ?>
                            <tr>
                              <td><?php echo $i; ?></td>
                              <td>
                                <strong><?php echo htmlspecialchars($data['username']); ?></strong>
                                <?php if($is_admin): ?>
                                  <span class="badge badge-primary ml-1">Admin</span>
                                <?php endif; ?>
                              </td>
                              <td><?php echo htmlspecialchars($data['full_name'] ?? '—'); ?></td>
                              <td><?php echo htmlspecialchars($data['email']); ?></td>
                              <td><?php echo htmlspecialchars($data['phone'] ?? '—'); ?></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><?php echo number_format($data['total_referred']); ?></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>
                                <div class="btn-group" role="group">
                                  <button type="button" 
                                          class="btn btn-sm btn-primary dropdown-toggle" 
                                          data-toggle="dropdown" 
                                          aria-haspopup="true" 
                                          aria-expanded="false">
                                    <i class="fas fa-cog"></i> Actions
                                  </button>
                                  <div class="dropdown-menu">
                                    <a class="dropdown-item" href="#" onclick="editUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($data['full_name'] ?? '', ENT_QUOTES); ?>', '<?php echo htmlspecialchars($data['email'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($data['phone'] ?? '', ENT_QUOTES); ?>')">
                                      <i class="fas fa-edit text-primary"></i> Edit User
                                    </a>
                                    <a class="dropdown-item" href="#" onclick="addFunds(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                      <i class="fas fa-plus-circle text-success"></i> Add Funds
                                    </a>
                                    <a class="dropdown-item" href="#" onclick="debitUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                      <i class="fas fa-minus-circle text-danger"></i> Debit User
                                    </a>
                                    <a class="dropdown-item" href="#" onclick="loginAsUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                      <i class="fas fa-sign-in-alt text-info"></i> Login as User
                                    </a>
                                    
                                    <?php if(!$is_current_user): ?>
                                      <?php if($data['status'] == 1): ?>
                                        <a class="dropdown-item" href="#" onclick="blockUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                          <i class="fas fa-ban text-warning"></i> Block User
                                        </a>
                                      <?php endif; ?>
                                      
                                      <?php if(!$is_admin): ?>
                                        <a class="dropdown-item" href="#" onclick="makeAdmin(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                          <i class="fas fa-user-shield text-info"></i> Make Admin
                                        </a>
                                      <?php else: ?>
                                        <a class="dropdown-item" href="#" onclick="removeAdmin(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                          <i class="fas fa-user-minus text-secondary"></i> Remove Admin
                                        </a>
                                      <?php endif; ?>
                                      
                                      <div class="dropdown-divider"></div>
                                      
                                      <a class="dropdown-item" href="#" onclick="banUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>')">
                                        <i class="fas fa-user-slash text-danger"></i> Ban User
                                      </a>
                                      
                                      <a class="dropdown-item" href="#" onclick="deleteUser(<?php echo $user_id; ?>, '<?php echo htmlspecialchars($data['username'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($data['email'], ENT_QUOTES); ?>')">
                                        <i class="fas fa-trash text-danger"></i> Delete User
                                      </a>
                                    <?php endif; ?>
                                  </div>
                                </div>
                              </td>
                            </tr>
                            <?php
                            $i++;
                          }
                          ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>

              </div>
              <!-- Footer -->
           <!-- Page level plugins -->
          <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,
                order: [[0, 'desc']]
              });
            });
            
            // Edit user function - opens popup modal
            function editUser(userId, userName, fullName, email, phone) {
              document.getElementById('editUserId').value    = userId;
              document.getElementById('editUsername').value  = userName;
              document.getElementById('editFullName').value  = fullName;
              document.getElementById('editEmail').value     = email;
              document.getElementById('editPhone').value     = phone;
              document.getElementById('editUserLabel').textContent = 'Edit: ' + userName;
              $('#editUserModal').modal('show');
            }

            // Submit edit user form via AJAX
            $('#editUserForm').on('submit', function(e) {
              e.preventDefault();
              const phone = document.getElementById('editPhone').value.trim();
              if (phone !== '' && !/^\+?[0-9]{7,15}$/.test(phone)) {
                Swal.fire('Validation Error', 'Please enter a valid phone number (e.g. +2349065236144)', 'warning');
                return;
              }
              Swal.fire({
                title: 'Saving...',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
              });
              $.ajax({
                url: 'ajax/edit_user.php',
                type: 'POST',
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                  Swal.close();
                  if (data.status == '1') {
                    $('#editUserModal').modal('hide');
                    Swal.fire({
                      title: 'Success!',
                      text: data.msg,
                      icon: 'success',
                      confirmButtonColor: '#1cc88a'
                    }).then(() => { location.reload(); });
                  } else {
                    Swal.fire('Error!', data.msg, 'error');
                  }
                },
                error: function() {
                  Swal.close();
                  Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                }
              });
            });
            
            // Add funds function
            function addFunds(userId, userName) {
              Swal.fire({
                title: 'Add Funds',
                html: `
                  <p>Adding funds to: <strong>${userName}</strong></p>
                  <input type="number" id="amount" class="swal2-input" placeholder="Enter amount" min="1" step="0.01">
                  <select id="fund_type" class="swal2-input">
                    <option value="main_balance">Main Balance</option>
                    <option value="referral_balance">Referral Balance</option>
                  </select>
                `,
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#1cc88a',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Add Funds',
                preConfirm: () => {
                  const amount = document.getElementById('amount').value;
                  const fund_type = document.getElementById('fund_type').value;
                  
                  if (!amount || amount <= 0) {
                    Swal.showValidationMessage('Please enter a valid amount');
                    return false;
                  }
                  
                  return { amount: amount, fund_type: fund_type };
                }
              }).then((result) => {
                if (result.isConfirmed) {
                  Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                  });
                  
                  $.ajax({
                    url: 'ajax/add_funds.php',
                    type: 'POST',
                    data: { 
                      user_id: userId, 
                      amount: result.value.amount,
                      fund_type: result.value.fund_type
                    },
                    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');
                    }
                  });
                }
              });
            }
            
            // Debit user function
            function debitUser(userId, userName) {
              Swal.fire({
                title: 'Debit User',
                html: `
                  <p>Deducting funds from: <strong>${userName}</strong></p>
                  <input type="number" id="debit_amount" class="swal2-input" placeholder="Enter amount" min="1" step="0.01">
                  <select id="debit_fund_type" class="swal2-input">
                    <option value="main_balance">Main Balance</option>
                    <option value="referral_balance">Referral Balance</option>
                  </select>
                  <input type="text" id="debit_reason" class="swal2-input" placeholder="Reason (optional)">
                `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Debit User',
                preConfirm: () => {
                  const amount = document.getElementById('debit_amount').value;
                  const fund_type = document.getElementById('debit_fund_type').value;
                  const reason = document.getElementById('debit_reason').value;
                  
                  if (!amount || amount <= 0) {
                    Swal.showValidationMessage('Please enter a valid amount');
                    return false;
                  }
                  
                  return { amount: amount, fund_type: fund_type, reason: reason };
                }
              }).then((result) => {
                if (result.isConfirmed) {
                  Swal.fire({
                    title: 'Processing...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                  });
                  
                  $.ajax({
                    url: 'ajax/debit_user.php',
                    type: 'POST',
                    data: { 
                      user_id: userId, 
                      amount: result.value.amount,
                      fund_type: result.value.fund_type,
                      reason: result.value.reason
                    },
                    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');
                    }
                  });
                }
              });
            }
            
            // Block user function
            function blockUser(userId, userName) {
              Swal.fire({
                title: 'Block User?',
                html: `Are you sure you want to block <strong>${userName}</strong>?<br><small>User will not be able to login.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f6c23e',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Block User'
              }).then((result) => {
                if (result.isConfirmed) {
                  performAction('ajax/block_user.php', userId, 'Block');
                }
              });
            }
            
            // Ban user function
            function banUser(userId, userName) {
              Swal.fire({
                title: 'Ban User?',
                html: `Are you sure you want to ban <strong>${userName}</strong>?<br><small>User will be permanently banned.</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Ban User'
              }).then((result) => {
                if (result.isConfirmed) {
                  performAction('ajax/ban_user.php', userId, 'Ban');
                }
              });
            }
            
            // Make admin function
            function makeAdmin(userId, userName) {
              Swal.fire({
                title: 'Make Admin?',
                html: `Grant admin privileges to <strong>${userName}</strong>?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4e73df',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Make Admin'
              }).then((result) => {
                if (result.isConfirmed) {
                  performAction('ajax/make_admin.php', userId, 'Admin');
                }
              });
            }
            
            // Remove admin function
            function removeAdmin(userId, userName) {
              Swal.fire({
                title: 'Remove Admin?',
                html: `Remove admin privileges from <strong>${userName}</strong>?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#858796',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Remove Admin'
              }).then((result) => {
                if (result.isConfirmed) {
                  performAction('ajax/remove_admin.php', userId, 'Remove Admin');
                }
              });
            }
            
            // Delete user function
            function deleteUser(userId, userName, userEmail) {
              Swal.fire({
                title: 'Delete User Account?',
                html: `
                  <div style="text-align: left;">
                    <p><strong>Warning:</strong> This action will permanently delete:</p>
                    <ul style="text-align: left; margin-left: 20px;">
                      <li>User: <strong>${userName}</strong></li>
                      <li>Email: <strong>${userEmail}</strong></li>
                      <li>All user data (wallet, transactions, numbers)</li>
                      <li>All referral data</li>
                      <li>API keys and history</li>
                    </ul>
                    <p style="color: #e74a3b;"><strong>This action cannot be undone!</strong></p>
                  </div>
                `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Delete Permanently',
                cancelButtonText: 'Cancel',
                focusCancel: true
              }).then((result) => {
                if (result.isConfirmed) {
                  performAction('ajax/delete_user.php', userId, 'Delete');
                }
              });
            }
            
            // Login as user function
            function loginAsUser(userId, userName) {
              Swal.fire({
                title: 'Login as User?',
                html: `You will be logged in as <strong>${userName}</strong>.<br><small>You can return to admin from the user dashboard.</small>`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#36b9cc',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Yes, Login as User'
              }).then((result) => {
                if (result.isConfirmed) {
                  Swal.fire({
                    title: 'Switching...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                  });
                  
                  $.ajax({
                    url: 'ajax/login_as_user.php',
                    type: 'POST',
                    data: { user_id: userId },
                    dataType: 'json',
                    success: function(data) {
                      Swal.close();
                      if(data.status == '1') {
                        window.location.href = data.redirect || '../user/dashboard.php';
                      } else {
                        Swal.fire('Error!', data.msg, 'error');
                      }
                    },
                    error: function() {
                      Swal.close();
                      Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                    }
                  });
                }
              });
            }
            
            // Generic action performer
            function performAction(url, userId, actionName) {
              Swal.fire({
                title: 'Processing...',
                html: 'Please wait...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => { Swal.showLoading(); }
              });
              
              $.ajax({
                url: url,
                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(xhr) {
                  Swal.close();
                  console.error(actionName + ' error:', xhr.responseText);
                  Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                }
              });
            }
          </script>
          
          <!-- Edit User Modal -->
          <div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
              <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                  <h5 class="modal-title" id="editUserLabel">Edit User</h5>
                  <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <form id="editUserForm">
                  <div class="modal-body">
                    <input type="hidden" name="user_id" id="editUserId">

                    <div class="form-group">
                      <label class="font-weight-bold">Username</label>
                      <input type="text" id="editUsername" class="form-control bg-light" readonly>
                      <small class="text-muted">Username cannot be changed</small>
                    </div>

                    <div class="form-group">
                      <label class="font-weight-bold">Full Name</label>
                      <input type="text" name="full_name" id="editFullName" class="form-control" placeholder="Enter full name">
                    </div>

                    <div class="form-group">
                      <label class="font-weight-bold">Email Address</label>
                      <input type="email" id="editEmail" class="form-control bg-light" readonly>
                      <small class="text-muted">Email cannot be changed here</small>
                    </div>

                    <div class="form-group">
                      <label class="font-weight-bold">Phone Number</label>
                      <input type="tel" name="phone" id="editPhone" class="form-control" placeholder="e.g. +2349065236144">
                      <small class="text-muted">Include country code (e.g. +234...)</small>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <style>
            .btn-group {
              white-space: nowrap;
            }
            
            .dropdown-item {
              cursor: pointer;
            }
            
            .dropdown-item i {
              width: 20px;
              margin-right: 5px;
            }
          </style>

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