<?php use App\Helpers\Helper; ?>
<div class="d-flex justify-content-between align-items-center mb-4">
  <h1 class="admin-page-title">System Users</h1>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal"><i class="bi bi-person-plus me-1"></i>Add User</button>
</div>
<div class="data-card">
  <div class="table-responsive">
    <table class="table mb-0">
      <thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead>
      <tbody>
        <?php foreach ($users as $u): ?>
        <tr>
          <td>
            <div class="d-flex align-items-center gap-2">
              <div class="avatar-sm bg-primary d-flex align-items-center justify-content-center text-white fw-700 rounded-circle">
                <?= strtoupper(substr($u['first_name'],0,1)) ?>
              </div>
              <div class="fw-600 small"><?= Helper::e($u['first_name'].' '.$u['last_name']) ?></div>
            </div>
          </td>
          <td class="small"><?= Helper::e($u['email']) ?></td>
          <td class="small"><?= Helper::e($u['phone']??'—') ?></td>
          <td><?php
            $rc = ['super_admin'=>'danger','property_owner'=>'primary','property_manager'=>'info','accountant'=>'success','receptionist'=>'warning','tenant'=>'secondary'][$u['role_name']??''] ?? 'primary';
          ?><span class="badge bg-<?= $rc ?> text-white"><?= Helper::e($u['role_display']) ?></span></td>
          <td><?= Helper::statusBadge($u['status']) ?></td>
          <td class="small text-muted"><?= Helper::date($u['created_at']) ?></td>
          <td>
            <div class="d-flex gap-1">
              <?php $isSuperAdmin = ((int)($u['role_id'] ?? 0) === 1); ?>
              <a href="<?= APP_URL ?>/admin/users/<?= $u['id'] ?>/edit" class="btn btn-action btn-outline-primary" title="Edit"><i class="bi bi-pencil"></i></a>
              <button class="btn btn-action btn-outline-warning" title="Reset Password" onclick="openResetPwd(<?= $u['id'] ?>, '<?= Helper::e($u['first_name'].' '.$u['last_name']) ?>')"><i class="bi bi-key"></i></button>
              <?php if (!$isSuperAdmin && $u['id'] != ($_SESSION['user_id']??0)): ?>
              <form method="POST" action="<?= APP_URL ?>/admin/users/<?= $u['id'] ?>/delete" class="form-delete d-inline">
                <?= Helper::csrf() ?>
                <button class="btn btn-action btn-outline-danger" title="Deactivate"><i class="bi bi-person-dash"></i></button>
              </form>
              <?php elseif ($isSuperAdmin): ?>
              <span class="btn btn-action btn-outline-secondary disabled" title="Protected" style="cursor:not-allowed"><i class="bi bi-shield-lock"></i></span>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Reset Password Modal -->
<div class="modal fade" id="resetPwdModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header" style="background:linear-gradient(135deg,#1a3c5e,#2d6a9f);color:#fff">
        <h5 class="modal-title fw-700"><i class="bi bi-key me-2"></i>Reset Password</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" id="resetPwdForm">
        <?= Helper::csrf() ?>
        <input type="hidden" name="_reset_password" value="1">
        <div class="modal-body p-4">
          <p class="text-muted small mb-3">Set a new password for <strong id="resetPwdName"></strong>.</p>
          <div class="mb-3">
            <label class="form-label fw-600">New Password <span class="text-danger">*</span></label>
            <div class="input-group">
              <input type="password" name="password" id="resetPwdInput" class="form-control" minlength="8" required placeholder="Min. 8 characters">
              <button type="button" class="btn btn-outline-secondary" onclick="togglePwd()"><i class="bi bi-eye" id="resetPwdEye"></i></button>
            </div>
          </div>
          <div class="mb-0">
            <label class="form-label fw-600">Confirm Password <span class="text-danger">*</span></label>
            <input type="password" name="password_confirm" id="resetPwdConfirm" class="form-control" minlength="8" required placeholder="Repeat password">
          </div>
          <div id="resetPwdError" class="alert alert-danger py-2 mt-3 mb-0" style="display:none"></div>
        </div>
        <div class="modal-footer bg-light">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-warning px-4"><i class="bi bi-key me-2"></i>Reset Password</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function openResetPwd(id, name) {
  document.getElementById('resetPwdForm').action = '<?= APP_URL ?>/admin/users/' + id;
  document.getElementById('resetPwdName').textContent = name;
  document.getElementById('resetPwdInput').value = '';
  document.getElementById('resetPwdConfirm').value = '';
  document.getElementById('resetPwdError').style.display = 'none';
  new bootstrap.Modal(document.getElementById('resetPwdModal')).show();
}
function togglePwd() {
  const inp = document.getElementById('resetPwdInput');
  const eye = document.getElementById('resetPwdEye');
  inp.type = inp.type === 'password' ? 'text' : 'password';
  eye.className = inp.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}
document.getElementById('resetPwdForm').addEventListener('submit', function(e) {
  const pwd  = document.getElementById('resetPwdInput').value;
  const conf = document.getElementById('resetPwdConfirm').value;
  const err  = document.getElementById('resetPwdError');
  if (pwd !== conf) {
    e.preventDefault();
    err.style.display = '';
    err.textContent = 'Passwords do not match.';
    return;
  }
  if (pwd.length < 8) {
    e.preventDefault();
    err.style.display = '';
    err.textContent = 'Password must be at least 8 characters.';
    return;
  }
  err.style.display = 'none';
});
</script>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title fw-700">Add System User</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form method="POST" action="<?= APP_URL ?>/admin/users">
        <?= Helper::csrf() ?>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-6"><label class="form-label">First Name</label><input type="text" name="first_name" class="form-control" required></div>
            <div class="col-6"><label class="form-label">Last Name</label><input type="text" name="last_name" class="form-control" required></div>
            <div class="col-12"><label class="form-label">Email</label><input type="email" name="email" class="form-control" required></div>
            <div class="col-12"><label class="form-label">Phone</label><input type="tel" name="phone" class="form-control"></div>
            <div class="col-12"><label class="form-label">Role</label>
              <select name="role_id" class="form-select" required>
                <?php foreach ($roles as $r): ?><option value="<?= $r['id'] ?>"><?= Helper::e($r['display_name']) ?></option><?php endforeach; ?>
              </select>
            </div>
            <div class="col-12"><label class="form-label">Password</label><input type="password" name="password" class="form-control" required minlength="8"></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary">Add User</button>
        </div>
      </form>
    </div>
  </div>
</div>
