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

<section>
    <div class="container">
        <div class="page-header">
            <h1>Manage Cars</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openCarModal()">+ Add Car</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="carSearch" type="text"
                   placeholder="Search make, model or registration…" oninput="renderRows()"/>
            <span id="carCount" style="color:#888;font-size:13px"></span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="id">ID</th><th data-sort="registrationNumber">Reg No</th>
                    <th data-sort="make">Make / Model</th><th data-sort="yearOfRegistration">Year</th>
                    <th data-sort="type">Type</th><th data-sort="ownership">Owner</th>
                    <th data-sort="pricePerDay">Price/day</th><th data-sort="status">Status</th>
                    <th data-sort="available">Listed</th><th></th>
                </tr>
                </thead>
                <tbody id="carRows">
                <tr><td colspan="10" class="table-loading">Loading cars…</td></tr>
                </tbody>
            </table>
        </div>
        <div class="pager" id="carPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="carModal">
    <div class="modal-card">
        <div class="modal-head">
            <h2><span id="modalTitle">Add Car</span><span class="tag" id="modalTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeCarModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="carForm" onsubmit="return false">
                <input type="hidden" id="f_id"/>

                <h4 class="form-section">Basic details</h4>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Make</label>
                        <input type="text" id="f_make"/>
                        <small class="fe" id="e_make"></small>
                    </div>
                    <div class="form-group field">
                        <label>Model</label>
                        <input type="text" id="f_model"/>
                        <small class="fe" id="e_model"></small>
                    </div>
                    <div class="form-group field">
                        <label>Registration Number</label>
                        <input type="text" id="f_registrationNumber"/>
                        <small class="fe" id="e_registrationNumber"></small>
                    </div>
                    <div class="form-group field">
                        <label>Year of Registration</label>
                        <input type="number" id="f_yearOfRegistration" min="1990" max="2100"/>
                    </div>
                    <div class="form-group field">
                        <label>Colour</label>
                        <input type="text" id="f_colour"/>
                    </div>
                </div>

                <h4 class="form-section">Classification</h4>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Type</label>
                        <select id="f_type">
                            <option th:each="t : ${T(com.mvrent.carrental.model.CarType).values()}"
                                    th:value="${t}" th:text="${t}"></option>
                        </select>
                        <small class="fe" id="e_type"></small>
                    </div>
                    <div class="form-group field">
                        <label>Seats</label>
                        <input type="number" id="f_seats" min="2" max="15" value="5"/>
                        <small class="fe" id="e_seats"></small>
                    </div>
                    <div class="form-group field">
                        <label>Transmission</label>
                        <select id="f_transmission">
                            <option th:each="t : ${T(com.mvrent.carrental.model.Transmission).values()}"
                                    th:value="${t}" th:text="${t}"></option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Fuel Type</label>
                        <select id="f_fuelType">
                            <option th:each="f : ${T(com.mvrent.carrental.model.FuelType).values()}"
                                    th:value="${f}" th:text="${f}"></option>
                        </select>
                    </div>
                    <div class="form-group field" style="grid-column:1 / -1">
                        <label>Feature Tags (comma separated)</label>
                        <input type="text" id="f_featureTagsCsv" placeholder="AC, GPS, Sunroof, Bluetooth"/>
                    </div>
                </div>

                <h4 class="form-section">Rates ([[${currencySymbol}]])</h4>
                <div class="form-grid2">
                    <div class="form-group field"><label>Hourly</label><input type="number" step="0.01" id="f_hourlyRate"/></div>
                    <div class="form-group field">
                        <label>Daily *</label>
                        <input type="number" step="0.01" id="f_pricePerDay"/>
                        <small class="fe" id="e_pricePerDay"></small>
                    </div>
                    <div class="form-group field"><label>Monthly</label><input type="number" step="0.01" id="f_monthlyRate"/></div>
                </div>

                <h4 class="form-section">Ownership &amp; availability</h4>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Ownership</label>
                        <select id="f_ownership" onchange="toggleVendor()">
                            <option th:each="o : ${T(com.mvrent.carrental.model.CarOwnership).values()}"
                                    th:value="${o}" th:text="${o}"></option>
                        </select>
                    </div>
                    <div class="form-group field" id="vendorWrap">
                        <label>Vendor</label>
                        <select id="f_vendorId">
                            <option value="">— none —</option>
                            <option th:each="v : ${vendors}" th:value="${v.id}" th:text="${v.name}"></option>
                        </select>
                    </div>
                    <div class="form-group field"><label>Commission % override</label><input type="number" step="0.01" id="f_commissionPercentOverride"/></div>
                    <div class="form-group field"><label>Units (total)</label><input type="number" id="f_unitsTotal" min="1" value="1"/></div>
                    <div class="form-group field">
                        <label>Status</label>
                        <select id="f_status">
                            <option th:each="s : ${T(com.mvrent.carrental.model.CarStatus).values()}"
                                    th:value="${s}" th:text="${s}"></option>
                        </select>
                    </div>
                    <div class="form-group field"><label>Image URL</label><input type="text" id="f_imageUrl" placeholder="/images/car.png"/></div>
                    <div class="form-group" style="grid-column:1 / -1">
                        <label style="font-weight:500;color:#444">
                            <input type="checkbox" id="f_available" checked/> Listed for booking
                        </label>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <button id="docsLink" class="btn btn-ghost btn-sm" type="button" style="display:none"
                    onclick="openMediaModal(EDIT_CAR_ID, EDIT_CAR_NAME)">Documents &amp; Photos &rarr;</button>
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeCarModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="saveBtn" type="button" onclick="saveCar()">Save Car</button>
        </div>
    </div>
</div>

<!-- ============ Documents & Photos slide-over drawer ============ -->
<div class="drawer-overlay" id="mediaModal">
    <div class="drawer">
        <div class="drawer-head">
            <h2>Documents &amp; Photos <span class="tag" id="mediaCarName"></span></h2>
            <button class="modal-close" type="button" onclick="closeMediaModal()">&times;</button>
        </div>
        <div class="media-tabs">
            <button class="media-tab active" data-tab="docs" type="button" onclick="mediaTab('docs')">
                <span class="t-ico">&#128196;</span> Documents <span class="tab-count" id="docCount">0</span>
            </button>
            <button class="media-tab" data-tab="photos" type="button" onclick="mediaTab('photos')">
                <span class="t-ico">&#128247;</span> Photos <span class="tab-count" id="photoCount">0</span>
            </button>
        </div>
        <div class="drawer-body">
            <!-- Documents pane -->
            <div class="media-pane" id="tab-docs">
                <div id="docRows"><div class="media-empty">Loading…</div></div>
                <form id="docForm" class="media-add" onsubmit="return false">
                    <h5>Add document</h5>
                    <div class="stack">
                        <div class="field">
                            <label>Type</label>
                            <select id="m_docType">
                                <option th:each="t : ${T(com.mvrent.carrental.model.CarDocumentType).values()}"
                                        th:value="${t}" th:text="${t}"></option>
                            </select>
                        </div>
                        <div class="field">
                            <label>File</label>
                            <div class="filebox">
                                <input type="file" class="filebox-input" id="m_docFile" accept=".pdf,.jpg,.jpeg,.png" onchange="fileboxUpdate(this)"/>
                                <div class="filebox-face"><span class="filebox-ico">&#8682;</span><span class="filebox-label" data-placeholder="Choose file">Choose file</span></div>
                            </div>
                        </div>
                        <div class="field"><label>Issued</label><input type="date" id="m_issued"/></div>
                        <div class="field"><label>Expiry</label><input type="date" id="m_expiry"/></div>
                        <button class="btn btn-primary" type="button" onclick="addCarDoc()" style="width:100%">Add document</button>
                    </div>
                </form>
            </div>

            <!-- Photos pane -->
            <div class="media-pane" id="tab-photos" style="display:none">
                <div class="photo-grid" id="photoGrid"></div>
                <form id="photoForm" class="media-add" onsubmit="return false">
                    <h5>Add photo</h5>
                    <div class="stack">
                        <div class="field">
                            <label>Photo</label>
                            <div class="filebox">
                                <input type="file" class="filebox-input" id="m_photoFile" accept="image/*" onchange="fileboxUpdate(this)"/>
                                <div class="filebox-face"><span class="filebox-ico">&#128247;</span><span class="filebox-label" data-placeholder="Choose image">Choose image</span></div>
                            </div>
                        </div>
                        <div class="field"><label>or Photo URL</label><input type="text" id="m_photoUrl" placeholder="/images/..."/></div>
                        <div class="field"><label>Sort</label><input type="number" id="m_sort" value="0"/></div>
                        <button class="btn btn-primary" type="button" onclick="addCarPhoto()" style="width:100%">Add photo</button>
                    </div>
                </form>
            </div>
        </div>
        <div class="drawer-foot">
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeMediaModal()">Close</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/cars';
let CARS = [];
const ST = { sortKey: null, sortDir: 1, page: 1, pageSize: 10 };
const FIELDS = ['id','make','model','registrationNumber','yearOfRegistration','colour','type','seats',
  'transmission','fuelType','featureTagsCsv','hourlyRate','pricePerDay','monthlyRate','ownership',
  'vendorId','commissionPercentOverride','unitsTotal','status','imageUrl','available'];

function esc(s){ return (s==null?'':String(s)).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

function statusBadge(s){
  const cls = s==='ACTIVE' ? 'badge-confirmed' : (s==='MAINTENANCE' ? 'badge-pending' : 'badge-cancelled');
  return '<span class="badge '+cls+'">'+s+'</span>';
}
function listedBadge(a){
  return '<span class="badge '+(a?'badge-confirmed':'badge-cancelled')+'">'+(a?'YES':'NO')+'</span>';
}

function loadCars(){
  fetch(API).then(r=>r.json()).then(data=>{ CARS = data; renderRows(); })
    .catch(()=>{ document.getElementById('carRows').innerHTML =
      '<tr><td colspan="10" class="table-loading">Failed to load cars.</td></tr>'; });
}

function renderRows(){
  const q = (document.getElementById('carSearch').value||'').toLowerCase();
  let rows = CARS.filter(c =>
    !q || (c.make+' '+c.model+' '+c.registrationNumber).toLowerCase().includes(q));
  rows = AdminTable.sort(rows, ST.sortKey, ST.sortDir);
  document.getElementById('carCount').textContent = rows.length + ' car' + (rows.length===1?'':'s');
  const tb = document.getElementById('carRows');
  if(!rows.length){ tb.innerHTML = '<tr><td colspan="10" class="table-loading">No cars found.</td></tr>';
    document.getElementById('carPager').innerHTML=''; return; }
  const pg = AdminTable.paginate(rows, ST.page, ST.pageSize);
  tb.innerHTML = pg.slice.map(c => `
    <tr>
      <td>${c.id}</td>
      <td>${esc(c.registrationNumber)}</td>
      <td>${esc(c.make)} ${esc(c.model)}</td>
      <td>${c.yearOfRegistration||'—'}</td>
      <td>${esc(c.type)}</td>
      <td>${esc(c.ownership)}${c.vendorName?'<br><small style="color:#888">'+esc(c.vendorName)+'</small>':''}</td>
      <td>${CUR}${c.pricePerDay}</td>
      <td>${statusBadge(c.status)}</td>
      <td>${listedBadge(c.available)}</td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Edit" onclick="editCar(${c.id})">&#9998;</button>
        <button class="icon-btn docs" title="Documents & Photos" onclick="openMediaModal(${c.id}, '${esc(c.make)} ${esc(c.model)}')">&#128206;</button>
        <button class="icon-btn del" title="Delete" onclick="deleteCar(${c.id}, '${esc(c.make)} ${esc(c.model)}')">&#128465;</button>
      </div></td>
    </tr>`).join('');
  ST.page = pg.page;
  AdminTable.pager(document.getElementById('carPager'), pg.page, pg.total, p => { ST.page = p; renderRows(); });
}

function clearErrors(){ document.querySelectorAll('.fe').forEach(e=>{e.classList.remove('show');e.textContent='';});
  document.querySelectorAll('#carForm .invalid').forEach(e=>e.classList.remove('invalid')); }

function setVal(id,v){ const el=document.getElementById(id); if(el) el.value = (v==null?'':v); }

function toggleVendor(){
  document.getElementById('vendorWrap').style.opacity =
    document.getElementById('f_ownership').value === 'VENDOR' ? '1' : '.5';
}

function openCarModal(){
  clearErrors();
  document.getElementById('carForm').reset();
  setVal('f_id',''); setVal('f_seats',5); setVal('f_unitsTotal',1);
  document.getElementById('f_available').checked = true;
  document.getElementById('modalTitle').textContent = 'Add Car';
  document.getElementById('modalTag').style.display = 'none';
  document.getElementById('docsLink').style.display = 'none';
  toggleVendor();
  document.getElementById('carModal').classList.add('open');
}

let EDIT_CAR_ID = null, EDIT_CAR_NAME = '';
function editCar(id){
  clearErrors();
  fetch(API+'/'+id).then(r=>r.json()).then(c=>{
    FIELDS.forEach(f=>{ if(f!=='available') setVal('f_'+f, c[f]); });
    document.getElementById('f_available').checked = !!c.available;
    document.getElementById('modalTitle').textContent = 'Edit Car';
    document.getElementById('modalTag').style.display = 'inline-block';
    EDIT_CAR_ID = id; EDIT_CAR_NAME = (c.make || '') + ' ' + (c.model || '');
    document.getElementById('docsLink').style.display = 'inline-block';
    toggleVendor();
    document.getElementById('carModal').classList.add('open');
  });
}

function closeCarModal(){ document.getElementById('carModal').classList.remove('open'); }

function numOrNull(id){ const v=document.getElementById(id).value; return v===''?null:Number(v); }
function strOrNull(id){ const v=document.getElementById(id).value.trim(); return v===''?null:v; }

function saveCar(){
  clearErrors();
  const payload = {
    id: numOrNull('f_id'),
    make: document.getElementById('f_make').value,
    model: document.getElementById('f_model').value,
    registrationNumber: document.getElementById('f_registrationNumber').value,
    yearOfRegistration: numOrNull('f_yearOfRegistration'),
    colour: strOrNull('f_colour'),
    type: document.getElementById('f_type').value,
    seats: numOrNull('f_seats'),
    transmission: document.getElementById('f_transmission').value,
    fuelType: document.getElementById('f_fuelType').value,
    featureTagsCsv: document.getElementById('f_featureTagsCsv').value,
    hourlyRate: numOrNull('f_hourlyRate'),
    pricePerDay: numOrNull('f_pricePerDay'),
    monthlyRate: numOrNull('f_monthlyRate'),
    ownership: document.getElementById('f_ownership').value,
    vendorId: numOrNull('f_vendorId'),
    commissionPercentOverride: numOrNull('f_commissionPercentOverride'),
    unitsTotal: numOrNull('f_unitsTotal'),
    status: document.getElementById('f_status').value,
    imageUrl: strOrNull('f_imageUrl'),
    available: document.getElementById('f_available').checked
  };
  const btn = document.getElementById('saveBtn');
  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){
        closeCarModal();
        toast(payload.id ? 'Car updated' : 'Car added', 'ok');
        loadCars();
      } else {
        const errs = res.body.errors || {};
        Object.keys(errs).forEach(k=>{
          const e = document.getElementById('e_'+k); const inp = document.getElementById('f_'+k);
          if(e){ e.textContent = errs[k]; e.classList.add('show'); }
          if(inp){ inp.classList.add('invalid'); }
        });
        if(res.body.message) toast(res.body.message,'err');
        else if(!Object.keys(errs).length) toast('Could not save car','err');
      }
    })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{ btn.disabled=false; btn.textContent='Save Car'; });
}

function deleteCar(id, name){
  if(!confirm('Delete '+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('Car deleted','ok'); loadCars(); }
      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);
}

/* ---------- Documents & Photos modal ---------- */
let MEDIA_CAR = null;
function openMediaModal(id, name){
  MEDIA_CAR = id;
  document.getElementById('mediaCarName').textContent = name || ('#'+id);
  closeCarModal();
  document.getElementById('docRows').innerHTML = '<div class="media-empty">Loading…</div>';
  document.getElementById('photoGrid').innerHTML = '';
  loadMedia(id);
  mediaTab('docs');
  document.getElementById('mediaModal').classList.add('open');
}
function closeMediaModal(){ document.getElementById('mediaModal').classList.remove('open'); }
function mediaTab(name){
  document.getElementById('tab-docs').style.display   = name==='docs'   ? '' : 'none';
  document.getElementById('tab-photos').style.display = name==='photos' ? '' : 'none';
  document.querySelectorAll('.media-tab').forEach(t=>t.classList.toggle('active', t.dataset.tab===name));
}

function loadMedia(id){
  fetch(API+'/'+id+'/media').then(r=>r.json()).then(m=>{ renderDocs(m.documents); renderPhotos(m.photos); });
}
function docState(s){
  const cls = s==='EXPIRED' ? 'badge-cancelled' : (s==='EXPIRING' ? 'badge-pending' : 'badge-confirmed');
  return '<span class="badge '+cls+'">'+s+'</span>';
}
function renderDocs(docs){
  document.getElementById('docCount').textContent = (docs && docs.length) || 0;
  const c = document.getElementById('docRows');
  c.innerHTML = (docs && docs.length) ? docs.map(d=>`
    <div class="doc-card">
      <div>
        <div class="doc-card-type">${esc(d.docType)} ${docState(d.state)}</div>
        <div class="doc-card-meta">Issued ${d.issuedDate||'—'} &middot; Expires ${d.expiryDate||'—'}</div>
        ${d.fileUrl?'<a class="doc-card-link" href="'+esc(d.fileUrl)+'" target="_blank">View file &#8599;</a>':''}
      </div>
      <button class="icon-btn del" title="Delete" onclick="delCarDoc(${d.id})">&#128465;</button>
    </div>`).join('') : '<div class="media-empty">No documents yet.</div>';
}
function renderPhotos(photos){
  document.getElementById('photoCount').textContent = (photos && photos.length) || 0;
  const g = document.getElementById('photoGrid');
  g.innerHTML = (photos && photos.length) ? photos.map(p=>`
    <div class="photo-cell">
      <img src="${esc(p.url)}" alt="photo"/>
      <button class="ph-del" type="button" title="Delete" onclick="delCarPhoto(${p.id})">&#128465;</button>
    </div>`).join('') : '<div class="media-empty">No photos yet — add one below.</div>';
}

function mediaPost(url, body){
  const headers = {}; headers[CSRF_HEADER] = CSRF_TOKEN;
  return fetch(url, {method:'POST', headers, body}).then(async r=>({ok:r.ok, body:await r.json()}));
}
function addCarDoc(){
  const fd = new FormData();
  fd.append('docType', document.getElementById('m_docType').value);
  const f = document.getElementById('m_docFile').files[0]; if(f) fd.append('file', f);
  const iss = document.getElementById('m_issued').value; if(iss) fd.append('issuedDate', iss);
  const exp = document.getElementById('m_expiry').value; if(exp) fd.append('expiryDate', exp);
  mediaPost(API+'/'+MEDIA_CAR+'/documents', fd).then(res=>{
    if(res.ok && res.body.ok){ const fm=document.getElementById('docForm'); fm.reset(); AdminTable.resetFileboxes(fm); toast('Document added','ok'); loadMedia(MEDIA_CAR); }
    else toast(res.body.message||'Could not add','err');
  }).catch(()=>toast('Network error','err'));
}
function delCarDoc(docId){
  mediaPost(API+'/'+MEDIA_CAR+'/documents/'+docId+'/delete', null)
    .then(()=>{ toast('Document removed','ok'); loadMedia(MEDIA_CAR); }).catch(()=>toast('Network error','err'));
}
function addCarPhoto(){
  const fd = new FormData();
  const f = document.getElementById('m_photoFile').files[0]; if(f) fd.append('file', f);
  const url = document.getElementById('m_photoUrl').value.trim(); if(url) fd.append('url', url);
  fd.append('sortOrder', document.getElementById('m_sort').value||'0');
  mediaPost(API+'/'+MEDIA_CAR+'/photos', fd).then(res=>{
    if(res.ok && res.body.ok){ const fm=document.getElementById('photoForm'); fm.reset(); AdminTable.resetFileboxes(fm); toast('Photo added','ok'); loadMedia(MEDIA_CAR); }
    else toast(res.body.message||'Could not add','err');
  }).catch(()=>toast('Network error','err'));
}
function delCarPhoto(photoId){
  mediaPost(API+'/'+MEDIA_CAR+'/photos/'+photoId+'/delete', null)
    .then(()=>{ toast('Photo removed','ok'); loadMedia(MEDIA_CAR); }).catch(()=>toast('Network error','err'));
}

// close on overlay click / Esc
document.getElementById('carModal').addEventListener('click', e=>{ if(e.target.id==='carModal') closeCarModal(); });
document.getElementById('mediaModal').addEventListener('click', e=>{ if(e.target.id==='mediaModal') closeMediaModal(); });
document.addEventListener('keydown', e=>{ if(e.key==='Escape'){ closeCarModal(); closeMediaModal(); } });

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

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