<%- include('../partials/header') %>
<div class="page-head">
  <h1>Import — <%= s.name %></h1>
  <a class="btn btn-ghost" href="<%= base %>/suppliers/<%= s.id %>">Annuler</a>
</div>
<p class="muted">Fichier : <strong><%= up.meta.name %></strong> — <%= table.rows.length %> ligne(s) lue(s)</p>

<% errors.forEach(e => { %><div class="alert alert-error"><%= e %></div><% }) %>

<form method="post" class="card form" id="mapping-form">
  <input type="hidden" name="_csrf" value="<%= csrf %>">
  <h2>1. Lecture du fichier</h2>
  <div class="row wrap">
    <% if (table.sheets.length) { %>
      <label>Onglet
        <select name="sheet" data-autopreview>
          <% table.sheets.forEach(n => { %><option <%= n === table.sheet ? 'selected' : '' %>><%= n %></option><% }) %>
        </select>
      </label>
    <% } else { %>
      <label>Séparateur
        <select name="delimiter" data-autopreview>
          <% [['auto', `Auto (${table.detectedDelimiter === 'tab' ? 'tabulation' : table.detectedDelimiter})`], [';', 'Point-virgule ;'], [',', 'Virgule ,'], ['tab', 'Tabulation'], ['|', 'Barre |']].forEach(([v, l]) => { %>
            <option value="<%= v %>" <%= (mapping.delimiter || 'auto') === v ? 'selected' : '' %>><%= l %></option>
          <% }) %>
        </select>
      </label>
      <label>Encodage
        <select name="encoding" data-autopreview>
          <% [['auto', 'Auto'], ['utf8', 'UTF-8'], ['win1252', 'Windows-1252 / ANSI'], ['latin1', 'ISO-8859-1'], ['utf16le', 'UTF-16']].forEach(([v, l]) => { %>
            <option value="<%= v %>" <%= (mapping.encoding || 'auto') === v ? 'selected' : '' %>><%= l %></option>
          <% }) %>
        </select>
      </label>
    <% } %>
    <label>Ligne d’en-tête
      <input type="number" name="header_row" min="0" value="<%= mapping.header_row %>" data-autopreview>
      <small>0 = pas d’en-tête</small>
    </label>
    <label>Séparateur décimal
      <select name="decimal">
        <% [['auto', 'Auto'], [',', 'Virgule (12,50)'], ['.', 'Point (12.50)']].forEach(([v, l]) => { %>
          <option value="<%= v %>" <%= (mapping.decimal || 'auto') === v ? 'selected' : '' %>><%= l %></option>
        <% }) %>
      </select>
    </label>
  </div>

  <h2>2. Correspondance des colonnes</h2>
  <div class="row wrap">
    <% FIELDS.forEach(([f, label]) => { %>
      <label><%= label %>
        <select name="col_<%= f %>" class="col-select" data-field="<%= f %>">
          <option value="">— ignorer —</option>
          <% cols.forEach(c => { %><option value="<%= c.key %>" <%= selected[f] === c.key ? 'selected' : '' %>><%= c.label %></option><% }) %>
        </select>
      </label>
    <% }) %>
    <label>Remise fournisseur (%)
      <input name="discount" value="<%= mapping.discount || 0 %>" inputmode="decimal">
      <small>Si le fichier contient des prix catalogue</small>
    </label>
  </div>
  <p class="small muted">Si seule la colonne EAN est renseignée, l’EAN sert de référence. Les colonnes sont mémorisées par leur nom d’en-tête : l’ordre peut changer d’un fichier à l’autre.</p>

  <h2>3. Mode d’import</h2>
  <label class="check"><input type="radio" name="mode" value="replace" <%= mapping.mode !== 'upsert' ? 'checked' : '' %>> Remplacer le tarif (les articles absents du fichier sont retirés)</label>
  <label class="check"><input type="radio" name="mode" value="upsert" <%= mapping.mode === 'upsert' ? 'checked' : '' %>> Compléter (mise à jour partielle, rien n’est retiré)</label>

  <div class="form-actions">
    <button class="btn" name="action" value="preview">Actualiser l’aperçu</button>
    <button class="btn btn-primary" name="action" value="import" <%= preview && preview.count ? '' : 'disabled' %>>Importer <%= preview ? preview.count : 0 %> article(s)</button>
  </div>
</form>

<% if (preview) { %>
<section class="card">
  <h2>Résultat interprété</h2>
  <p><strong><%= preview.count %></strong> article(s) valides sur <%= preview.total %> ligne(s)<%= preview.duplicates > 0 ? `, ${preview.duplicates} doublon(s) fusionné(s)` : '' %><%= preview.errors.length ? `, ${preview.errors.length} ligne(s) ignorée(s)` : '' %>.</p>
  <table class="table">
    <thead><tr><th>Référence</th><th>EAN</th><th>Désignation</th><th class="num">Prix d’achat HT</th><th class="num">Marge</th><th class="num">Vente HT avant arrondi</th></tr></thead>
    <tbody>
    <% preview.items.forEach(i => { %>
      <tr><td><%= i.reference %></td><td><%= i.ean %></td><td><%= i.name %></td><td class="num"><%= i.purchase_price.toFixed(2) %> €</td><td class="num muted"><%= i.margin_label %></td><td class="num muted"><%= i.sale == null ? '—' : i.sale.toFixed(2) + ' €' %></td></tr>
    <% }) %>
    </tbody>
  </table>
  <% if (preview.errors.length) { %>
    <details><summary>Lignes ignorées (<%= preview.errors.length %>)</summary><pre class="log small"><%= preview.errors.slice(0, 200).join('\n') %></pre></details>
  <% } %>
</section>
<% } %>

<section class="card">
  <h2>Aperçu brut du fichier (25 premières lignes)</h2>
  <div class="scroll-x">
  <table class="table raw">
    <thead><tr><th>#</th><% cols.forEach((c, i) => { const f = Object.keys(selected).find(k => selected[k] === c.key); %><th class="<%= f ? 'hl' : '' %>">Col. <%= i + 1 %><%= f ? ` → ${f}` : '' %></th><% }) %></tr></thead>
    <tbody>
    <% rows.forEach((r, i) => { %>
      <tr class="<%= i + 1 === Number(mapping.header_row) ? 'header-row' : (i + 1 < Number(mapping.header_row) ? 'dim' : '') %>">
        <td class="muted"><%= i + 1 %></td>
        <% cols.forEach((c, j) => { const f = Object.keys(selected).find(k => selected[k] === c.key); const v = r[j]; %>
          <td class="<%= f ? 'hl' : '' %>"><%= v instanceof Date ? v.toISOString().slice(0, 10) : String(v ?? '').slice(0, 60) %></td>
        <% }) %>
      </tr>
    <% }) %>
    </tbody>
  </table>
  </div>
</section>
<%- include('../partials/footer') %>
