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

<section>
    <div class="container">
        <div class="page-header">
            <h1>Drivers</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openDriverModal()">+ Add Driver</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="drvSearch" type="text"
                   placeholder="Search name, phone or licence…" oninput="renderRows()"/>
            <span id="drvCount" style="color:#888;font-size:13px"></span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="id">ID</th><th data-sort="name">Name</th><th data-sort="phone">Phone</th>
                    <th data-sort="licenceNumber">Licence</th><th data-sort="categoryName">Category</th>
                    <th data-sort="employmentType">Employment</th><th data-sort="dailyCharge">Day Charge</th>
                    <th data-sort="yearsExperience">Exp</th><th data-sort="status">Status</th><th></th>
                </tr>
                </thead>
                <tbody id="drvRows">
                <tr><td colspan="10" class="table-loading">Loading drivers…</td></tr>
                </tbody>
            </table>
        </div>
        <div class="pager" id="drvPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="drvModal">
    <div class="modal-card">
        <div class="modal-head">
            <h2><span id="drvModalTitle">Add Driver</span><span class="tag" id="drvModalTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeDriverModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="drvForm" onsubmit="return false">
                <input type="hidden" id="d_id"/>

                <h4 class="form-section">Personal details</h4>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Name</label><input type="text" id="d_name"/>
                        <small class="fe" id="de_name"></small>
                    </div>
                    <div class="form-group field"><label>Phone</label><input type="tel" id="d_phone"/></div>
                    <div class="form-group field">
                        <label>Licence Number</label><input type="text" id="d_licenceNumber"/>
                        <small class="fe" id="de_licenceNumber"></small>
                    </div>
                    <div class="form-group field"><label>Licence Expiry</label><input type="date" id="d_licenceExpiry"/></div>
                    <div class="form-group field"><label>Years of Experience</label><input type="number" id="d_yearsExperience" min="0" value="0"/></div>
                    <div class="form-group field">
                        <label>Photo</label>
                        <div class="filebox" style="margin-bottom:8px">
                            <input type="file" class="filebox-input" id="d_photoFile" accept="image/*" onchange="uploadDriverPhoto(this)"/>
                            <div class="filebox-face"><span class="filebox-ico">&#128247;</span><span class="filebox-label" data-placeholder="Upload photo">Upload photo</span></div>
                        </div>
                        <input type="text" id="d_photoUrl" placeholder="or paste image URL" oninput="showDriverPreview(this.value)"/>
                        <img id="d_photoPreview" alt="preview" style="display:none;margin-top:8px;width:60px;height:60px;object-fit:cover;border-radius:10px;border:1px solid #eee"/>
                    </div>
                </div>

                <h4 class="form-section">Category &amp; employment</h4>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Category</label>
                        <select id="d_categoryId">
                            <option value="">— none —</option>
                            <option th:each="c : ${categories}" th:value="${c.id}" th:text="${c.name}"></option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Employment Type</label>
                        <select id="d_employmentType" onchange="drvToggleVendor()">
                            <option th:each="e : ${T(com.mvrent.carrental.model.DriverEmploymentType).values()}"
                                    th:value="${e}" th:text="${e}"></option>
                        </select>
                    </div>
                    <div class="form-group field" id="drvVendorWrap">
                        <label>Vendor</label>
                        <select id="d_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>Status</label>
                        <select id="d_status">
                            <option th:each="s : ${T(com.mvrent.carrental.model.DriverStatus).values()}"
                                    th:value="${s}" th:text="${s}"></option>
                        </select>
                    </div>
                </div>

                <h4 class="form-section">Charges ([[${currencySymbol}]])</h4>
                <div class="form-grid2">
                    <div class="form-group field"><label>Hourly</label><input type="number" step="0.01" id="d_hourlyCharge"/></div>
                    <div class="form-group field"><label>Daily</label><input type="number" step="0.01" id="d_dailyCharge"/></div>
                    <div class="form-group field"><label>Monthly</label><input type="number" step="0.01" id="d_monthlyCharge"/></div>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <button id="drvProfileLink" class="btn btn-ghost btn-sm" type="button" style="display:none"
                    onclick="openDrvDocs(EDIT_DRV_ID, EDIT_DRV_NAME)">Documents &rarr;</button>
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeDriverModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="drvSaveBtn" type="button" onclick="saveDriver()">Save Driver</button>
        </div>
    </div>
</div>

<!-- ============ Driver documents slide-over drawer ============ -->
<div class="drawer-overlay" id="drvDocsModal">
    <div class="drawer">
        <div class="drawer-head">
            <h2>Documents <span class="tag" id="drvDocsName"></span></h2>
            <button class="modal-close" type="button" onclick="closeDrvDocs()">&times;</button>
        </div>
        <div class="drawer-body">
            <div id="drvDocRows"><div class="media-empty">Loading…</div></div>
            <form id="drvDocForm" class="media-add" onsubmit="return false">
                <h5>Add document</h5>
                <div class="stack">
                    <div class="field">
                        <label>Type</label>
                        <select id="dm_docType">
                            <option th:each="t : ${T(com.mvrent.carrental.model.DriverDocumentType).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="dm_file" 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="dm_issued"/></div>
                    <div class="field"><label>Expiry</label><input type="date" id="dm_expiry"/></div>
                    <button class="btn btn-primary" type="button" onclick="addDrvDoc()" style="width:100%">Add document</button>
                </div>
            </form>
        </div>
        <div class="drawer-foot">
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeDrvDocs()">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/drivers';
let DRIVERS = [];
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 statusBadge(s){
  const cls = s==='AVAILABLE' ? 'badge-confirmed' : (s==='ON_TRIP' ? 'badge-pending' : 'badge-cancelled');
  return '<span class="badge '+cls+'">'+s+'</span>';
}

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

function renderRows(){
  const q=(document.getElementById('drvSearch').value||'').toLowerCase();
  let rows=DRIVERS.filter(d=>!q || (d.name+' '+(d.phone||'')+' '+d.licenceNumber).toLowerCase().includes(q));
  rows = AdminTable.sort(rows, ST.sortKey, ST.sortDir);
  document.getElementById('drvCount').textContent = rows.length+' driver'+(rows.length===1?'':'s');
  const tb=document.getElementById('drvRows');
  if(!rows.length){ tb.innerHTML='<tr><td colspan="10" class="table-loading">No drivers found.</td></tr>';
    document.getElementById('drvPager').innerHTML=''; return; }
  const pg = AdminTable.paginate(rows, ST.page, ST.pageSize);
  tb.innerHTML = pg.slice.map(d=>`
    <tr>
      <td>${d.id}</td>
      <td><a href="/admin/drivers/${d.id}">${esc(d.name)}</a></td>
      <td>${esc(d.phone)||'—'}</td>
      <td>${esc(d.licenceNumber)} ${d.licenceExpired?'<span class="badge badge-cancelled" style="margin-left:4px">EXPIRED</span>':''}</td>
      <td>${esc(d.categoryName)||'—'}</td>
      <td>${esc(d.employmentType)}${d.vendorName?'<br><small style="color:#888">'+esc(d.vendorName)+'</small>':''}</td>
      <td>${d.dailyCharge!=null?CUR+d.dailyCharge:'—'}</td>
      <td>${d.yearsExperience}</td>
      <td>${statusBadge(d.status)}</td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Edit" onclick="editDriver(${d.id})">&#9998;</button>
        <button class="icon-btn ${d.status==='OFF'?'':'del'}" title="${d.status==='OFF'?'Activate':'Deactivate'}"
                onclick="toggleDriverActive(${d.id}, '${d.status}', '${esc(d.name)}')">${d.status==='OFF'?'&#10003;':'&#8856;'}</button>
        <button class="icon-btn docs" title="Documents" onclick="openDrvDocs(${d.id}, '${esc(d.name)}')">&#128206;</button>
        <a class="icon-btn" title="Profile" href="/admin/drivers/${d.id}">&#128100;</a>
        <button class="icon-btn del" title="Delete" onclick="deleteDriver(${d.id}, '${esc(d.name)}')">&#128465;</button>
      </div></td>
    </tr>`).join('');
  ST.page = pg.page;
  AdminTable.pager(document.getElementById('drvPager'), pg.page, pg.total, p => { ST.page = p; renderRows(); });
}

function clearErrors(){ document.querySelectorAll('#drvForm .fe').forEach(e=>{e.classList.remove('show');e.textContent='';});
  document.querySelectorAll('#drvForm .invalid').forEach(e=>e.classList.remove('invalid')); }
function setVal(id,v){ const el=document.getElementById(id); if(el) el.value=(v==null?'':v); }
function drvToggleVendor(){ document.getElementById('drvVendorWrap').style.opacity =
  document.getElementById('d_employmentType').value==='VENDOR' ? '1' : '.5'; }

function openDriverModal(){
  clearErrors(); document.getElementById('drvForm').reset();
  setVal('d_id',''); setVal('d_yearsExperience',0);
  AdminTable.resetFileboxes(document.getElementById('drvForm')); showDriverPreview('');
  document.getElementById('drvModalTitle').textContent='Add Driver';
  document.getElementById('drvModalTag').style.display='none';
  document.getElementById('drvProfileLink').style.display='none';
  drvToggleVendor();
  document.getElementById('drvModal').classList.add('open');
}

function showDriverPreview(url){
  const img=document.getElementById('d_photoPreview');
  if(url){ img.src=url; img.style.display='block'; } else { img.removeAttribute('src'); img.style.display='none'; }
}
function uploadDriverPhoto(input){
  const f=input.files[0]; if(!f) return;
  fileboxUpdate(input);
  const fd=new FormData(); fd.append('file', f);
  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('d_photoUrl',res.body.url); showDriverPreview(res.body.url); toast('Photo uploaded','ok'); }
      else toast(res.body.message||'Upload failed','err'); })
    .catch(()=>toast('Upload failed','err'));
}

function editDriver(id){
  clearErrors();
  fetch(API+'/'+id).then(r=>r.json()).then(d=>{
    setVal('d_id',d.id); setVal('d_name',d.name); setVal('d_phone',d.phone);
    setVal('d_licenceNumber',d.licenceNumber); setVal('d_licenceExpiry',d.licenceExpiry);
    setVal('d_yearsExperience',d.yearsExperience); setVal('d_photoUrl',d.photoUrl); showDriverPreview(d.photoUrl);
    setVal('d_categoryId',d.categoryId); setVal('d_employmentType',d.employmentType);
    setVal('d_vendorId',d.vendorId); setVal('d_status',d.status);
    setVal('d_hourlyCharge',d.hourlyCharge); setVal('d_dailyCharge',d.dailyCharge); setVal('d_monthlyCharge',d.monthlyCharge);
    document.getElementById('drvModalTitle').textContent='Edit Driver';
    document.getElementById('drvModalTag').style.display='inline-block';
    EDIT_DRV_ID = id; EDIT_DRV_NAME = d.name || '';
    document.getElementById('drvProfileLink').style.display='inline-block';
    drvToggleVendor();
    document.getElementById('drvModal').classList.add('open');
  });
}

function closeDriverModal(){ document.getElementById('drvModal').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 saveDriver(){
  clearErrors();
  const payload={
    id:numOrNull('d_id'), name:document.getElementById('d_name').value, phone:strOrNull('d_phone'),
    licenceNumber:document.getElementById('d_licenceNumber').value, licenceExpiry:strOrNull('d_licenceExpiry'),
    yearsExperience:numOrNull('d_yearsExperience'), categoryId:numOrNull('d_categoryId'),
    employmentType:document.getElementById('d_employmentType').value, vendorId:numOrNull('d_vendorId'),
    hourlyCharge:numOrNull('d_hourlyCharge'), dailyCharge:numOrNull('d_dailyCharge'), monthlyCharge:numOrNull('d_monthlyCharge'),
    status:document.getElementById('d_status').value, photoUrl:strOrNull('d_photoUrl')
  };
  const btn=document.getElementById('drvSaveBtn'); 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){ closeDriverModal(); toast(payload.id?'Driver updated':'Driver added','ok'); loadDrivers(); }
      else{
        const errs=res.body.errors||{};
        Object.keys(errs).forEach(k=>{ const e=document.getElementById('de_'+k), inp=document.getElementById('d_'+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 driver','err');
      }
    }).catch(()=>toast('Network error','err'))
    .finally(()=>{ btn.disabled=false; btn.textContent='Save Driver'; });
}

function deleteDriver(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('Driver deleted','ok');loadDrivers();} else toast(res.body.message||'Could not delete','err'); })
    .catch(()=>toast('Network error','err'));
}

/* Activate (AVAILABLE) / deactivate (OFF) a driver in one click. */
function toggleDriverActive(id, current, name){
  const next = current==='OFF' ? 'AVAILABLE' : 'OFF';
  if(next==='OFF' && !confirm('Deactivate '+name+'? They won\'t be assignable to trips.')) return;
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/status?status='+next,{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ toast(name+(next==='OFF'?' deactivated':' activated'),'ok'); loadDrivers(); }
      else toast((res.body&&res.body.message)||'Could not update','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 modal ---------- */
let EDIT_DRV_ID = null, EDIT_DRV_NAME = '', DOCS_DRV = null;
function openDrvDocs(id, name){
  DOCS_DRV = id;
  document.getElementById('drvDocsName').textContent = name || ('#'+id);
  closeDriverModal();
  document.getElementById('drvDocRows').innerHTML = '<div class="media-empty">Loading…</div>';
  loadDrvDocs(id);
  document.getElementById('drvDocsModal').classList.add('open');
}
function closeDrvDocs(){ document.getElementById('drvDocsModal').classList.remove('open'); }
function loadDrvDocs(id){
  fetch(API+'/'+id+'/documents').then(r=>r.json()).then(m=>renderDrvDocs(m.documents));
}
function drvDocState(s){
  const cls = s==='EXPIRED' ? 'badge-cancelled' : (s==='EXPIRING' ? 'badge-pending' : 'badge-confirmed');
  return '<span class="badge '+cls+'">'+s+'</span>';
}
function renderDrvDocs(docs){
  const c=document.getElementById('drvDocRows');
  c.innerHTML = (docs && docs.length) ? docs.map(d=>`
    <div class="doc-card">
      <div>
        <div class="doc-card-type">${esc(d.docType)} ${drvDocState(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="delDrvDoc(${d.id})">&#128465;</button>
    </div>`).join('') : '<div class="media-empty">No documents yet.</div>';
}
function drvMediaPost(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 addDrvDoc(){
  const fd=new FormData();
  fd.append('docType', document.getElementById('dm_docType').value);
  const f=document.getElementById('dm_file').files[0]; if(f) fd.append('file', f);
  const iss=document.getElementById('dm_issued').value; if(iss) fd.append('issuedDate', iss);
  const exp=document.getElementById('dm_expiry').value; if(exp) fd.append('expiryDate', exp);
  drvMediaPost(API+'/'+DOCS_DRV+'/documents', fd).then(res=>{
    if(res.ok&&res.body.ok){ const fm=document.getElementById('drvDocForm'); fm.reset(); AdminTable.resetFileboxes(fm); toast('Document added','ok'); loadDrvDocs(DOCS_DRV); }
    else toast(res.body.message||'Could not add','err');
  }).catch(()=>toast('Network error','err'));
}
function delDrvDoc(docId){
  drvMediaPost(API+'/'+DOCS_DRV+'/documents/'+docId+'/delete', null)
    .then(()=>{ toast('Document removed','ok'); loadDrvDocs(DOCS_DRV); }).catch(()=>toast('Network error','err'));
}

document.getElementById('drvModal').addEventListener('click',e=>{ if(e.target.id==='drvModal') closeDriverModal(); });
document.getElementById('drvDocsModal').addEventListener('click',e=>{ if(e.target.id==='drvDocsModal') closeDrvDocs(); });
document.addEventListener('keydown',e=>{ if(e.key==='Escape'){ closeDriverModal(); closeDrvDocs(); } });
AdminTable.attachSort(document.querySelector('.table-wrap thead tr'), ST, ()=>{ ST.page=1; renderRows(); });
loadDrivers();
// Deep-link: /admin/drivers?edit={id} opens the edit modal (e.g. from the profile page)
(function(){ const eid=new URLSearchParams(location.search).get('edit'); if(eid) editDriver(eid); })();
</script>

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