{{ define "content" }}
<h1>{{ T "settings.title" }}</h1>
<div class="card" id="registration">
  <h2>{{ T "settings.enrol.title" }}</h2>
  {{ if enrolled }}
    <p>✅ {{ T "settings.enrol.registered" }}</p>
    {{ if enrolstore }}<p class="muted">{{ T "settings.enrol.store" }}: <code>{{ enrolstore }}</code></p>{{ end }}
    {{ if enroldevice }}<p class="muted">{{ T "settings.enrol.device" }}: <code>{{ enroldevice }}</code></p>{{ end }}
  {{ else }}
    <p>⚠️ {{ T "settings.enrol.not_registered" }}</p>
    <p class="muted">{{ T "settings.enrol.benefits" }}</p>
    {{ if .isManager }}
    <div style="display:flex; gap:.4rem; align-items:center">
      <button class="btn btn-touch" hx-post="/api/enrol/now" hx-target="#enrol-msg" hx-swap="innerHTML">{{ T "settings.enrol.retry" }}</button>
      <span id="enrol-msg" aria-live="polite"></span>
    </div>
    {{ end }}
  {{ end }}
</div>
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.theme.title" }}</h2>
  <form hx-post="/api/settings/theme" hx-swap="none" hx-on::after-request="window.location.reload()">
    <select name="theme">
      {{ $current := .theme }}
      {{ range .themes }}
      <option value="{{ .Key }}" {{ if eq .Key $current }}selected{{ end }}>{{ .Label }}{{ if ne .Source "built-in" }} ({{ .Source }}){{ end }}</option>
      {{ end }}
    </select>
    <button class="btn" type="submit">{{ T "settings.theme.apply" }}</button>
  </form>
</div>
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.display.title" }}</h2>
  <p class="muted">{{ T "settings.display.help" }}</p>
  <form hx-post="/api/settings/ui-scale" hx-swap="none" hx-on::after-request="window.location.reload()">
    {{ $scale := .uiScale }}
    <select name="scale">
      <option value="0.7"  {{ if eq $scale "0.7" }}selected{{ end }}>70% — {{ T "settings.display.tiny" }}</option>
      <option value="0.8"  {{ if eq $scale "0.8" }}selected{{ end }}>80% — {{ T "settings.display.small" }}</option>
      <option value="0.9"  {{ if eq $scale "0.9" }}selected{{ end }}>90%</option>
      <option value="1"    {{ if eq $scale "1" }}selected{{ end }}>100% — {{ T "settings.display.default" }}</option>
      <option value="1.15" {{ if eq $scale "1.15" }}selected{{ end }}>115%</option>
      <option value="1.3"  {{ if eq $scale "1.3" }}selected{{ end }}>130% — {{ T "settings.display.large" }}</option>
      <option value="1.5"  {{ if eq $scale "1.5" }}selected{{ end }}>150%</option>
    </select>
    <button class="btn" type="submit">{{ T "settings.display.apply" }}</button>
  </form>
</div>
{{ if .isManager }}
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.backup.title" }}</h2>
  <p class="muted">{{ T "settings.backup.help" }}</p>
  <div style="display:flex; gap:.4rem; align-items:center; margin-bottom:.6rem">
    <button class="btn" hx-post="/api/backup/now" hx-target="#backup-msg" hx-swap="innerHTML">{{ T "settings.backup.now" }}</button>
    <span id="backup-msg" aria-live="polite"></span>
  </div>
  {{ if .backups }}
  <table class="table">
    <thead><tr><th>{{ T "settings.backup.col_file" }}</th><th>{{ T "settings.backup.col_date" }}</th><th>{{ T "settings.backup.col_size" }}</th><th></th></tr></thead>
    <tbody>
      {{ range .backups }}
      <tr>
        <td style="font-family:monospace">{{ .Name }}</td>
        <td>{{ .Date }}</td>
        <td>{{ .Size }}</td>
        <td style="display:flex; gap:.3rem">
          <a class="btn secondary" href="/api/backup/download/{{ .Name }}">{{ T "settings.backup.download" }}</a>
          <form hx-post="/api/backup/restore" hx-target="#restore-msg" hx-swap="innerHTML" style="display:flex; gap:.3rem">
            <input type="hidden" name="name" value="{{ .Name }}">
            <input type="text" name="confirm" placeholder="{{ T "settings.backup.confirm_placeholder" }}" style="width:8rem" required>
            <button class="btn secondary" type="submit">{{ T "settings.backup.restore" }}</button>
          </form>
        </td>
      </tr>
      {{ end }}
    </tbody>
  </table>
  <div id="restore-msg" class="muted" aria-live="polite" style="min-height:1.2rem"></div>
  <p class="muted">{{ T "settings.backup.restore_note" }}</p>
  {{ else }}
  <p class="muted">{{ T "settings.backup.none_yet" }}</p>
  {{ end }}
</div>

<div class="card" style="margin-top:1rem">
  <h2>🧹 {{ T "settings.data.title" }}</h2>
  <p class="muted">{{ T "settings.data.help" }}</p>
  <p class="muted" style="color:#b45309">{{ T "settings.data.warn" }}</p>
  <div style="display:flex; gap:.4rem; align-items:center; flex-wrap:wrap">
    <input type="text" id="data-reset-confirm" placeholder="{{ T "settings.data.confirm_ph" }}" style="width:9rem">
    <button class="btn secondary" id="data-reset-btn" data-testid="data-reset">{{ T "settings.data.reset_btn" }}</button>
    <span id="data-reset-msg" class="muted" aria-live="polite" style="min-height:1.2rem"></span>
  </div>

  <hr style="margin:1.2rem 0; border:0; border-top:1px solid var(--border)">
  <h3 style="margin:0 0 .3rem">{{ T "settings.data.gdpr_title" }}</h3>
  <p class="muted">{{ T "settings.data.gdpr_help" }}</p>
  <div style="display:flex; gap:.4rem; align-items:center; flex-wrap:wrap">
    <input type="text" id="cust-q" placeholder="{{ T "settings.data.customer_search_ph" }}" style="width:14rem">
    <button class="btn secondary" id="cust-search-btn">{{ T "settings.data.search_btn" }}</button>
    <span id="cust-msg" class="muted" aria-live="polite"></span>
  </div>
  <div id="cust-results" style="margin-top:.5rem"></div>

  <hr style="margin:1.2rem 0; border:0; border-top:1px solid var(--border)">
  <h3 style="margin:0 0 .3rem">{{ T "settings.data.catalog_title" }}</h3>
  <p class="muted">{{ T "settings.data.catalog_help" }}</p>
  <div style="display:flex; gap:.4rem; align-items:center; flex-wrap:wrap">
    <button class="btn secondary" id="cat-preview-btn">{{ T "settings.data.catalog_preview_btn" }}</button>
    <input type="text" id="cat-confirm" placeholder="{{ T "settings.data.catalog_confirm_ph" }}" style="width:9rem">
    <button class="btn secondary" id="cat-cleanup-btn" data-testid="data-cleanup" disabled>{{ T "settings.data.catalog_cleanup_btn" }}</button>
    <span id="cat-msg" class="muted" aria-live="polite" style="min-height:1.2rem"></span>
  </div>
  <div id="cat-results" style="margin-top:.5rem"></div>
</div>

<script>
(function () {
  var btn = document.getElementById('data-reset-btn');
  if (!btn) return;
  var msg = document.getElementById('data-reset-msg');
  var inp = document.getElementById('data-reset-confirm');
  btn.addEventListener('click', function () {
    if (inp.value.trim() !== 'RESET') { msg.textContent = '✗ type RESET to confirm'; return; }
    if (!confirm('Permanently clear ALL sales, shifts and invoices? The catalog, users and settings are kept. This cannot be undone.')) return;
    btn.disabled = true; msg.textContent = '⏳ clearing…';
    fetch('/api/data/reset-transactions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ confirm: inp.value.trim() }).toString()
    }).then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) {
      btn.disabled = false;
      msg.textContent = (r.ok ? '✓ ' : '✗ ') + (j.message || ('HTTP ' + r.status));
      if (r.ok) inp.value = '';
    }); }).catch(function (e) { btn.disabled = false; msg.textContent = '✗ ' + e; });
  });
})();
(function () {
  var sb = document.getElementById('cust-search-btn');
  if (!sb) return;
  var q = document.getElementById('cust-q');
  var out = document.getElementById('cust-results');
  var msg = document.getElementById('cust-msg');
  function esc(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
  function search() {
    msg.textContent = '…';
    fetch('/api/data/customers?q=' + encodeURIComponent(q.value.trim()))
      .then(function (r) { return r.json(); })
      .then(function (j) {
        msg.textContent = '';
        var list = (j.customers) || [];
        if (!list.length) { out.innerHTML = '<p class="muted">No matches.</p>'; return; }
        out.innerHTML = list.map(function (c) {
          return '<div style="display:flex;gap:.5rem;align-items:center;margin:.2rem 0">'
            + '<span>' + esc(c.Name) + (c.Phone ? ' · ' + esc(c.Phone) : '') + (c.Email ? ' · ' + esc(c.Email) : '') + '</span>'
            + '<button class="btn secondary" data-erase="' + esc(c.ID) + '">Erase</button></div>';
        }).join('');
      }).catch(function (e) { msg.textContent = '✗ ' + e; });
  }
  sb.addEventListener('click', search);
  q.addEventListener('keydown', function (e) { if (e.key === 'Enter') search(); });
  out.addEventListener('click', function (ev) {
    var b = ev.target.closest('[data-erase]');
    if (!b) return;
    if (!confirm("Erase this customer's personal data? Their sales are kept but anonymised. This cannot be undone.")) return;
    b.disabled = true;
    fetch('/api/data/customers/erase', {
      method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ id: b.getAttribute('data-erase') }).toString()
    }).then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) {
      msg.textContent = (r.ok ? '✓ ' : '✗ ') + (j.message || ('HTTP ' + r.status));
      if (r.ok) { b.closest('div').remove(); } else { b.disabled = false; }
    }); }).catch(function (e) { b.disabled = false; msg.textContent = '✗ ' + e; });
  });
})();
(function () {
  var pv = document.getElementById('cat-preview-btn');
  if (!pv) return;
  var run = document.getElementById('cat-cleanup-btn');
  var conf = document.getElementById('cat-confirm');
  var out = document.getElementById('cat-results');
  var msg = document.getElementById('cat-msg');
  function esc(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
  pv.addEventListener('click', function () {
    msg.textContent = '…';
    fetch('/api/data/obsolete-items')
      .then(function (r) { return r.json(); })
      .then(function (j) {
        msg.textContent = '';
        var list = (j.items) || [];
        run.disabled = list.length === 0;
        if (!list.length) { out.innerHTML = '<p class="muted">Nothing to remove — no inactive, never-sold products.</p>'; return; }
        out.innerHTML = '<p class="muted">' + list.length + ' product(s) will be removed:</p>'
          + list.map(function (it) {
              return '<div style="margin:.15rem 0">' + esc(it.Name) + (it.SKU ? ' · ' + esc(it.SKU) : '') + '</div>';
            }).join('');
      }).catch(function (e) { msg.textContent = '✗ ' + e; });
  });
  run.addEventListener('click', function () {
    if (conf.value.trim() !== 'CLEANUP') { msg.textContent = '✗ type CLEANUP to confirm'; return; }
    if (!confirm('Permanently delete these inactive, never-sold products? This cannot be undone.')) return;
    run.disabled = true; msg.textContent = '⏳ removing…';
    fetch('/api/data/cleanup-catalog', {
      method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ confirm: conf.value.trim() }).toString()
    }).then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) {
      msg.textContent = (r.ok ? '✓ ' : '✗ ') + (j.message || ('HTTP ' + r.status));
      if (r.ok) { conf.value = ''; out.innerHTML = ''; run.disabled = true; }
      else { run.disabled = false; }
    }); }).catch(function (e) { run.disabled = false; msg.textContent = '✗ ' + e; });
  });
})();
</script>
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.printer.title" }}</h2>
  <p class="muted">{{ T "settings.printer.help" }}</p>
  <form hx-post="/api/settings/printer" hx-swap="none" hx-on::after-request="window.location.reload()">
    {{ $p := .printer }}
    <div class="field-pair">
      <label>{{ T "settings.printer.mode" }}
        <select name="mode">
          <option value="off"     {{ if eq $p.Mode "off" }}selected{{ end }}>{{ T "settings.printer.mode_off" }}</option>
          <option value="network" {{ if eq $p.Mode "network" }}selected{{ end }}>{{ T "settings.printer.mode_network" }}</option>
          <option value="device"  {{ if eq $p.Mode "device" }}selected{{ end }}>{{ T "settings.printer.mode_device" }}</option>
        </select>
      </label>
      <label>{{ T "settings.printer.charset" }}
        <select name="charset">
          <option value="utf8"  {{ if eq $p.Charset "utf8" }}selected{{ end }}>UTF-8</option>
          <option value="ascii" {{ if eq $p.Charset "ascii" }}selected{{ end }}>ASCII</option>
        </select>
      </label>
    </div>
    <div class="field-pair">
      <label>{{ T "settings.printer.address" }} <input type="text" name="address" value="{{ $p.Address }}" placeholder="192.168.1.50:9100"></label>
      <label>{{ T "settings.printer.device" }} <input type="text" name="device" value="{{ $p.Device }}" placeholder="/dev/usb/lp0"></label>
    </div>
    <label>{{ T "settings.printer.kitchen_addr" }}
      <input type="text" name="kitchenAddr" value="{{ $p.KitchenAddress }}" placeholder="192.168.1.60:9100">
      <span class="muted">{{ T "settings.printer.kitchen_help" }}</span>
    </label>
    <label><input type="checkbox" name="autoPrint" {{ if $p.AutoPrint }}checked{{ end }}> {{ T "settings.printer.auto" }}</label>
    <div style="display:flex; gap:.4rem; align-items:center; margin-top:.5rem">
      <button class="btn" type="submit">{{ T "settings.printer.apply" }}</button>
      <button class="btn secondary" type="button" hx-post="/api/print/test" hx-target="#print-test-msg" hx-swap="innerHTML">{{ T "settings.printer.test" }}</button>
      <a class="btn secondary" href="/receipt-designer">{{ T "designer.receipt.title" }}</a>
      <a class="btn secondary" href="/tills">{{ T "tills.title" }}</a>
      <span id="print-test-msg" aria-live="polite"></span>
    </div>
  </form>
</div>
<div class="card" style="margin-top:1rem">
  <h2>🧾 {{ T "settings.invoice.title" }}</h2>
  <p class="muted">{{ T "settings.invoice.help" }}</p>
  <form hx-post="/api/settings/invoice" hx-swap="none" hx-on::after-request="window.location.reload()">
    <div class="field-pair">
      <label>{{ T "settings.invoice.seller_name" }}
        <input type="text" name="seller_name" value="{{ index .settingsMap "invoice.seller_name" }}"></label>
      <label>{{ T "settings.invoice.seller_vat_no" }}
        <input type="text" name="seller_vat_no" value="{{ index .settingsMap "invoice.seller_vat_no" }}"></label>
    </div>
    <label>{{ T "settings.invoice.seller_address" }}
      <input type="text" name="seller_address" value="{{ index .settingsMap "invoice.seller_address" }}"></label>
    <div style="margin-top:.5rem">
      <button class="btn" type="submit">{{ T "settings.invoice.apply" }}</button>
    </div>
  </form>
</div>
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.idle_lock.title" }}</h2>
  <p class="muted">{{ T "settings.idle_lock.help" }}</p>
  <form hx-post="/api/settings/idle-lock" hx-swap="none" hx-on::after-request="window.location.reload()">
    {{ $idle := .settings.IdleLockMinutes }}
    <select name="minutes">
      <option value="0"  {{ if eq $idle 0 }}selected{{ end }}>{{ T "settings.idle_lock.off" }}</option>
      <option value="2"  {{ if eq $idle 2 }}selected{{ end }}>2 {{ T "settings.idle_lock.minutes" }}</option>
      <option value="5"  {{ if eq $idle 5 }}selected{{ end }}>5 {{ T "settings.idle_lock.minutes" }}</option>
      <option value="10" {{ if eq $idle 10 }}selected{{ end }}>10 {{ T "settings.idle_lock.minutes" }}</option>
      <option value="15" {{ if eq $idle 15 }}selected{{ end }}>15 {{ T "settings.idle_lock.minutes" }}</option>
      <option value="30" {{ if eq $idle 30 }}selected{{ end }}>30 {{ T "settings.idle_lock.minutes" }}</option>
      <option value="60" {{ if eq $idle 60 }}selected{{ end }}>60 {{ T "settings.idle_lock.minutes" }}</option>
    </select>
    <button class="btn" type="submit">{{ T "settings.idle_lock.apply" }}</button>
  </form>
</div>
{{ end }}
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.currency.title" }}</h2>
  <p class="muted">{{ T "settings.currency.help" }}</p>
  <form hx-post="/api/settings/save" hx-swap="none" hx-on::after-request="window.location.reload()">
    {{ $cur := currency }}
    <select name="currency">
      {{ range currencies }}
      <option value="{{ .Code }}" {{ if eq .Code $cur.Code }}selected{{ end }}>{{ .Name }}</option>
      {{ end }}
    </select>
    <button class="btn" type="submit">{{ T "settings.currency.apply" }}</button>
  </form>
  <p class="muted">{{ T "settings.currency.warning" }}</p>
</div>
<div class="card" style="margin-top:1rem">
  <h2>{{ T "settings.all" }}</h2>
  <table class="table">
    <thead>
      <tr><th>{{ T "settings.key" }}</th><th>{{ T "settings.value" }}</th><th></th></tr>
    </thead>
    <tbody>
    {{ range $k, $v := .settingsMap }}
      <tr>
        <td><code>{{ $k }}</code></td>
        <td>
          <input type="text" name="value" value="{{ $v }}" hx-post="/api/settings/upsert" hx-include="closest tr" hx-swap="none">
          <input type="hidden" name="key" value="{{ $k }}">
        </td>
        <td><button class="btn secondary" hx-post="/api/settings/upsert" hx-include="closest tr" hx-swap="none">{{ T "settings.update" }}</button></td>
      </tr>
    {{ end }}
      <tr>
        <td><input type="text" name="key" placeholder="new.key" form="new-setting"></td>
        <td><input type="text" name="value" placeholder="value" form="new-setting"></td>
        <td><button class="btn" type="submit" form="new-setting">{{ T "settings.add_update" }}</button></td>
      </tr>
    </tbody>
  </table>
  <form id="new-setting" hx-post="/api/settings/upsert" hx-swap="none"></form>
</div>
{{ end }}
