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

<section class="dash">
    <div class="container">
        <div class="settings-page" style="max-width:1080px">

            <div class="page-head" style="display:flex;justify-content:space-between;align-items:flex-end;flex-wrap:wrap;gap:12px">
                <div>
                    <h1>Category Masters</h1>
                    <p>Vehicle, driver &amp; customer categories used across the system.</p>
                </div>
                <div style="display:flex;gap:10px;align-items:center">
                    <input class="cars-search" id="catSearch" type="text" placeholder="Search categories…" oninput="renderAll()"/>
                    <a class="btn btn-ghost btn-sm" th:href="@{/admin/settings}">&larr; Settings</a>
                </div>
            </div>

            <div class="cat-grid">
                <!-- VEHICLE -->
                <div class="settings-card">
                    <div class="settings-card-head">
                        <span class="ic">&#128663;</span>
                        <div><h2>Vehicle <span class="cat-count" id="count-VEHICLE">0</span></h2><p>Hatchback, Sedan, SUV…</p></div>
                    </div>
                    <div class="cat-card-body" id="list-VEHICLE"></div>
                    <div class="cat-add">
                        <input type="text" id="in-VEHICLE" placeholder="New vehicle category" onkeydown="if(event.key==='Enter')addCat('VEHICLE')"/>
                        <button class="btn btn-primary btn-sm" type="button" onclick="addCat('VEHICLE')">Add</button>
                    </div>
                </div>

                <!-- DRIVER -->
                <div class="settings-card">
                    <div class="settings-card-head">
                        <span class="ic blue">&#128100;</span>
                        <div><h2>Driver <span class="cat-count" id="count-DRIVER">0</span></h2><p>Standard, Premium, Chauffeur…</p></div>
                    </div>
                    <div class="cat-card-body" id="list-DRIVER"></div>
                    <div class="cat-add">
                        <input type="text" id="in-DRIVER" placeholder="New driver category" onkeydown="if(event.key==='Enter')addCat('DRIVER')"/>
                        <button class="btn btn-primary btn-sm" type="button" onclick="addCat('DRIVER')">Add</button>
                    </div>
                </div>

                <!-- CUSTOMER -->
                <div class="settings-card">
                    <div class="settings-card-head">
                        <span class="ic green">&#129489;</span>
                        <div><h2>Customer <span class="cat-count" id="count-CUSTOMER">0</span></h2><p>Individual, Company, Corporate…</p></div>
                    </div>
                    <div class="cat-card-body" id="list-CUSTOMER"></div>
                    <div class="cat-add">
                        <input type="text" id="in-CUSTOMER" placeholder="New customer category" onkeydown="if(event.key==='Enter')addCat('CUSTOMER')"/>
                        <button class="btn btn-primary btn-sm" type="button" onclick="addCat('CUSTOMER')">Add</button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</section>

<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>
const API='/admin/api/categories';
const TYPES=['VEHICLE','DRIVER','CUSTOMER'];
let CATS=[];
function esc(s){ return (s==null?'':String(s)).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

function loadCats(){ fetch(API).then(r=>r.json()).then(d=>{CATS=d;renderAll();})
  .catch(()=>TYPES.forEach(t=>document.getElementById('list-'+t).innerHTML='<div class="media-empty">Failed to load.</div>')); }

function renderAll(){
  const q=(document.getElementById('catSearch').value||'').toLowerCase();
  TYPES.forEach(t=>{
    const items=CATS.filter(c=>c.type===t && (!q || c.name.toLowerCase().includes(q)));
    document.getElementById('count-'+t).textContent=CATS.filter(c=>c.type===t).length;
    const el=document.getElementById('list-'+t);
    el.innerHTML = items.length ? items.map(c=>`
      <div class="cat-item ${c.active?'':'off'}">
        <span class="nm">${esc(c.name)}${c.description?'<small>'+esc(c.description)+'</small>':''}</span>
        <span class="cat-actions">
          <span class="badge ${c.active?'badge-confirmed':'badge-cancelled'}">${c.active?'ACTIVE':'OFF'}</span>
          <button class="icon-btn" title="${c.active?'Disable':'Enable'}" onclick="toggleCat(${c.id})">${c.active?'&#9210;':'&#9205;'}</button>
          <button class="icon-btn del" title="Delete" onclick="deleteCat(${c.id}, '${esc(c.name)}')">&#128465;</button>
        </span>
      </div>`).join('') : '<div class="media-empty" style="margin:8px 0">No categories.</div>';
  });
}

function headers(json){ const h=json?{'Content-Type':'application/json'}:{}; h[CSRF_HEADER]=CSRF_TOKEN; return h; }
function addCat(type){
  const input=document.getElementById('in-'+type); const name=input.value.trim();
  if(!name){ toast('Enter a name','err'); return; }
  fetch(API,{method:'POST',headers:headers(true),body:JSON.stringify({type,name})})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ input.value=''; toast('Category added','ok'); loadCats(); }
      else toast(res.body.message||'Could not add','err'); })
    .catch(()=>toast('Network error','err'));
}
function action(url, okMsg){
  fetch(url,{method:'POST',headers:headers(false)})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ toast(okMsg,'ok'); loadCats(); } else toast(res.body.message||'Action failed','err'); })
    .catch(()=>toast('Network error','err'));
}
function toggleCat(id){ action(API+'/'+id+'/toggle','Category updated'); }
function deleteCat(id,name){ if(confirm('Delete '+name+'?')) action(API+'/'+id+'/delete','Category deleted'); }

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); }

loadCats();
</script>

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