{% extends "admin_base.html" %}
{% block title %}Roles &amp; Permissions | Nexora Admin{% endblock %}
{% block content %}
<div class="admin-head">
  <p class="eyebrow">Access Control</p>
  <h1>Roles &amp; Permissions</h1>
  <p>Define roles, assign permissions, and manage users per role.</p>
</div>

{# ── CREATE ROLE ── #}
<section class="admin-panel roles-panel roles-create-section">
  <h2><i class="fas fa-plus"></i> Create Role</h2>
  <form method="post" class="roles-create-form" data-role-form>
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <div class="roles-create-fields">
      <label>Role Name<input name="name" required maxlength="80" placeholder="e.g. Check-in Staff"></label>
      <label>Description<input name="description" maxlength="180" placeholder="Short description of this role"></label>
    </div>

    {# ── ASSIGN USERS SEARCHABLE PICKER ── #}
    <div class="assign-users-section">
      <h3 class="perm-group-title"><i class="fas fa-users"></i> Assign Users</h3>
      <p class="assign-users-hint">Search staff accounts by name or username. Users already assigned to another role will be moved to this new role.</p>
      <div class="user-picker" data-user-picker>
        <div class="user-picker-input-wrap">
          <i class="fas fa-magnifying-glass"></i>
          <input type="text" class="user-picker-search" placeholder="Type to search staff accounts..." data-user-search autocomplete="off">
          <button type="button" class="user-picker-clear" data-user-clear title="Clear"><i class="fas fa-xmark"></i></button>
        </div>
        <div class="user-picker-dropdown" data-user-dropdown hidden>
          {% for u in all_users %}
          <div class="user-picker-opt" data-user-opt data-uid="{{ u.id }}" data-uname="{{ u.username|lower }}" data-unamefull="{{ (u.full_name or u.username)|lower }}">
            <span class="user-picker-avatar"><i class="fas fa-user"></i></span>
            <span class="user-picker-info">
              <strong>{{ u.full_name or u.username }}</strong>
              <small>@{{ u.username }}</small>
            </span>
            {% if u.role_id %}
            <span class="user-picker-already"><i class="fas fa-link"></i> Has role</span>
            {% endif %}
          </div>
          {% endfor %}
          <div class="user-picker-empty" data-user-empty hidden>No matching accounts found.</div>
        </div>
        <div class="user-picker-selected" data-user-selected></div>
      </div>
    </div>

    {% 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 %}

    <button class="btn primary" type="submit"><i class="fas fa-user-shield"></i> Create Role</button>
  </form>
</section>

{# ── EXISTING ROLES ── #}
{% for role in roles %}
{% set rp = role_permissions[role.id] %}
{% set ru = role_users[role.id] %}
<section class="admin-panel roles-panel role-block">
  <div class="role-head">
    <div class="role-id-block">
      <h2>
        <i class="fas fa-shield-halved"></i>
        {{ role.name }}
      </h2>
      {% if role.description %}<p class="role-desc">{{ role.description }}</p>{% endif %}
      <div class="role-meta">
        <span class="role-chip"><i class="fas fa-key"></i> {{ rp|length }} of {{ permission_labels|length }} permissions</span>
        <span class="role-chip role-member-chip"><i class="fas fa-users"></i> {{ ru|length }} user{{ '' if ru|length == 1 else 's' }}</span>
      </div>
    </div>
    <div class="role-actions">
      <button type="button" class="act-btn act-edit"
        data-open-role-edit data-id="{{ role.id }}"
        data-name="{{ role.name }}" data-description="{{ role.description or '' }}">
        <i class="fas fa-pen"></i> Edit
      </button>
      <button type="button" class="act-btn act-delete"
        data-open-role-del data-id="{{ role.id }}" data-name="{{ role.name }}">
        <i class="fas fa-trash"></i> Delete
      </button>
    </div>
  </div>

  {% if ru %}
  <div class="role-assigned-users">
    <span class="role-assigned-label"><i class="fas fa-users"></i> Assigned Users:</span>
    <div class="role-assigned-list">
      {% for u in ru %}
      <span class="role-assigned-chip">
        <i class="fas fa-user"></i> {{ u.full_name or u.username }}
        <small>@{{ u.username }}</small>
      </span>
      {% endfor %}
    </div>
  </div>
  {% else %}
  <div class="role-assigned-users role-assigned-empty">
    <span class="role-assigned-label"><i class="fas fa-user-slash"></i> No users assigned to this role yet.</span>
  </div>
  {% endif %}

  <form method="post" action="{{ url_for('update_role_permissions', role_id=role.id) }}" data-role-form>
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    {% 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 }}" {% if key in rp %}checked{% endif %}>
          <span class="perm-box"><i class="fas fa-check"></i></span>
          <span class="perm-text">{{ permission_labels[key] }}</span>
        </label>
        {% endfor %}
      </div>
    </div>
    {% endfor %}
    <button class="btn primary role-save" type="submit"><i class="fas fa-floppy-disk"></i> Save Permissions</button>
  </form>
</section>
{% endfor %}

{# ── AUDIT LOG ── #}
<section class="admin-panel">
  <h2><i class="fas fa-clipboard-list"></i> Role Change Audit</h2>
  <div class="admin-table-wrap audit-wrap">
    <table class="audit-table">
      <thead><tr><th>Time</th><th>Actor</th><th>Action</th><th>Target</th><th>Details</th></tr></thead>
      <tbody>
        {% for item in audit %}
        <tr>
          <td data-label="Time">{{ item.created_at|pretty_dt }}</td>
          <td data-label="Actor"><strong>{{ item.actor_username }}</strong></td>
          <td data-label="Action"><span class="badge neutral audit-action">{{ item.action }}</span></td>
          <td data-label="Target">{{ item.target_username or '—' }}</td>
          <td data-label="Details"><span class="audit-details">{{ item.details or '—' }}</span></td>
        </tr>
        {% else %}
        <tr><td colspan="5">No role changes recorded.</td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</section>

{# ── EDIT ROLE MODAL ── #}
<div class="nx-modal" id="roleEditModal" hidden>
  <div class="nx-modal-card" role="dialog" aria-modal="true">
    <div class="nx-modal-head">
      <h3><i class="fas fa-pen"></i> Edit Role</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="roleEditForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <div class="nx-modal-body">
        <label>Role Name<input name="name" id="reName" required maxlength="80"></label>
        <label>Description<input name="description" id="reDesc" maxlength="180"></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>

{# ── DELETE ROLE MODAL ── #}
<div class="nx-modal" id="roleDelModal" hidden>
  <div class="nx-modal-card nx-danger" role="dialog" aria-modal="true">
    <div class="nx-modal-head">
      <h3><i class="fas fa-triangle-exclamation"></i> Delete Role?</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="roleDelForm">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <div class="nx-modal-body">
        <p class="nx-modal-note">You are about to delete <strong id="rdName"></strong>. Staff assigned to it will be left with no role, and all its permissions will be removed. 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 Role</button>
      </div>
    </form>
  </div>
</div>

<script>
(function () {
  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-toggle-section]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      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-role-edit]').forEach(function (b) {
    b.addEventListener('click', function () {
      document.getElementById('reName').value = b.dataset.name;
      document.getElementById('reDesc').value = b.dataset.description;
      document.getElementById('roleEditForm').action = '/admin/roles/' + b.dataset.id + '/edit';
      open('roleEditModal');
    });
  });

  document.querySelectorAll('[data-open-role-del]').forEach(function (b) {
    b.addEventListener('click', function () {
      document.getElementById('rdName').textContent = b.dataset.name;
      document.getElementById('roleDelForm').action = '/admin/roles/' + b.dataset.id + '/delete';
      open('roleDelModal');
    });
  });

  /* ── USER PICKER ── */
  var picker = document.querySelector('[data-user-picker]');
  if (!picker) return;
  var searchInput = picker.querySelector('[data-user-search]');
  var dropdown = picker.querySelector('[data-user-dropdown]');
  var selectedWrap = picker.querySelector('[data-user-selected]');
  var emptyMsg = picker.querySelector('[data-user-empty]');
  var clearBtn = picker.querySelector('[data-user-clear]');
  var opts = picker.querySelectorAll('[data-user-opt]');
  var selectedIds = {};

  function renderSelected() {
    selectedWrap.innerHTML = '';
    Object.keys(selectedIds).forEach(function (uid) {
      var info = selectedIds[uid];
      var chip = document.createElement('span');
      chip.className = 'user-picker-chip';
      chip.innerHTML = '<i class="fas fa-user"></i> ' + info.label + ' <button type="button" data-remove-uid="' + uid + '"><i class="fas fa-xmark"></i></button>';
      selectedWrap.appendChild(chip);
    });
    selectedWrap.querySelectorAll('[data-remove-uid]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        delete selectedIds[btn.dataset.removeUid];
        renderSelected();
      });
    });
  }

  function filterOpts(query) {
    var q = query.toLowerCase().trim();
    var found = 0;
    opts.forEach(function (o) {
      var match = !q || o.dataset.uname.indexOf(q) !== -1 || o.dataset.unamefull.indexOf(q) !== -1;
      o.style.display = match ? '' : 'none';
      if (match) found++;
    });
    emptyMsg.hidden = found > 0;
  }

  searchInput.addEventListener('focus', function () {
    dropdown.hidden = false;
    filterOpts(searchInput.value);
  });

  searchInput.addEventListener('input', function () {
    dropdown.hidden = false;
    filterOpts(searchInput.value);
  });

  clearBtn.addEventListener('click', function () {
    searchInput.value = '';
    filterOpts('');
    searchInput.focus();
  });

  opts.forEach(function (o) {
    o.addEventListener('click', function () {
      var uid = o.dataset.uid;
      if (selectedIds[uid]) {
        delete selectedIds[uid];
      } else {
        var uname = o.querySelector('.user-picker-info small').textContent.replace('@', '');
        var fname = o.querySelector('.user-picker-info strong').textContent;
        selectedIds[uid] = { label: fname + ' (@' + uname + ')' };
      }
      renderSelected();
      searchInput.value = '';
      filterOpts('');
      searchInput.focus();
    });
  });

  document.addEventListener('click', function (e) {
    if (!picker.contains(e.target)) {
      dropdown.hidden = true;
    }
  });

  var origSubmit = picker.closest('form');
  if (origSubmit) {
    origSubmit.addEventListener('submit', function () {
      Object.keys(selectedIds).forEach(function (uid) {
        var h = document.createElement('input');
        h.type = 'hidden';
        h.name = 'assign_users';
        h.value = uid;
        origSubmit.appendChild(h);
      });
    });
  }
}());
</script>
{% endblock %}
