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

<section>
    <div class="container">
        <div class="page-header">
            <h1>Damage &amp; Inspection Records</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openModal()">+ New Inspection</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="iSearch" type="text"
                   placeholder="Search car, inspector, notes…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="iFilter" class="cars-search" style="min-width:160px" onchange="renderRows()">
                    <option value="">All conditions</option>
                    <option value="GOOD">Good</option>
                    <option value="MINOR_DAMAGE">Minor damage</option>
                    <option value="MAJOR_DAMAGE">Major damage</option>
                </select>
                <span id="iCount" style="color:#888;font-size:13px"></span>
            </span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="regNo">Car</th><th data-sort="type">Type</th>
                    <th data-sort="condition">Condition</th><th data-sort="inspectionDate">Date</th>
                    <th data-sort="inspector">Inspector</th><th data-sort="odometer">Odo</th>
                    <th data-sort="fuelLevel">Fuel</th><th>Photo</th><th></th>
                </tr>
                </thead>
                <tbody id="iRows"><tr><td colspan="9" class="table-loading">Loading…</td></tr></tbody>
            </table>
        </div>
        <div class="pager" id="iPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="iModal">
    <div class="modal-card" style="max-width:700px">
        <div class="modal-head">
            <h2><span id="iTitle">New Inspection</span><span class="tag" id="iTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="iForm" onsubmit="return false">
                <input type="hidden" id="i_id"/>
                <input type="hidden" id="i_photoUrl"/>
                <div class="form-grid2">
                    <div class="form-group field" style="grid-column:1 / -1">
                        <label>Car</label>
                        <select id="i_carId">
                            <option value="">— choose a car —</option>
                            <option th:each="c : ${cars}" th:value="${c.id}"
                                    th:text="${c.make + ' ' + c.model + ' (' + c.registrationNumber + ')'}">Car</option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Inspection type</label>
                        <select id="i_type">
                            <option th:each="t : ${T(com.mvrent.carrental.model.InspectionType).values()}"
                                    th:value="${t}" th:text="${#strings.replace(t, '_', ' ')}"></option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Condition</label>
                        <select id="i_condition">
                            <option value="GOOD">Good</option>
                            <option value="MINOR_DAMAGE">Minor damage</option>
                            <option value="MAJOR_DAMAGE">Major damage</option>
                        </select>
                    </div>
                    <div class="form-group field"><label>Inspection date</label><input type="date" id="i_inspectionDate"/></div>
                    <div class="form-group field"><label>Inspector</label><input type="text" id="i_inspector"/></div>
                    <div class="form-group field"><label>Odometer (km)</label><input type="number" id="i_odometer" min="0"/></div>
                    <div class="form-group field"><label>Fuel level (%)</label><input type="number" id="i_fuelLevel" min="0" max="100"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Booking ID (optional)</label><input type="number" id="i_bookingId" min="1" placeholder="Link to a trip"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Damage / condition notes</label><input type="text" id="i_damageNotes" placeholder="Scratches on rear bumper…"/></div>
                    <div class="form-group field" style="grid-column:1 / -1">
                        <label>Photo</label>
                        <label class="filebox">
                            <input type="file" accept="image/*" onchange="uploadPhoto(this)"/>
                            <span class="filebox-label">Choose photo…</span>
                        </label>
                        <div id="i_photoPrev" style="margin-top:8px"></div>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="iSaveBtn" 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/inspections';
let ROWS=[];
const ST={sortKey:null,sortDir:1,page:1,pageSize:10};
function esc(s){return (s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function condBadge(c){const map={GOOD:'badge-confirmed',MINOR_DAMAGE:'badge-pending',MAJOR_DAMAGE:'badge-cancelled'};
  return '<span class="badge '+(map[c]||'')+'">'+(c||'').replace('_',' ')+'</span>';}

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

function renderRows(){
  const q=(document.getElementById('iSearch').value||'').toLowerCase();
  const f=document.getElementById('iFilter').value;
  let rows=ROWS.filter(m=>(!q||((m.carName||'')+' '+(m.regNo||'')+' '+(m.inspector||'')+' '+(m.damageNotes||'')).toLowerCase().includes(q)) && (!f||m.condition===f));
  rows=AdminTable.sort(rows,ST.sortKey,ST.sortDir);
  document.getElementById('iCount').textContent=rows.length+' record'+(rows.length===1?'':'s');
  const tb=document.getElementById('iRows');
  if(!rows.length){tb.innerHTML='<tr><td colspan="9" class="table-loading">No records found.</td></tr>';document.getElementById('iPager').innerHTML='';return;}
  const pg=AdminTable.paginate(rows,ST.page,ST.pageSize);
  tb.innerHTML=pg.slice.map(m=>`
    <tr>
      <td><div>${esc(m.carName)}</div><small style="color:#888">${esc(m.regNo)}</small></td>
      <td>${esc((m.type||'').replace('_',' '))}${m.bookingId?'<br><small style="color:#888">trip #'+m.bookingId+'</small>':''}</td>
      <td>${condBadge(m.condition)}${m.damageNotes?'<br><small style="color:#888">'+esc(m.damageNotes)+'</small>':''}</td>
      <td>${m.inspectionDate||'—'}</td>
      <td>${esc(m.inspector)||'—'}</td>
      <td>${m.odometer!=null?m.odometer:'—'}</td>
      <td>${m.fuelLevel!=null?m.fuelLevel+'%':'—'}</td>
      <td>${m.photoUrl?'<a href="'+esc(m.photoUrl)+'" target="_blank"><img src="'+esc(m.photoUrl)+'" style="width:42px;height:32px;object-fit:cover;border-radius:5px"/></a>':'—'}</td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Edit" onclick="edit(${m.id})">&#9998;</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('iPager'),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 showPhoto(url){ document.getElementById('i_photoPrev').innerHTML = url
  ? '<img src="'+url+'" style="height:70px;border-radius:7px;border:1px solid #e6e8ee"/>' : ''; }

function openModal(){
  document.getElementById('iForm').reset(); setVal('i_id',''); setVal('i_photoUrl','');
  document.getElementById('i_inspectionDate').valueAsDate=new Date();
  showPhoto(''); AdminTable.resetFileboxes && AdminTable.resetFileboxes(document.getElementById('iForm'));
  document.getElementById('iTitle').textContent='New Inspection';
  document.getElementById('iTag').style.display='none';
  document.getElementById('iModal').classList.add('open');
}
function edit(id){
  fetch(API+'/'+id).then(r=>r.json()).then(m=>{
    setVal('i_id',m.id); setVal('i_carId',m.carId); setVal('i_type',m.type); setVal('i_condition',m.condition);
    setVal('i_inspectionDate',m.inspectionDate); setVal('i_inspector',m.inspector); setVal('i_odometer',m.odometer);
    setVal('i_fuelLevel',m.fuelLevel); setVal('i_bookingId',m.bookingId); setVal('i_damageNotes',m.damageNotes);
    setVal('i_photoUrl',m.photoUrl||''); showPhoto(m.photoUrl);
    document.getElementById('iTitle').textContent='Edit Inspection';
    document.getElementById('iTag').style.display='inline-block';
    document.getElementById('iModal').classList.add('open');
  });
}
function closeModal(){document.getElementById('iModal').classList.remove('open');}
function nOrNull(id){const v=document.getElementById(id).value;return v===''?null:Number(v);}
function sOrNull(id){const v=document.getElementById(id).value.trim();return v===''?null:v;}

function uploadPhoto(input){
  if(!input.files||!input.files[0])return;
  if(window.fileboxUpdate) fileboxUpdate(input);
  const fd=new FormData(); fd.append('file',input.files[0]);
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch('/admin/api/upload',{method:'POST',headers,body:fd})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ setVal('i_photoUrl',res.body.url); showPhoto(res.body.url); toast('Photo uploaded','ok'); }
      else toast(res.body.message||'Upload failed','err'); })
    .catch(()=>toast('Upload error','err'));
}

function save(){
  const payload={ id:nOrNull('i_id'), carId:nOrNull('i_carId'), bookingId:nOrNull('i_bookingId'),
    type:document.getElementById('i_type').value, condition:document.getElementById('i_condition').value,
    inspectionDate:sOrNull('i_inspectionDate'), inspector:sOrNull('i_inspector'),
    odometer:nOrNull('i_odometer'), fuelLevel:nOrNull('i_fuelLevel'),
    damageNotes:sOrNull('i_damageNotes'), photoUrl:sOrNull('i_photoUrl') };
  if(!payload.carId) return toast('Select a car','err');
  const btn=document.getElementById('iSaveBtn'); 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(payload.id?'Inspection updated':'Inspection saved','ok');load();}
      else toast(res.body.message||'Could not save','err'); })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{btn.disabled=false;btn.textContent='Save';});
}
function del(id){
  if(!confirm('Delete this inspection record?'))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('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('iModal').addEventListener('click',e=>{if(e.target.id==='iModal')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>
