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

<section>
    <div class="container">
        <div class="page-header"><h1>Reviews &amp; Ratings</h1></div>

        <div class="cars-toolbar">
            <input class="cars-search" id="rSearch" type="text"
                   placeholder="Search car, customer, comment…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="rFilter" class="cars-search" style="min-width:150px" onchange="renderRows()">
                    <option value="">All</option>
                    <option value="published">Published</option>
                    <option value="hidden">Hidden</option>
                </select>
                <span id="rCount" style="color:#888;font-size:13px"></span>
            </span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="createdAt">When</th><th data-sort="carName">Car</th>
                    <th data-sort="customerName">Customer</th><th data-sort="rating">Rating</th>
                    <th data-sort="comment">Comment</th><th data-sort="approved">Status</th><th></th>
                </tr>
                </thead>
                <tbody id="rRows"><tr><td colspan="7" class="table-loading">Loading…</td></tr></tbody>
            </table>
        </div>
        <div class="pager" id="rPager"></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 src="/js/admin-table.js"></script>
<script>
const API='/admin/api/reviews';
let ROWS=[];
const ST={sortKey:'createdAt',sortDir:-1,page:1,pageSize:15};
function esc(s){return (s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function fmt(ts){ if(!ts)return '—'; const d=new Date(ts); return d.toLocaleDateString(); }
function stars(n){ let s=''; for(let i=1;i<=5;i++) s+= (i<=n?'★':'☆'); return '<span style="color:#f7941d;letter-spacing:1px">'+s+'</span>'; }

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

function renderRows(){
  const q=(document.getElementById('rSearch').value||'').toLowerCase();
  const f=document.getElementById('rFilter').value;
  let rows=ROWS.filter(m=>(!q||((m.carName||'')+' '+(m.customerName||'')+' '+(m.comment||'')).toLowerCase().includes(q))
    && (!f || (f==='published'?m.approved:!m.approved)));
  rows=AdminTable.sort(rows,ST.sortKey,ST.sortDir);
  document.getElementById('rCount').textContent=rows.length+' review'+(rows.length===1?'':'s');
  const tb=document.getElementById('rRows');
  if(!rows.length){tb.innerHTML='<tr><td colspan="7" class="table-loading">No reviews yet.</td></tr>';document.getElementById('rPager').innerHTML='';return;}
  const pg=AdminTable.paginate(rows,ST.page,ST.pageSize);
  tb.innerHTML=pg.slice.map(m=>`
    <tr>
      <td><small>${fmt(m.createdAt)}</small></td>
      <td>${esc(m.carName)}</td>
      <td>${esc(m.customerName)}${m.bookingId?'<br><small style="color:#888">trip #'+m.bookingId+'</small>':''}</td>
      <td>${stars(m.rating)}</td>
      <td><small>${esc(m.comment)||'—'}</small></td>
      <td><span class="badge ${m.approved?'badge-confirmed':'badge-cancelled'}">${m.approved?'PUBLISHED':'HIDDEN'}</span></td>
      <td><div class="row-actions">
        <button class="icon-btn" title="${m.approved?'Hide':'Publish'}" onclick="toggle(${m.id},${!m.approved})">${m.approved?'&#128065;':'&#10003;'}</button>
        <button class="icon-btn del" title="Delete" onclick="del(${m.id})">&#128465;</button>
      </div></td>
    </tr>`).join('');
  ST.page=pg.page;
  AdminTable.pager(document.getElementById('rPager'),pg.page,pg.total,p=>{ST.page=p;renderRows();});
}

function toggle(id,approved){
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/approve?approved='+approved,{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{if(res.ok&&res.body.ok){toast(approved?'Published':'Hidden','ok');load();}else toast('Failed','err');})
    .catch(()=>toast('Network error','err'));
}
function del(id){
  if(!confirm('Delete this review?'))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('Failed','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);}

AdminTable.attachSort(document.querySelector('.table-wrap thead tr'),ST,()=>{ST.page=1;renderRows();});
load();
</script>

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