<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('Staff & Users')}"></head>
<body>
<nav th:replace="~{fragments/layout :: adminbar}"></nav>

<section>
    <div class="container">
        <div class="page-header">
            <h1>Staff &amp; Users</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openModal()">+ Add User</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="uSearch" type="text"
                   placeholder="Search name, username, email…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="uFilter" class="cars-search" style="min-width:140px" onchange="renderRows()">
                    <option value="">All roles</option>
                    <option value="ADMIN">Admin</option>
                    <option value="STAFF">Staff</option>
                </select>
                <span id="uCount" style="color:#888;font-size:13px"></span>
            </span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="fullName">Name</th><th data-sort="username">Username</th>
                    <th data-sort="email">Email</th><th data-sort="role">Role</th>
                    <th>Permissions</th><th data-sort="enabled">Status</th><th></th>
                </tr>
                </thead>
                <tbody id="uRows"><tr><td colspan="7" class="table-loading">Loading…</td></tr></tbody>
            </table>
        </div>
        <div class="pager" id="uPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="uModal">
    <div class="modal-card" style="max-width:660px">
        <div class="modal-head">
            <h2><span id="uTitle">Add User</span><span class="tag" id="uTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="uForm" onsubmit="return false">
                <input type="hidden" id="u_id"/>
                <div class="form-grid2">
                    <div class="form-group field"><label>Full name</label><input type="text" id="u_fullName"/></div>
                    <div class="form-group field">
                        <label>Username</label><input type="text" id="u_username"/>
                        <small class="fe" id="ue_username"></small>
                    </div>
                    <div class="form-group field"><label>Email</label><input type="email" id="u_email"/></div>
                    <div class="form-group field"><label>Phone</label><input type="tel" id="u_phone"/></div>
                    <div class="form-group field">
                        <label>Role</label>
                        <select id="u_role" onchange="roleChanged()">
                            <option value="STAFF">Staff</option>
                            <option value="ADMIN">Admin (full access)</option>
                        </select>
                    </div>
                    <div class="form-group field" id="u_pwWrap">
                        <label>Password</label><input type="password" id="u_password" placeholder="Min 6 characters"/>
                    </div>
                </div>

                <div id="permsBlock" style="margin-top:8px">
                    <label class="form-section-label">Permissions</label>
                    <div class="perm-grid">
                        <label class="perm-item" th:each="p : ${permissions}">
                            <input type="checkbox" class="perm-cb" th:value="${p}"/>
                            <span th:text="${#strings.capitalize(#strings.replace(#strings.toLowerCase(p), '_', ' '))}">Manage fleet</span>
                        </label>
                    </div>
                    <p id="adminNote" class="perm-note" style="display:none">Admins automatically have every permission.</p>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <button class="btn btn-ghost btn-sm" id="uPwBtn" type="button" onclick="resetPw()" style="display:none;margin-right:auto">Reset password</button>
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="uSaveBtn" type="button" onclick="save()">Save</button>
        </div>
    </div>
</div>

<div class="toast-wrap" id="toasts"></div>

<script th:inline="javascript">
/*<![CDATA[*/
const CSRF_TOKEN  = /*[[${_csrf.token}]]*/ '';
const CSRF_HEADER = /*[[${_csrf.headerName}]]*/ 'X-CSRF-TOKEN';
/*]]>*/
</script>
<script src="/js/admin-table.js"></script>
<script>
const API='/admin/api/users';
let ROWS=[];
const ST={sortKey:'fullName',sortDir:1,page:1,pageSize:12};
function esc(s){return (s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}

function load(){ fetch(API).then(r=>r.json()).then(d=>{ROWS=d;renderRows();})
  .catch(()=>{document.getElementById('uRows').innerHTML='<tr><td colspan="7" class="table-loading">Failed to load.</td></tr>';}); }

function renderRows(){
  const q=(document.getElementById('uSearch').value||'').toLowerCase();
  const f=document.getElementById('uFilter').value;
  let rows=ROWS.filter(u=>(!q||((u.fullName||'')+' '+(u.username||'')+' '+(u.email||'')).toLowerCase().includes(q)) && (!f||u.role===f));
  rows=AdminTable.sort(rows,ST.sortKey,ST.sortDir);
  document.getElementById('uCount').textContent=rows.length+' user'+(rows.length===1?'':'s');
  const tb=document.getElementById('uRows');
  if(!rows.length){tb.innerHTML='<tr><td colspan="7" class="table-loading">No users found.</td></tr>';document.getElementById('uPager').innerHTML='';return;}
  const pg=AdminTable.paginate(rows,ST.page,ST.pageSize);
  tb.innerHTML=pg.slice.map(u=>`
    <tr>
      <td>${esc(u.fullName)||'—'}</td>
      <td>${esc(u.username)}</td>
      <td>${esc(u.email)||'—'}</td>
      <td><span class="badge ${u.role==='ADMIN'?'badge-confirmed':''}">${esc(u.role)}</span></td>
      <td>${u.role==='ADMIN'?'<small style="color:#888">All</small>':(u.permissions.length?u.permissions.length+' granted':'<small style="color:#c0392b">none</small>')}</td>
      <td><span class="badge ${u.enabled?'badge-confirmed':'badge-cancelled'}">${u.enabled?'ACTIVE':'DISABLED'}</span></td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Edit" onclick="edit(${u.id})">&#9998;</button>
        <button class="icon-btn" title="${u.enabled?'Disable':'Enable'}" onclick="toggle(${u.id},${!u.enabled})">${u.enabled?'&#128683;':'&#10003;'}</button>
        <button class="icon-btn del" title="Delete" onclick="del(${u.id},'${esc(u.username)}')">&#128465;</button>
      </div></td>
    </tr>`).join('');
  ST.page=pg.page;
  AdminTable.pager(document.getElementById('uPager'),pg.page,pg.total,p=>{ST.page=p;renderRows();});
}

function setVal(id,v){const el=document.getElementById(id);if(el)el.value=(v==null?'':v);}
function setPerms(list){ document.querySelectorAll('.perm-cb').forEach(cb=>{ cb.checked=(list||[]).includes(cb.value); }); }
function getPerms(){ return Array.from(document.querySelectorAll('.perm-cb:checked')).map(cb=>cb.value); }
function clearErrors(){ document.querySelectorAll('#uForm .fe').forEach(e=>{e.classList.remove('show');e.textContent='';}); }
function roleChanged(){
  const isAdmin=document.getElementById('u_role').value==='ADMIN';
  document.getElementById('permsBlock').querySelector('.perm-grid').style.display=isAdmin?'none':'grid';
  document.getElementById('adminNote').style.display=isAdmin?'block':'none';
}

function openModal(){
  clearErrors(); document.getElementById('uForm').reset(); setVal('u_id','');
  document.getElementById('u_role').value='STAFF'; setPerms([]); roleChanged();
  document.getElementById('u_pwWrap').style.display='block';
  document.getElementById('uPwBtn').style.display='none';
  document.getElementById('uTitle').textContent='Add User';
  document.getElementById('uTag').style.display='none';
  document.getElementById('uModal').classList.add('open');
}
function edit(id){
  clearErrors();
  fetch(API+'/'+id).then(r=>r.json()).then(u=>{
    setVal('u_id',u.id); setVal('u_fullName',u.fullName); setVal('u_username',u.username);
    setVal('u_email',u.email); setVal('u_phone',u.phone); setVal('u_role',u.role);
    setPerms(u.permissions); roleChanged();
    document.getElementById('u_username').disabled=true;
    document.getElementById('u_pwWrap').style.display='none';
    document.getElementById('uPwBtn').style.display='inline-block';
    document.getElementById('uTitle').textContent='Edit User';
    document.getElementById('uTag').style.display='inline-block';
    document.getElementById('uModal').classList.add('open');
  });
}
function closeModal(){ document.getElementById('u_username').disabled=false; document.getElementById('uModal').classList.remove('open'); }
function sOrNull(id){const v=document.getElementById(id).value.trim();return v===''?null:v;}

function save(){
  clearErrors();
  const id=sOrNull('u_id');
  const payload={ id:id?Number(id):null, username:document.getElementById('u_username').value.trim(),
    fullName:sOrNull('u_fullName'), email:sOrNull('u_email'), phone:sOrNull('u_phone'),
    role:document.getElementById('u_role').value, password:sOrNull('u_password'),
    enabled:true, permissions:getPerms() };
  const btn=document.getElementById('uSaveBtn'); btn.disabled=true; btn.textContent='Saving…';
  const headers={'Content-Type':'application/json'}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API,{method:'POST',headers,body:JSON.stringify(payload)})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){closeModal();toast(id?'User updated':'User created','ok');load();}
      else toast(res.body.message||'Could not save','err'); })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{btn.disabled=false;btn.textContent='Save';});
}
function resetPw(){
  const id=document.getElementById('u_id').value;
  const pw=prompt('Enter a new password (min 6 characters):');
  if(!pw)return;
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/password?password='+encodeURIComponent(pw),{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok) toast('Password reset','ok'); else toast(res.body.message||'Failed','err'); })
    .catch(()=>toast('Network error','err'));
}
function toggle(id,enabled){
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/enabled?enabled='+enabled,{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){toast(enabled?'Enabled':'Disabled','ok');load();} else toast(res.body.message||'Failed','err'); })
    .catch(()=>toast('Network error','err'));
}
function del(id,name){
  if(!confirm('Delete user '+name+'?'))return;
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/delete',{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){toast('Deleted','ok');load();} else toast(res.body.message||'Could not delete','err'); })
    .catch(()=>toast('Network error','err'));
}
function toast(msg,kind){const t=document.createElement('div');t.className='toast '+(kind||'ok');t.textContent=msg;
  document.getElementById('toasts').appendChild(t);
  setTimeout(()=>{t.style.opacity='0';t.style.transition='opacity .3s';setTimeout(()=>t.remove(),300);},2600);}

document.getElementById('uModal').addEventListener('click',e=>{if(e.target.id==='uModal')closeModal();});
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeModal();});
AdminTable.attachSort(document.querySelector('.table-wrap thead tr'),ST,()=>{ST.page=1;renderRows();});
load();
</script>

<footer th:replace="~{fragments/layout :: footer}"></footer>
</body>
</html>
