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

<section>
    <div class="container">
        <div class="page-header">
            <h1>Vendors</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openVendorModal()">+ Add Vendor</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="vSearch" type="text"
                   placeholder="Search name, contact or phone…" oninput="renderRows()"/>
            <span id="vCount" 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="contactPerson">Contact</th>
                    <th data-sort="phone">Phone</th><th data-sort="commissionPercent">Commission %</th>
                    <th data-sort="active">Active</th><th></th></tr>
                </thead>
                <tbody id="vRows">
                <tr><td colspan="7" class="table-loading">Loading vendors…</td></tr>
                </tbody>
            </table>
        </div>
        <div class="pager" id="vPager"></div>
    </div>
</section>

<!-- ============ Add/Edit modal ============ -->
<div class="modal-overlay" id="vModal">
    <div class="modal-card" style="max-width:680px">
        <div class="modal-head">
            <h2><span id="vModalTitle">Add Vendor</span><span class="tag" id="vModalTag" style="display:none">Edit</span></h2>
            <button class="modal-close" type="button" onclick="closeVendorModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="vForm" onsubmit="return false">
                <input type="hidden" id="v_id"/>
                <div class="form-grid2">
                    <div class="form-group field">
                        <label>Name</label><input type="text" id="v_name"/>
                        <small class="fe" id="ve_name"></small>
                    </div>
                    <div class="form-group field"><label>Contact Person</label><input type="text" id="v_contactPerson"/></div>
                    <div class="form-group field"><label>Phone</label><input type="tel" id="v_phone"/></div>
                    <div class="form-group field"><label>Email</label><input type="email" id="v_email"/></div>
                    <div class="form-group field"><label>GST Number</label><input type="text" id="v_gstNumber"/></div>
                    <div class="form-group field"><label>Commission % (blank = global default)</label><input type="number" step="0.01" id="v_commissionPercent"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Address</label><input type="text" id="v_address"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Settlement / Bank Details</label><input type="text" id="v_settlementDetails" placeholder="Account no, IFSC, UPI…"/></div>
                    <div class="form-group" style="grid-column:1 / -1">
                        <label style="font-weight:500;color:#444"><input type="checkbox" id="v_active" checked/> Active</label>
                    </div>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <a id="vOpenLink" class="btn btn-ghost btn-sm" style="display:none">Settlements &amp; portal &rarr;</a>
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeVendorModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="vSaveBtn" type="button" onclick="saveVendor()">Save Vendor</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/vendors';
let VENDORS=[];
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 loadVendors(){ fetch(API).then(r=>r.json()).then(d=>{VENDORS=d;renderRows();})
  .catch(()=>{document.getElementById('vRows').innerHTML='<tr><td colspan="7" class="table-loading">Failed to load.</td></tr>';}); }

function renderRows(){
  const q=(document.getElementById('vSearch').value||'').toLowerCase();
  let rows=VENDORS.filter(v=>!q||(v.name+' '+(v.contactPerson||'')+' '+(v.phone||'')).toLowerCase().includes(q));
  rows = AdminTable.sort(rows, ST.sortKey, ST.sortDir);
  document.getElementById('vCount').textContent=rows.length+' vendor'+(rows.length===1?'':'s');
  const tb=document.getElementById('vRows');
  if(!rows.length){ tb.innerHTML='<tr><td colspan="7" class="table-loading">No vendors found.</td></tr>';
    document.getElementById('vPager').innerHTML=''; return; }
  const pg = AdminTable.paginate(rows, ST.page, ST.pageSize);
  tb.innerHTML=pg.slice.map(v=>`
    <tr>
      <td>${v.id}</td>
      <td><a href="/admin/vendors/${v.id}">${esc(v.name)}</a></td>
      <td>${esc(v.contactPerson)||'—'}</td>
      <td>${esc(v.phone)||'—'}</td>
      <td>${v.commissionPercent!=null?v.commissionPercent+'%':'default'}</td>
      <td><span class="badge ${v.active?'badge-confirmed':'badge-cancelled'}">${v.active?'YES':'NO'}</span></td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Edit" onclick="editVendor(${v.id})">&#9998;</button>
        <a class="icon-btn docs" title="Settlements & portal" href="/admin/vendors/${v.id}">&#128202;</a>
        <button class="icon-btn del" title="Delete" onclick="deleteVendor(${v.id}, '${esc(v.name)}')">&#128465;</button>
      </div></td>
    </tr>`).join('');
  ST.page = pg.page;
  AdminTable.pager(document.getElementById('vPager'), pg.page, pg.total, p => { ST.page = p; renderRows(); });
}

function clearErrors(){ document.querySelectorAll('#vForm .fe').forEach(e=>{e.classList.remove('show');e.textContent='';});
  document.querySelectorAll('#vForm .invalid').forEach(e=>e.classList.remove('invalid')); }
function setVal(id,v){ const el=document.getElementById(id); if(el) el.value=(v==null?'':v); }

function openVendorModal(){
  clearErrors(); document.getElementById('vForm').reset(); setVal('v_id','');
  document.getElementById('v_active').checked=true;
  document.getElementById('vModalTitle').textContent='Add Vendor';
  document.getElementById('vModalTag').style.display='none';
  document.getElementById('vOpenLink').style.display='none';
  document.getElementById('vModal').classList.add('open');
}

function editVendor(id){
  clearErrors();
  fetch(API+'/'+id).then(r=>r.json()).then(v=>{
    setVal('v_id',v.id); setVal('v_name',v.name); setVal('v_contactPerson',v.contactPerson);
    setVal('v_phone',v.phone); setVal('v_email',v.email); setVal('v_gstNumber',v.gstNumber);
    setVal('v_commissionPercent',v.commissionPercent); setVal('v_address',v.address);
    setVal('v_settlementDetails',v.settlementDetails);
    document.getElementById('v_active').checked=!!v.active;
    document.getElementById('vModalTitle').textContent='Edit Vendor';
    document.getElementById('vModalTag').style.display='inline-block';
    const ol=document.getElementById('vOpenLink'); ol.href='/admin/vendors/'+id; ol.style.display='inline-block';
    document.getElementById('vModal').classList.add('open');
  });
}

function closeVendorModal(){ document.getElementById('vModal').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 saveVendor(){
  clearErrors();
  const payload={ id:numOrNull('v_id'), name:document.getElementById('v_name').value,
    contactPerson:strOrNull('v_contactPerson'), phone:strOrNull('v_phone'), email:strOrNull('v_email'),
    address:strOrNull('v_address'), gstNumber:strOrNull('v_gstNumber'),
    settlementDetails:strOrNull('v_settlementDetails'), commissionPercent:numOrNull('v_commissionPercent'),
    active:document.getElementById('v_active').checked };
  const btn=document.getElementById('vSaveBtn'); 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){ closeVendorModal(); toast(payload.id?'Vendor updated':'Vendor added','ok'); loadVendors(); }
      else{ const errs=res.body.errors||{};
        Object.keys(errs).forEach(k=>{ const e=document.getElementById('ve_'+k), inp=document.getElementById('v_'+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 vendor','err'); }
    }).catch(()=>toast('Network error','err'))
    .finally(()=>{ btn.disabled=false; btn.textContent='Save Vendor'; });
}

function deleteVendor(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('Vendor deleted','ok');loadVendors();} 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); }

document.getElementById('vModal').addEventListener('click',e=>{ if(e.target.id==='vModal') closeVendorModal(); });
document.addEventListener('keydown',e=>{ if(e.key==='Escape') closeVendorModal(); });
AdminTable.attachSort(document.querySelector('.table-wrap thead tr'), ST, ()=>{ ST.page=1; renderRows(); });
loadVendors();
// Deep-link: /admin/vendors?edit={id} opens the edit modal (e.g. from the vendor detail page)
(function(){ const eid=new URLSearchParams(location.search).get('edit'); if(eid) editVendor(eid); })();
</script>

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