{% extends "admin_base.html" %}
{% block title %}Staff Users | Nexora Admin{% endblock %}
{% block content %}
<div class="admin-head">
  <p class="eyebrow">Access Control</p>
  <h1>Staff Users</h1>
  <p>Create staff accounts, assign roles, and grant additional permissions per user.</p>
</div>

<section class="admin-panel users-create-panel">
  <h2><i class="fas fa-user-plus"></i> Create Staff User</h2>
  <form method="post" class="users-create-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div class="users-create-grid">
      <label>Full Name<input name="full_name" maxlength="100" placeholder="e.g. Muhammad Huzaifa"></label>
      <label>Username<input name="username" required maxlength="60" autocomplete="off" placeholder="e.g. huzaifa.haider"></label>
      <label>Password<input name="password" required type="password" minlength="8" autocomplete="new-password" placeholder="Min 8 characters"></label>
      <label>Role
        <select name="role_id" required>
          <option value="">Select role</option>
          {% for role in roles %}<option value="{{ role.id }}">{{ role.name }}</option>{% endfor %}
        </select>
      </label>
    </div>
    <button class="btn primary" type="submit"><i class="fas fa-user-plus"></i> Create Staff User</button>
  </form>
</section>

<section class="admin-panel users-list-panel">
  <h2><i class="fas fa-users-gear"></i> Staff Accounts</h2>

  {% if users %}
  <div class="admin-table-wrap users-table-wrap">
    <table class="users-table">
      <thead><tr><th>Name</th><th>Username</th><th>Role</th><th>Extra Perms</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
        {% for user in users %}
        <tr data-user-row="{{ user.id }}">
          <td data-label="Name"><strong class="u-name">{{ user.full_name or '—' }}</strong></td>
          <td data-label="Username"><span class="u-username">{{ user.username }}</span></td>
          <td data-label="Role"><span class="u-role">{{ user.role_name or 'No role' }}</span></td>
          <td data-label="Extra Perms">
            {% set up = user_permissions.get(user.id, []) %}
            {% if up %}
            <span class="badge perm-badge-extra" title="{{ up|join(', ') }}">
              <i class="fas fa-key"></i> {{ up|length }} direct perm{{ '' if up|length == 1 else 's' }}
            </span>
            {% else %}
            <span class="perm-none-label">None</span>
            {% endif %}
          </td>
          <td data-label="Status"><span class="badge {{ 'st-active' if user.active else 'st-disabled' }}">{{ 'Active' if user.active else 'Disabled' }}</span></td>
          <td data-label="Actions" class="user-actions">
            <button type="button" class="act-btn act-edit"
              data-open-edit
              data-id="{{ user.id }}"
              data-fullname="{{ user.full_name or '' }}"
              data-username="{{ user.username }}"
              data-role="{{ user.role_id or '' }}"
              data-active="{{ 1 if user.active else 0 }}">
              <i class="fas fa-pen"></i> Edit
            </button>

            <button type="button" class="act-btn act-perms"
              data-open-perms data-id="{{ user.id }}" data-username="{{ user.username }}">
              <i class="fas fa-key"></i> Permissions
            </button>

            <form method="post" action="{{ url_for('toggle_admin_user', user_id=user.id) }}">
              <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
              <button type="submit" class="act-btn {{ 'act-disable' if user.active else 'act-enable' }}">
                <i class="fas fa-power-off"></i> {{ 'Disable' if user.active else 'Enable' }}
              </button>
            </form>

            <button type="button" class="act-btn act-reset"
              data-open-pw data-id="{{ user.id }}" data-username="{{ user.username }}">
              <i class="fas fa-key"></i> Reset Password
            </button>

            <button type="button" class="act-btn act-delete"
              data-open-del data-id="{{ user.id }}" data-username="{{ user.username }}">
              <i class="fas fa-trash"></i> Delete
            </button>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% else %}
  <div class="empty users-empty">
    <i class="fas fa-user-shield"></i>
    <strong>No Staff Users Yet</strong>
    <p>Create your first staff account to manage tournament operations.</p>
  </div>
  {% endif %}
</section>

{# ── EDIT MODAL ── #}
<div class="nx-modal" id="editModal" hidden>
  <div class="nx-modal-card" role="dialog" aria-modal="true" aria-labelledby="editTitle">
    <div class="nx-modal-head">
      <h3 id="editTitle"><i class="fas fa-pen"></i> Edit Staff User</h3>
      <button type="button" class="nx-modal-x" data-close-modal aria-label="Close"><i class="fas fa-xmark"></i></button>
    </div>
    <form method="post" action="" id="editForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <input type="hidden" name="user_id" id="editId">
      <div class="nx-modal-body">
        <label>Full Name<input name="full_name" id="editFullName" maxlength="100"></label>
        <label>Username<input name="username" id="editUsername" required maxlength="60" autocomplete="off"></label>
        <label>Role
          <select name="role_id" id="editRole" required>
            <option value="">Select role</option>
            {% for role in roles %}<option value="{{ role.id }}">{{ role.name }}</option>{% endfor %}
          </select>
        </label>
        <label class="check nx-check"><input type="checkbox" name="active" id="editActive"> Account Active</label>
      </div>
      <div class="nx-modal-actions">
        <button type="button" class="btn outline small" data-close-modal>Cancel</button>
        <button type="submit" class="btn primary small"><i class="fas fa-floppy-disk"></i> Save Changes</button>
      </div>
    </form>
  </div>
</div>

{# ── PERMISSIONS MODAL ── #}
<div class="nx-modal" id="permsModal" hidden>
  <div class="nx-modal-card nx-modal-wide" role="dialog" aria-modal="true" aria-labelledby="permsTitle">
    <div class="nx-modal-head">
      <h3 id="permsTitle"><i class="fas fa-key"></i> Direct Permissions — <span id="permsUsername"></span></h3>
      <button type="button" class="nx-modal-x" data-close-modal aria-label="Close"><i class="fas fa-xmark"></i></button>
    </div>
    <form method="post" action="" id="permsForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <div class="nx-modal-body">
        <p class="nx-modal-note">These are <strong>additional</strong> permissions granted directly to this user on top of their role. Use this to give specific access without changing the role for everyone.</p>
        {% for heading, keys in permission_sections %}
        <div class="perm-group">
          <div class="perm-group-header">
            <h3 class="perm-group-title">{{ heading }}</h3>
            <button type="button" class="perm-toggle-all" data-toggle-section="{{ heading }}">
              <i class="fas fa-check-double"></i> Select All
            </button>
          </div>
          <div class="perm-grid">
            {% for key in keys %}
            <label class="perm-card">
              <input type="checkbox" name="permissions" value="{{ key }}">
              <span class="perm-box"><i class="fas fa-check"></i></span>
              <span class="perm-text">{{ permission_labels[key] }}</span>
            </label>
            {% endfor %}
          </div>
        </div>
        {% endfor %}
      </div>
      <div class="nx-modal-actions">
        <button type="button" class="btn outline small" data-close-modal>Cancel</button>
        <button type="submit" class="btn primary small"><i class="fas fa-floppy-disk"></i> Save Direct Permissions</button>
      </div>
    </form>
  </div>
</div>

{# ── RESET PASSWORD MODAL ── #}
<div class="nx-modal" id="pwModal" hidden>
  <div class="nx-modal-card" role="dialog" aria-modal="true" aria-labelledby="pwTitle">
    <div class="nx-modal-head">
      <h3 id="pwTitle"><i class="fas fa-key"></i> Reset Password</h3>
      <button type="button" class="nx-modal-x" data-close-modal aria-label="Close"><i class="fas fa-xmark"></i></button>
    </div>
    <form method="post" action="" id="pwForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <input type="hidden" name="user_id" id="pwId">
      <div class="nx-modal-body">
        <p class="nx-modal-note">Set a new password for <strong id="pwUsername"></strong>. The existing password is never displayed. Minimum 8 characters.</p>
        <label>New Password<input type="password" name="new_password" required minlength="8" autocomplete="new-password" placeholder="Min 8 characters"></label>
      </div>
      <div class="nx-modal-actions">
        <button type="button" class="btn outline small" data-close-modal>Cancel</button>
        <button type="submit" class="btn primary small"><i class="fas fa-key"></i> Reset Password</button>
      </div>
    </form>
  </div>
</div>

{# ── DELETE CONFIRM MODAL ── #}
<div class="nx-modal" id="delModal" hidden>
  <div class="nx-modal-card nx-danger" role="dialog" aria-modal="true" aria-labelledby="delTitle">
    <div class="nx-modal-head">
      <h3 id="delTitle"><i class="fas fa-triangle-exclamation"></i> Delete Staff User?</h3>
      <button type="button" class="nx-modal-x" data-close-modal aria-label="Close"><i class="fas fa-xmark"></i></button>
    </div>
    <form method="post" action="" id="delForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <input type="hidden" name="user_id" id="delId">
      <div class="nx-modal-body">
        <p class="nx-modal-note">You are about to permanently remove <strong id="delUsername"></strong>. This action cannot be undone.</p>
      </div>
      <div class="nx-modal-actions">
        <button type="button" class="btn outline small" data-close-modal>Cancel</button>
        <button type="submit" class="btn danger small"><i class="fas fa-trash"></i> Delete User</button>
      </div>
    </form>
  </div>
</div>

<script>
(function () {
  var userPerms = {{ user_permissions | tojson }};

  function open(id) { document.getElementById(id).hidden = false; }
  function close(m) { m.hidden = true; }
  document.querySelectorAll('[data-close-modal]').forEach(function (b) {
    b.addEventListener('click', function () { close(b.closest('.nx-modal')); });
  });
  document.querySelectorAll('.nx-modal').forEach(function (m) {
    m.addEventListener('click', function (e) { if (e.target === m) close(m); });
  });
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') document.querySelectorAll('.nx-modal:not([hidden])').forEach(close);
  });

  document.querySelectorAll('[data-open-edit]').forEach(function (b) {
    b.addEventListener('click', function () {
      document.getElementById('editId').value = b.dataset.id;
      document.getElementById('editFullName').value = b.dataset.fullname;
      document.getElementById('editUsername').value = b.dataset.username;
      document.getElementById('editRole').value = b.dataset.role || '';
      document.getElementById('editActive').checked = b.dataset.active === '1';
      document.getElementById('editForm').action = '/admin/users/' + b.dataset.id + '/edit';
      open('editModal');
    });
  });

  document.querySelectorAll('[data-open-perms]').forEach(function (b) {
    b.addEventListener('click', function () {
      var uid = parseInt(b.dataset.id);
      document.getElementById('permsUsername').textContent = b.dataset.username;
      document.getElementById('permsForm').action = '/admin/users/' + b.dataset.id + '/permissions';
      var existing = userPerms[uid] || [];
      document.querySelectorAll('#permsForm input[type="checkbox"]').forEach(function (cb) {
        cb.checked = existing.indexOf(cb.value) !== -1;
      });
      open('permsModal');
    });
  });

  document.querySelectorAll('[data-toggle-section]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var sectionName = btn.dataset.toggleSection;
      var section = btn.closest('.perm-group');
      var cbs = section.querySelectorAll('.perm-grid input[type="checkbox"]');
      var allChecked = Array.prototype.every.call(cbs, function (c) { return c.checked; });
      cbs.forEach(function (cb) { cb.checked = !allChecked; });
      btn.innerHTML = allChecked
        ? '<i class="fas fa-check-double"></i> Select All'
        : '<i class="fas fa-times"></i> Deselect All';
    });
  });

  document.querySelectorAll('[data-open-pw]').forEach(function (b) {
    b.addEventListener('click', function () {
      document.getElementById('pwId').value = b.dataset.id;
      document.getElementById('pwUsername').textContent = b.dataset.username;
      document.getElementById('pwForm').action = '/admin/users/' + b.dataset.id + '/reset-password';
      open('pwModal');
    });
  });

  document.querySelectorAll('[data-open-del]').forEach(function (b) {
    b.addEventListener('click', function () {
      document.getElementById('delId').value = b.dataset.id;
      document.getElementById('delUsername').textContent = b.dataset.username;
      document.getElementById('delForm').action = '/admin/users/' + b.dataset.id + '/delete';
      open('delModal');
    });
  });
}());
</script>
{% endblock %}
