<?php
require_once __DIR__ . '/../actions/admin_auth.php';
require_once __DIR__ . '/../includes/db.php';

$search = trim($_GET['search'] ?? '');
$limit = 10;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

$whereSQL = '';
$params = [];

if ($search !== '') {
  $whereSQL = "WHERE firstname LIKE ? OR lastname LIKE ? OR email LIKE ? OR account_number LIKE ?";
  $params = ["%$search%", "%$search%", "%$search%", "%$search%"];
}

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM users $whereSQL");
$countStmt->execute($params);
$totalUsers = (int)$countStmt->fetchColumn();
$totalPages = ceil($totalUsers / $limit);

$stmt = $pdo->prepare("SELECT * 
                       FROM users $whereSQL ORDER BY id DESC LIMIT $limit OFFSET $offset");
$stmt->execute($params);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    body {
      background: #f5f6fa;
      font-family: 'Poppins', sans-serif;
    }
    .navbar {
      background: #0f2027;
      background: linear-gradient(90deg, #203a43, #2c5364);
    }
    .navbar-brand {
      color: #fff !important;
      font-weight: 600;
    }
    .card {
      border-radius: 1rem;
      box-shadow: 0 2px 15px rgba(0,0,0,0.1);
    }
    .btn-action {
      padding: 3px 10px;
      font-size: 0.85rem;
    }
  </style>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Manage Users - Admin Panel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-dark">
<nav class="navbar navbar-dark px-3">
  <a class="navbar-brand" href="../users">User Dashboard</a>
  <div>
      <a href="." class="btn btn-primary btn-sm"><i class="bi bi-box-arrow-right"></i> Dashboard</a>
  <a href="transactions" class="btn btn-primary btn-sm"><i class="bi bi-box-arrow-right"></i> Transactions</a>
  </div>
</nav>


<div class="container py-5">
  <div class="card shadow-sm">
    

    <div class="card-body">
      <form method="get" class="row g-2 mb-3">
        <div class="col-md-8">
          <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-control" placeholder="Search by name, email, or account number">
        </div>
        <div class="col-md-2 d-grid">
          <button class="btn btn-primary">Search</button>
        </div>
        <div class="col-md-2 d-grid">
          <a href="users" class="btn btn-secondary">Reset</a>
        </div>
      </form>

      <div class="table-responsive">
        <?php if (count($users) > 0): ?>
          <table class="table table-striped table-bordered align-middle">
            <thead class="table-dark">
              <tr>
                <!--<th>#</th>-->
                <th>OTP</th>
                <th>Email</th>
                <!--<th>Phone</th>-->
                <th>Account No.</th>
                <th>Balance</th>
                <th>Email Status</th>
                <th>Account Status</th>
                <th>Admin</th>
                <th>Joined</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($users as $i => $u): ?>
                <tr>
                  <!--<td><?= $offset + $i + 1 ?></td>-->
                  <!--<td><?= htmlspecialchars($u['firstname'] . ' ' . $u['lastname']) ?></td>-->
                  <td><?php echo $u['otp']; ?></td>
                  <td><?= htmlspecialchars($u['email']) ?></td>
                  <!--<td><?= htmlspecialchars($u['phone'] ?? '-') ?></td>-->
                  <td><strong><?= htmlspecialchars($u['account_number'] ?? '-') ?></strong></td>
                  <td><?= htmlspecialchars($u['currency'] ?? '$') . ' ' . number_format((float)($u['account_balance'] ?? 0), 2) ?></td>
                  <td>
                    <?php if ($u['is_verified']): ?>
                      <span class="badge bg-success">Verified</span>
                    <?php else: ?>
                      <span class="badge bg-secondary">Unverified</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php if ($u['status'] == 'active'): ?>
                      <span class="badge bg-success">Active</span>
                    <?php else: ?>
                      <span class="badge bg-secondary"><?php echo $u['status']; ?></span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?= $u['is_admin'] ? '<span class="badge bg-info">Admin</span>' : '<span class="badge bg-light text-dark">User</span>' ?>
                  </td>
                  <td><?= htmlspecialchars(date('M d, Y', strtotime($u['created_at'] ?? 'now'))) ?></td>
                  <td>
                    <button class="btn btn-sm btn-primary" 
                            onclick='openEditModal(<?= json_encode($u) ?>)'>Edit</button>
                    <button class="btn btn-sm btn-danger" 
                            onclick="confirmDelete(<?= $u['id'] ?>, '<?= htmlspecialchars($u['firstname'] . ' ' . $u['lastname']) ?>')">
                      Delete
                    </button>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>

          <nav>
            <ul class="pagination justify-content-center">
              <?php if ($page > 1): ?>
                <li class="page-item">
                  <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Previous</a>
                </li>
              <?php endif; ?>

              <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                  <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                </li>
              <?php endfor; ?>

              <?php if ($page < $totalPages): ?>
                <li class="page-item">
                  <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next</a>
                </li>
              <?php endif; ?>
            </ul>
          </nav>

        <?php else: ?>
          <div class="alert alert-info text-center">No users found.</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<!-- 🧩 Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Edit User Information</h5>
        <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="editUserForm">
        <div class="modal-body row g-3">
          <input type="hidden" name="id" id="editId">

          <div class="col-md-6">
            <label class="form-label">First Name</label>
            <input type="text" class="form-control" name="firstname" id="editFirstname" required>
          </div>

          <div class="col-md-6">
            <label class="form-label">Last Name</label>
            <input type="text" class="form-control" name="lastname" id="editLastname" required>
          </div>

          <div class="col-md-6">
            <label class="form-label">Email</label>
            <input type="email" class="form-control" name="email" id="editEmail" required>
          </div>

          <div class="col-md-6">
            <label class="form-label">Phone</label>
            <input type="text" class="form-control" name="phone" id="editPhone">
          </div>

          <div class="col-md-6">
            <label class="form-label">Account Number</label>
            <input type="text" class="form-control" name="account_number" id="editAccountNumber">
          </div>

          <div class="col-md-6">
            <label class="form-label">Account Balance</label>
            <input type="number" step="0.01" class="form-control" name="account_balance" id="editBalance">
          </div>

          <div class="col-md-6">
            <label class="form-label">Currency</label>
            <input type="text" class="form-control" name="currency" id="editCurrency" maxlength="5">
          </div>

          <div class="col-md-6">
            <label class="form-label">Transfer PIN</label>
            <input type="text" class="form-control" name="transfer_pin" id="editPin" maxlength="6">
          </div>

          <div class="col-md-6">
            <label class="form-label">Email Status</label>
            <select class="form-select" name="is_verified" id="editVerified">
              <option value="1">Verified</option>
              <option value="0">Unverified</option>
            </select>
          </div>
          
          
          <div class="col-md-6">
  <label class="form-label">Account Status</label>
  <select class="form-select" name="a_status" id="aStatus">
    <option value="active">Active</option>
    <option value="pending">Suspend </option>
  </select>
</div>

          <div class="col-md-6">
            <label class="form-label">Privilege</label>
            <select class="form-select" name="is_admin" id="editAdmin">
              <option value="0">User</option>
              <option value="1">Admin</option>
            </select>
          </div>


          <div class="col-md-6">
  <label class="form-label">Transaction Status (tstatus)</label>
  <select class="form-select" name="tr_status" id="editTrstatus">
    <option value="active">Active (Transactions go normally)</option>
    <option value="review">Review (Restrict / pending)</option>
  </select>
</div>

<div class="col-md-6">
  <label class="form-label">Auto Reverse</label>
  <select class="form-select" name="auto_reverse" id="editAutoReverse">
    <option value="0">Disabled (Normal Transfer)</option>
    <option value="1">Enabled (Hold & Auto-Reverse)</option>
  </select>
</div>

<div class="col-md-6">
  <label class="form-label">Card Request On Transfer</label>
  <select class="form-select" name="has_card" id="hasCard">
    <option value="0">Enabled (Request for card)</option>
    <option value="1">Disabled (No Card Request)</option>
  </select>
</div>



<div class="col-md-6">
  <label class="form-label">Card Number</label>
  <input type="text" class="form-control" name="card_number" id="cardNumber" maxlength="">
</div>


<div class="col-md-6">
  <label class="form-label">Card Status</label>
  <select class="form-select" name="card_status" id="cardStatus">
    <option value="None">None</option>
    <option value="Requested">Requested</option>
    <option value="Review">Review </option>
    <option value="Processing">Processing</option>
    <option value="Approved">Approved </option>
    <option value="Shipped">Shipped</option>
    <option value="Delivered">Delivered </option>
    <option value="Frozen">Frozen </option>
  </select>
</div>



<div class="col-md-6">
  <label class="form-label">OTP</label>
  <input type="text" class="form-control" name="otp" id="otp" maxlength="">
</div>




        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button class="btn btn-success" type="submit">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- 🗑️ Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title">Confirm Deletion</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to delete <strong id="deleteUserName"></strong>?</p>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-danger" id="confirmDeleteBtn">Delete</button>
      </div>
    </div>
  </div>
</div>




<!-- 🧩 Feedback Message Modal -->
<div class="modal fade" id="messageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title" id="messageModalLabel">System Message</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="messageModalBody"></div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
   
   
   
   

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
const editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
const messageModal = new bootstrap.Modal(document.getElementById('messageModal'));
let selectedUserId = null;

// ✅ OPEN EDIT MODAL
function openEditModal(user) {
  document.getElementById('editId').value = user.id;
  document.getElementById('editFirstname').value = user.firstname || '';
  document.getElementById('editLastname').value = user.lastname || '';
  document.getElementById('editEmail').value = user.email || '';
  document.getElementById('editPhone').value = user.phone || '';
  document.getElementById('editAccountNumber').value = user.account_number || '';
  document.getElementById('editBalance').value = user.account_balance || '';
  document.getElementById('editCurrency').value = user.currency || '';
  document.getElementById('editPin').value = user.transfer_pin || '';
  document.getElementById('editVerified').value = user.is_verified ? 1 : 0; 
  document.getElementById('editAdmin').value = user.is_admin ? 1 : 0;
  // set tstatus (string) and auto_reverse (0/1)
// document.getElementById('editTstatus').value = user.tstatus ?? 'review';
document.getElementById('editAutoReverse').value = (parseInt(user.auto_reverse) === 1) ? '1' : '0';
document.getElementById('hasCard').value = (parseInt(user.has_card) === 1) ? '1' : '0'; 

 document.getElementById('cardNumber').value = user.card_number || '';
 
 
document.getElementById('cardStatus').value = user.card_status ?? 'None';

document.getElementById('aStatus').value = user.a_status ?? 'active';

document.getElementById('editTrstatus').value = user.tr_status ?? 'active';

document.getElementById('otp').value = user.otp || '';

  editUserModal.show();
}

// ✅ CONFIRM DELETE
function confirmDelete(id, name) { 
  selectedUserId = id;
  document.getElementById('deleteUserName').textContent = name;
  deleteModal.show();
}

// ✅ DELETE USER
document.getElementById('confirmDeleteBtn').addEventListener('click', () => {
  if (!selectedUserId) return;

  fetch('../actions/delete_user?id=' + selectedUserId)
    .then(res => res.json())
    .then(data => {
      showMessage(data.status, data.message);
      if (data.status === 'success') {
        setTimeout(() => location.reload(), 1200);
      }
      deleteModal.hide();
    })
    .catch(() => showMessage('error', 'Error deleting user.'));
});

// ✅ EDIT FORM SUBMIT
const editForm = document.getElementById('editUserForm');
if (editForm) {
  editForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const fd = new FormData(editForm);
    const res = await fetch('../actions/update_user', { method: 'POST', body: fd });
    const data = await res.json();

    showMessage(data.status, data.message);

    if (data.status === 'success') {
      editUserModal.hide();
      setTimeout(() => location.reload(), 1200);
    }
  });
}

// ✅ SHOW MESSAGE USING MODAL
function showMessage(status, message) {
  const modalTitle = document.getElementById('messageModalLabel');
  const modalBody = document.getElementById('messageModalBody');

  if (status === 'success') {
    modalTitle.textContent = '✅ Success';
    modalBody.innerHTML = `<div class="alert alert-success mb-0">${message}</div>`;
  } else {
    modalTitle.textContent = '⚠️ Error';
    modalBody.innerHTML = `<div class="alert alert-danger mb-0">${message}</div>`;
  }

  messageModal.show();
}
</script>

</body>
</html>
