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

<section>
    <div class="container">
        <div class="page-header">
            <h1>Maintenance &amp; Service Logs</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openModal()">+ Log Service</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="mSearch" type="text"
                   placeholder="Search car, garage, notes…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="mFilter" class="cars-search" style="min-width:150px" onchange="renderRows()">
                    <option value="">All statuses</option>
                    <option value="SCHEDULED">Scheduled</option>
                    <option value="IN_PROGRESS">In progress</option>
                    <option value="COMPLETED">Completed</option>
                </select>
                <span id="mCount" 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="status">Status</th><th data-sort="serviceDate">Service date</th>
                    <th data-sort="odometer">Odometer</th><th data-sort="cost">Cost</th>
                    <th data-sort="garage">Garage</th><th data-sort="nextServiceDate">Next due</th><th></th>
                </tr>
                </thead>
                <tbody id="mRows"><tr><td colspan="9" class="table-loading">Loading…</td></tr></tbody>
            </table>
        </div>
        <div class="pager" id="mPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="mModal">
    <div class="modal-card" style="max-width:680px">
        <div class="modal-head">
            <h2><span id="mTitle">Log Service</span><span class="tag" id="mTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="mForm" onsubmit="return false">
                <input type="hidden" id="m_id"/>
                <div class="form-grid2">
                    <div class="form-group field" style="grid-column:1 / -1">
                        <label>Car</label>
                        <select id="m_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>Work type</label>
                        <select id="m_type">
                            <option th:each="t : ${T(com.mvrent.carrental.model.MaintenanceType).values()}"
                                    th:value="${t}" th:text="${t}"></option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Status</label>
                        <select id="m_status">
                            <option value="COMPLETED">Completed</option>
                            <option value="SCHEDULED">Scheduled</option>
                            <option value="IN_PROGRESS">In progress</option>
                        </select>
                        <small class="fe" style="color:#888;display:block">Open jobs put the car into MAINTENANCE.</small>
                    </div>
                    <div class="form-group field"><label>Service date</label><input type="date" id="m_serviceDate"/></div>
                    <div class="form-group field"><label>Odometer (km)</label><input type="number" id="m_odometer" min="0"/></div>
                    <div class="form-group field"><label>Cost</label><input type="number" step="0.01" id="m_cost" min="0"/></div>
                    <div class="form-group field"><label>Garage / workshop</label><input type="text" id="m_garage"/></div>
                    <div class="form-group field"><label>Next service date</label><input type="date" id="m_nextServiceDate"/></div>
                    <div class="form-group field"><label>Next service odometer</label><input type="number" id="m_nextServiceOdometer" min="0"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Notes</label><input type="text" id="m_notes" placeholder="Parts replaced, observations…"/></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="mSaveBtn" 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';
const CUR         = /*[[${currencySymbol}]]*/ '₹';
/*]]>*/
</script>
<script src="/js/admin-table.js"></script>
<script>
const API='/admin/api/maintenance';
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 pill(s){return '<span class="dash-pill '+(s==='COMPLETED'?'pill-confirmed':(s==='IN_PROGRESS'?'pill-pending':'pill-cancelled'))+'">'+s.replace('_',' ')+'</span>';}

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

function renderRows(){
  const q=(document.getElementById('mSearch').value||'').toLowerCase();
  const f=document.getElementById('mFilter').value;
  let rows=ROWS.filter(m=>(!q||((m.carName||'')+' '+(m.regNo||'')+' '+(m.garage||'')+' '+(m.notes||'')).toLowerCase().includes(q)) && (!f||m.status===f));
  rows=AdminTable.sort(rows,ST.sortKey,ST.sortDir);
  document.getElementById('mCount').textContent=rows.length+' record'+(rows.length===1?'':'s');
  const tb=document.getElementById('mRows');
  if(!rows.length){tb.innerHTML='<tr><td colspan="9" class="table-loading">No records found.</td></tr>';document.getElementById('mPager').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('_',' '))}</td>
      <td>${pill(m.status||'')}</td>
      <td>${m.serviceDate||'—'}</td>
      <td>${m.odometer!=null?m.odometer+' km':'—'}</td>
      <td>${m.cost!=null?CUR+m.cost:'—'}</td>
      <td>${esc(m.garage)||'—'}</td>
      <td>${m.nextServiceDate?(m.dueSoon?'<span class="badge badge-pending">'+m.nextServiceDate+'</span>':m.nextServiceDate):'—'}</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('mPager'),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 openModal(){
  document.getElementById('mForm').reset(); setVal('m_id','');
  document.getElementById('m_status').value='COMPLETED';
  document.getElementById('m_serviceDate').valueAsDate=new Date();
  document.getElementById('mTitle').textContent='Log Service';
  document.getElementById('mTag').style.display='none';
  document.getElementById('mModal').classList.add('open');
}
function edit(id){
  fetch(API+'/'+id).then(r=>r.json()).then(m=>{
    setVal('m_id',m.id); setVal('m_carId',m.carId); setVal('m_type',m.type); setVal('m_status',m.status);
    setVal('m_serviceDate',m.serviceDate); setVal('m_odometer',m.odometer); setVal('m_cost',m.cost);
    setVal('m_garage',m.garage); setVal('m_notes',m.notes);
    setVal('m_nextServiceDate',m.nextServiceDate); setVal('m_nextServiceOdometer',m.nextServiceOdometer);
    document.getElementById('mTitle').textContent='Edit Record';
    document.getElementById('mTag').style.display='inline-block';
    document.getElementById('mModal').classList.add('open');
  });
}
function closeModal(){document.getElementById('mModal').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 save(){
  const payload={ id:nOrNull('m_id'), carId:nOrNull('m_carId'), type:document.getElementById('m_type').value,
    status:document.getElementById('m_status').value, serviceDate:sOrNull('m_serviceDate'),
    odometer:nOrNull('m_odometer'), cost:nOrNull('m_cost'), garage:sOrNull('m_garage'), notes:sOrNull('m_notes'),
    nextServiceDate:sOrNull('m_nextServiceDate'), nextServiceOdometer:nOrNull('m_nextServiceOdometer') };
  if(!payload.carId) return toast('Select a car','err');
  const btn=document.getElementById('mSaveBtn'); 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?'Record updated':'Service logged','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 maintenance 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('mModal').addEventListener('click',e=>{if(e.target.id==='mModal')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>
