<?php
session_start();
require_once 'db.php';

// Only allow admins
if (!isset($_SESSION['user_id']) || ($_SESSION['is_admin'] ?? 0) != 1) {
    header("Location: login.php");
    exit();
}

// Fetch users
$stmt = $conn->query("SELECT * FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Users - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="admin-sidebar.css">
<style>
body {
  font-family:'Segoe UI', sans-serif;
  background:#000;
  color:#fff;
  margin:0;
}

/* Buttons */
button {
  cursor:pointer;
  border:none;
  border-radius:6px;
  padding:8px 12px;
  color:#fff;
  background:#28a745;
  font-weight:bold;
  transition:0.3s;
}
button:hover { background:#218838; }

/* Table */
.user-table {
  width:100%;
  border-collapse: collapse;
  margin-top: 20px;
}
.user-table th, .user-table td {
  padding:12px;
  border-bottom:1px solid #333;
  text-align:left;
}
.user-table th { background:#111; }
.user-table td img { width:50px; height:50px; border-radius:50%; object-fit:cover; }

/* Mobile cards */
.mobile-list {
  display:none;
  flex-direction: column;
  gap:6px;
  padding:10px;
}
.mobile-list .user-card {
  background:#111;
  border-radius:6px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:6px 8px;
}
.mobile-list .user-card img {
  width:50px;
  height:50px;
  border-radius:50%;
  object-fit:cover;
  margin-right:10px;
}
.mobile-list .user-card .details {
  flex:1;
  min-width:0;
}
.mobile-list .user-card .details strong { display:block; font-size:0.9em; margin-bottom:3px; }
.mobile-list .user-card .actions button {
  background:#444;
  color:#fff;
  border:none;
  padding:4px 8px;
  border-radius:4px;
  margin-left:4px;
  font-size:0.85em;
  cursor:pointer;
}

/* Filter & Search */
.filter-search-container {
  display:flex;
  flex-wrap:wrap;
  gap:10px;
  margin-top:10px;
  align-items:center;
}
.filter-search-container input {
  padding:6px 10px;
  border-radius:6px;
  border:none;
  background:#222;
  color:#fff;
}
.filter-search-container input::placeholder { color:#aaa; }

/* Modals */
.modal {
  display:none;
  position:fixed;
  top:0; left:0;
  width:100%; height:100%;
  background:rgba(0,0,0,0.8);
  justify-content:center;
  align-items:center;
  z-index:2000;
}
.modal-content {
  background:#111;
  padding:20px;
  border-radius:8px;
  width:90%;
  max-width:500px;
  position:relative;
  color:#fff;
  max-height:90vh;
  overflow-y:auto;
}
.modal-close {
  position:absolute;
  top:10px; right:15px;
  font-size:18px;
  cursor:pointer;
}
.modal-content input, .modal-content select, .modal-content textarea {
  width:100%;
  margin-top:8px;
  padding:8px;
  border:none;
  border-radius:6px;
  background:#222;
  color:#fff;
}
.modal-content label { margin-top:10px; display:block; font-weight:bold; }

/* Toast */
#toast {
  position: fixed;
  top:20px;
  right:20px;
  background:#28a745;
  color:#fff;
  padding:12px 20px;
  border-radius:8px;
  box-shadow:0 4px 8px rgba(0,0,0,0.3);
  display:none;
  z-index:9999;
  font-weight:bold;
}

/* Responsive */
@media(max-width:768px){
  .user-table { display:none; }
  .mobile-list { display:flex; }
  .main-content { margin-left:0 !important; padding:10px; }
  .filter-search-container { width:100%; flex-wrap:wrap; }
}
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<?php include "admin-sidebar.php"; ?>

<div class="main-content">
  <h2>User Management</h2>
  <p>Welcome back, <?= $_SESSION['firstName'] ?? 'Admin' ?>. Here’s your user list.</p>
  
  <div class="filter-search-container">
    <input type="text" id="searchInput" placeholder="🔍 Search users...">
    <button onclick="openModal('addModal')"><i class="fas fa-plus"></i> Add User</button>
  </div>

  <!-- Desktop Table -->
  <table class="user-table" id="userTable">
    <thead>
      <tr>
        <th>#</th>
        <th>Profile</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Admin</th>
        <th>Created</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="tableBody">
      <?php foreach($users as $index=>$u): ?>
      <tr data-name="<?= htmlspecialchars(strtolower($u['firstName'].' '.$u['lastName'])) ?>" data-email="<?= htmlspecialchars(strtolower($u['email'])) ?>" data-phone="<?= htmlspecialchars($u['phone']) ?>">
        <td><?= $index+1 ?></td>
        <td><img src="<?= htmlspecialchars($u['profile_pic'] ?: 'images/default-user.png') ?>" alt=""></td>
        <td><?= htmlspecialchars($u['firstName']) ?></td>
        <td><?= htmlspecialchars($u['lastName']) ?></td>
        <td><?= htmlspecialchars($u['email']) ?></td>
        <td><?= htmlspecialchars($u['phone']) ?></td>
        <td><?= $u['is_admin'] ? 'Yes' : 'No' ?></td>
        <td><?= $u['created_at'] ?></td>
        <td>
          <button onclick="openEditModal(<?= $u['id'] ?>)">Edit</button>
          <button onclick="openDeleteModal(<?= $u['id'] ?>)">Delete</button>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <!-- Mobile Cards -->
  <div class="mobile-list" id="mobileList">
    <?php foreach($users as $u): ?>
    <div class="user-card" data-name="<?= htmlspecialchars(strtolower($u['firstName'].' '.$u['lastName'])) ?>" data-email="<?= htmlspecialchars(strtolower($u['email'])) ?>" data-phone="<?= htmlspecialchars($u['phone']) ?>">
      <img src="<?= htmlspecialchars($u['profile_pic'] ?: 'images/default-user.png') ?>" alt="">
      <div class="details">
        <strong><?= htmlspecialchars($u['firstName'].' '.$u['lastName']) ?></strong>
        <?= htmlspecialchars($u['email']) ?>
        <div>Phone: <?= htmlspecialchars($u['phone']) ?></div>
        <div>Admin: <?= $u['is_admin'] ? 'Yes' : 'No' ?></div>
      </div>
      <div class="actions">
        <button onclick="openEditModal(<?= $u['id'] ?>)">Edit</button>
        <button onclick="openDeleteModal(<?= $u['id'] ?>)">Delete</button>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<!-- Add User Modal -->
<div class="modal" id="addModal">
  <div class="modal-content">
    <span class="modal-close" onclick="closeModal('addModal')">&times;</span>
    <h3>Add User</h3>
    <form id="addForm" method="post" enctype="multipart/form-data" action="add-user.php">
      <label>First Name</label>
      <input type="text" name="firstName" required>
      <label>Last Name</label>
      <input type="text" name="lastName" required>
      <label>Email</label>
      <input type="email" name="email" required>
      <label>Phone</label>
      <input type="text" name="phone" required>
      <label>Password</label>
      <input type="password" name="password" required>
      <label>Profile Picture</label>
      <input type="file" name="profile_pic">
      <label>Admin</label>
      <select name="is_admin">
        <option value="0">No</option>
        <option value="1">Yes</option>
      </select>
      <button type="submit">Add User</button>
    </form>
  </div>
</div>

<!-- Edit User Modal -->
<div class="modal" id="editModal">
  <div class="modal-content" id="editContent">
    <span class="modal-close" onclick="closeModal('editModal')">&times;</span>
  </div>
</div>

<!-- Delete User Modal -->
<div class="modal" id="deleteModal">
  <div class="modal-content">
    <span class="modal-close" onclick="closeModal('deleteModal')">&times;</span>
    <h3>Confirm Delete?</h3>
    <p>Are you sure you want to delete this user?</p>
    <button id="confirmDeleteBtn">Yes, Delete</button>
    <button onclick="closeModal('deleteModal')">Cancel</button>
  </div>
</div>

<script>
// Modal helpers
function openModal(id){ document.getElementById(id).style.display='flex'; }
function closeModal(id){ document.getElementById(id).style.display='none'; }

// Users data
const users = <?= json_encode($users) ?>;

// Edit modal
function openEditModal(id){
  const u = users.find(x=>x.id==id);
  if(!u) return;
  const editContent = document.getElementById('editContent');
  editContent.innerHTML = `<span class="modal-close" onclick="closeModal('editModal')">&times;</span>
    <h3>Edit User</h3>
    <form id="editForm" method="post" enctype="multipart/form-data" action="edit-user.php">
      <input type="hidden" name="id" value="${u.id}">
      <label>First Name</label><input type="text" name="firstName" value="${u.firstName}" required>
      <label>Last Name</label><input type="text" name="lastName" value="${u.lastName}" required>
      <label>Email</label><input type="email" name="email" value="${u.email}" required>
      <label>Phone</label><input type="text" name="phone" value="${u.phone}" required>
      <label>Password (leave blank to keep)</label><input type="password" name="password">
      <label>Profile Picture</label><input type="file" name="profile_pic">
      <label>Admin</label>
      <select name="is_admin">
        <option value="0" ${u.is_admin==0?'selected':''}>No</option>
        <option value="1" ${u.is_admin==1?'selected':''}>Yes</option>
      </select>
      <button type="submit">Save Changes</button>
    </form>`;
  openModal('editModal');
}

// Delete modal
let deleteId = null;
function openDeleteModal(id){ deleteId=id; openModal('deleteModal'); }
document.getElementById('confirmDeleteBtn').addEventListener('click', ()=>{
  if(deleteId) window.location.href=`delete-user.php?id=${deleteId}`;
});

// Toast helper
function showToast(msg, duration=3000){
    const toast = document.getElementById('toast');
    toast.textContent = msg;
    toast.style.display = 'block';
    setTimeout(()=>{ toast.style.display='none'; }, duration);
}
const urlParams = new URLSearchParams(window.location.search);
if(urlParams.get('added')==='1'){ showToast('User Added!'); }
if(urlParams.get('updated')==='1'){ showToast('Changes Saved!'); }

// Search filter
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', applyFilters);

function applyFilters(){
  const search = searchInput.value.toLowerCase();
  document.querySelectorAll('#tableBody tr').forEach(row=>{
    const name = row.dataset.name;
    const email = row.dataset.email;
    const phone = row.dataset.phone;
    row.style.display = (name.includes(search) || email.includes(search) || phone.includes(search)) ? '' : 'none';
  });
  document.querySelectorAll('#mobileList .user-card').forEach(card=>{
    const name = card.dataset.name;
    const email = card.dataset.email;
    const phone = card.dataset.phone;
    card.style.display = (name.includes(search) || email.includes(search) || phone.includes(search)) ? '' : 'none';
  });
}
</script>

</body>
</html>
