<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Upload Purchase — Stock Locator</title>
<link rel="stylesheet" href="/static/css/style.css"/>
</head>
<body>
<div class="topbar">
  <div class="brand">Stock Locator</div>
  <a href="/purchase" class="active">Upload Purchase</a>
  <a href="/locations">Item Locations</a>
</div>
<div class="update-banner" id="updateBanner">
  <span id="updateText"></span>
  <button onclick="applyUpdate()">Update now</button>
  <button onclick="dismissUpdate()" style="background:transparent;color:#fff;border:1px solid rgba(255,255,255,.5);">Later</button>
</div>

<div class="wrap">
  <div class="card">
    <h1>Upload today's purchase</h1>
    <p class="sub">Upload the distributor's purchase Excel — every item shows its shelf location instantly, no typing.</p>
    <div class="dropzone" id="dropzone" onclick="document.getElementById('fileInput').click()">
      <div id="dzText">📦 Click or drop the purchase Excel here (.xlsx / .xls / .csv)</div>
      <input type="file" id="fileInput" accept=".xlsx,.xls,.csv"/>
    </div>
  </div>

  <div id="resultsCard" style="display:none;">
    <div class="stat-row">
      <div class="stat"><div class="n" id="statTotal">0</div><div class="l">Items</div></div>
      <div class="stat matched"><div class="n" id="statMatched">0</div><div class="l">Located</div></div>
      <div class="stat unmatched"><div class="n" id="statUnmatched">0</div><div class="l">Need location</div></div>
    </div>
    <div class="card">
      <h2>Results</h2>
      <table id="resultsTable">
        <thead><tr><th>Item</th><th>Qty</th><th>Location</th><th></th></tr></thead>
        <tbody id="resultsBody"></tbody>
      </table>
    </div>
  </div>
</div>

<div class="toast" id="toast"></div>
<script>
const dz = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag'); });
dz.addEventListener('dragleave', () => dz.classList.remove('drag'));
dz.addEventListener('drop', e => {
  e.preventDefault(); dz.classList.remove('drag');
  if(e.dataTransfer.files.length){ fileInput.files = e.dataTransfer.files; handleFile(); }
});
fileInput.addEventListener('change', handleFile);

let lastResults = [];

async function handleFile(){
  const f = fileInput.files[0];
  if(!f) return;
  document.getElementById('dzText').textContent = `Matching "${f.name}"…`;
  const fd = new FormData();
  fd.append('file', f);
  try{
    const r = await fetch('/api/purchase/match', {method:'POST', body: fd});
    const d = await r.json();
    if(!r.ok || d.error){ showToast(d.error || 'Could not read file', true); document.getElementById('dzText').textContent = '📦 Click or drop the purchase Excel here (.xlsx / .xls / .csv)'; return; }
    lastResults = d.results;
    renderResults(d);
    document.getElementById('dzText').textContent = `✓ ${f.name} — click or drop another file to re-check`;
  }catch(e){
    showToast('Upload failed: ' + e, true);
    document.getElementById('dzText').textContent = '📦 Click or drop the purchase Excel here (.xlsx / .xls / .csv)';
  }
}

function badgeFor(type){
  if(type === 'exact' || type === 'alias') return `<span class="badge b-exact">MATCHED</span>`;
  if(type === 'fuzzy') return `<span class="badge b-fuzzy">CHECK</span>`;
  return `<span class="badge b-none">NO LOCATION</span>`;
}

function renderResults(d){
  document.getElementById('resultsCard').style.display = 'block';
  document.getElementById('statTotal').textContent = d.total;
  document.getElementById('statMatched').textContent = d.matched;
  document.getElementById('statUnmatched').textContent = d.unmatched;
  const body = document.getElementById('resultsBody');
  body.innerHTML = d.results.map((r, i) => rowHtml(r, i)).join('');
}

function rowHtml(r, i){
  const isConfident = r.location_item_id && (r.match_type === 'exact' || r.match_type === 'alias');
  const isFuzzyConfirmed = r.location_item_id && r.match_type === 'fuzzy';
  let locCell;
  if(isConfident){
    locCell = `<span class="loc-pill">${escapeHtml(r.location || '—')}</span>`;
  } else if(isFuzzyConfirmed){
    locCell = `<span class="loc-pill">${escapeHtml(r.location || '—')}</span> ${badgeFor('fuzzy')}
      <div style="margin-top:4px;"><button class="suggest-btn" onclick="confirmMatch(${i})">✓ Confirm "${escapeHtml(r.matched_name)}"</button></div>`;
  } else if(r.suggestions && r.suggestions.length){
    locCell = `${badgeFor('none')}<div style="margin-top:4px;">` +
      r.suggestions.map((s, si) => `<button class="suggest-btn" onclick="pickSuggestion(${i}, ${si})">${escapeHtml(s.name)} → ${escapeHtml(s.location || '?')}</button>`).join('') +
      `<div style="margin-top:6px;display:flex;gap:6px;"><input class="input" style="width:auto;flex:1;" placeholder="or type new location" id="newloc-${i}"/>
      <button class="btn small" onclick="typeNewLocation(${i})">Save</button></div></div>`;
  } else {
    locCell = `${badgeFor('none')}<div style="margin-top:6px;display:flex;gap:6px;">
      <input class="input" style="width:auto;flex:1;" placeholder="type location, e.g. A14" id="newloc-${i}"/>
      <button class="btn small" onclick="typeNewLocation(${i})">Save</button></div>`;
  }
  return `<tr data-idx="${i}">
    <td data-label="Item">${escapeHtml(r.raw_name)}</td>
    <td data-label="Qty">${r.qty}</td>
    <td data-label="Location" colspan="2">${locCell}</td>
  </tr>`;
}

async function confirmMatch(i){
  const r = lastResults[i];
  await resolveLine(r.raw_name, r.location_item_id, null);
  r.match_type = 'alias';
  refreshRow(i, r);
}
async function pickSuggestion(i, si){
  const r = lastResults[i];
  const s = r.suggestions[si];
  await resolveLine(r.raw_name, s.id, null);
  r.location_item_id = s.id; r.location = s.location; r.matched_name = s.name; r.match_type = 'alias';
  refreshRow(i, r);
}
async function typeNewLocation(i){
  const val = document.getElementById(`newloc-${i}`).value.trim();
  if(!val){ showToast('Type a location first', true); return; }
  const r = lastResults[i];
  const d = await resolveLine(r.raw_name, null, val);
  r.location_item_id = d.location_item_id; r.location = d.location; r.matched_name = r.raw_name; r.match_type = 'alias';
  refreshRow(i, r);
}
async function resolveLine(raw_name, location_item_id, new_location){
  const r = await fetch('/api/purchase/resolve', {method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({raw_name, location_item_id, new_location})});
  const d = await r.json();
  if(!r.ok || d.error){ showToast(d.error || 'Could not save', true); return {}; }
  showToast('Saved — remembered for next time');
  return d;
}
function refreshRow(i, r){
  document.querySelector(`tr[data-idx="${i}"]`).outerHTML = rowHtml(r, i);
  document.getElementById('statMatched').textContent = lastResults.filter(x => x.location_item_id).length;
  document.getElementById('statUnmatched').textContent = lastResults.filter(x => !x.location_item_id).length;
}
function escapeHtml(s){
  return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
function showToast(msg, err){
  const t = document.getElementById('toast');
  t.textContent = msg; t.classList.toggle('err', !!err); t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 2500);
}

let updateInfo = null;
async function checkUpdate(){
  try{
    const r = await fetch('/api/update/check');
    if(!r.ok) return;
    const d = await r.json();
    if(d.update_available){
      updateInfo = d;
      document.getElementById('updateText').textContent = `New version ${d.latest_version} available — ${d.notes || ''}`;
      document.getElementById('updateBanner').classList.add('show');
    }
  }catch(e){ /* offline or not built yet — silently skip */ }
}
function dismissUpdate(){ document.getElementById('updateBanner').classList.remove('show'); }
async function applyUpdate(){
  if(!updateInfo) return;
  showToast('Downloading update…');
  try{
    const r = await fetch('/api/update/apply', {method:'POST'});
    const d = await r.json();
    if(d.status === 'ok'){ showToast('Updated! Please restart the app.'); dismissUpdate(); }
    else showToast(d.error || 'Update failed', true);
  }catch(e){ showToast('Update failed: ' + e, true); }
}
checkUpdate();
</script>
</body>
</html>
