<div class="wizard-steps" id="wzSteps">
  <?php foreach (['Unggah Berkas','Pilih Worksheet','Pratinjau Data','Deteksi Header','Pemetaan Kolom','Opsi Import',
                  'Validasi Data','Tinjau Kesalahan','Konfirmasi','Ringkasan'] as $i => $s): ?>
    <div class="wizard-step <?= $i === 0 ? 'active' : '' ?>" data-step="<?= $i + 1 ?>">
      <span class="n"><?= $i + 1 ?></span><span><?= e($s) ?></span></div>
  <?php endforeach; ?>
</div>

<!-- LANGKAH 1 -->
<div class="card mb-3" id="wz1">
  <div class="card-header"><i class="bi bi-cloud-upload me-1"></i>Langkah 1 — Unggah Berkas Excel / CSV</div>
  <div class="card-body">
    <form id="formUnggah" enctype="multipart/form-data">
      <?= csrf() ?>
      <div class="row g-3 align-items-end">
        <div class="col-md-8">
          <label class="form-label required" for="berkas">Berkas</label>
          <input type="file" class="form-control" id="berkas" name="berkas" accept=".xlsx,.xlsm,.csv,.txt" required>
          <div class="form-text">Format didukung: .xlsx, .xlsm, .csv. Ukuran maksimal <?= ukuranBerkas($maxUpload) ?>.</div>
        </div>
        <div class="col-md-4"><button class="btn btn-primary w-100" type="submit"><i class="bi bi-upload me-1"></i>Unggah &amp; Analisis</button></div>
      </div>
    </form>
    <div class="alert alert-info mt-3 mb-0 small">
      <strong><i class="bi bi-info-circle me-1"></i>Kolom hasil rumus Excel diabaikan otomatis.</strong>
      Kolom <code>JT TEMPO</code>, <code>TOTAL</code>, <code>SALDO</code>, <code>PAYMENT</code>, <code>UMUR PIUTANG</code>,
      dan seluruh kolom bucket aging tidak diimpor — seluruh nilai tersebut dihitung ulang oleh server memakai aturan bisnis
      yang terstandardisasi. Nilai asli Excel tetap disimpan untuk keperluan rekonsiliasi.
    </div>
  </div>
</div>

<!-- LANGKAH 2 -->
<div class="card mb-3 d-none" id="wz2">
  <div class="card-header"><i class="bi bi-files me-1"></i>Langkah 2 — Pilih Worksheet</div>
  <div class="card-body"><div class="table-wrap"><table class="table table-hover table-sm mb-0">
    <thead><tr><th style="width:40px"></th><th>Worksheet</th><th>Jenis Terdeteksi</th><th class="num">Kolom Dikenali</th><th>Kolom Rumus (diabaikan)</th></tr></thead>
    <tbody id="daftarSheet"></tbody>
  </table></div></div>
</div>

<!-- LANGKAH 3-5 -->
<div class="card mb-3 d-none" id="wz3">
  <div class="card-header"><i class="bi bi-eye me-1"></i>Langkah 3–5 — Pratinjau, Deteksi Header &amp; Pemetaan Kolom
    <div class="card-actions"><button class="btn btn-sm btn-light" type="button" id="btnKembali2"><i class="bi bi-arrow-left me-1"></i>Pilih Sheet Lain</button></div>
  </div>
  <div class="card-body">
    <h6 class="mb-2">Pemetaan Kolom Excel → Field Sistem</h6>
    <p class="small text-body-secondary">Sistem sudah menebak pemetaan berdasarkan judul kolom. Periksa dan sesuaikan bila perlu.
      Pilih <em>“— Abaikan kolom ini —”</em> untuk kolom yang tidak ingin diimpor.</p>
    <div class="table-wrap" style="max-height:420px"><table class="table table-sm table-sticky mb-0">
      <thead><tr><th style="width:60px">Kolom</th><th>Judul di Excel</th><th style="width:280px">Field Sistem</th><th>Contoh Nilai</th></tr></thead>
      <tbody id="tabelMapping"></tbody>
    </table></div>

    <h6 class="mt-3 mb-2">Pratinjau Data</h6>
    <div class="table-wrap" style="max-height:300px"><table class="table table-sm table-bordered mb-0" id="tabelPreview"></table></div>
  </div>
</div>

<!-- LANGKAH 6 -->
<div class="card mb-3 d-none" id="wz6">
  <div class="card-header"><i class="bi bi-gear me-1"></i>Langkah 6 — Opsi Import</div>
  <div class="card-body row g-3">
    <div class="col-md-4"><div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" id="optMaster" checked>
      <label class="form-check-label" for="optMaster">Buat master data baru otomatis</label>
      <div class="form-text">Area, sales, customer, outlet, dan kategori yang belum ada akan dibuat otomatis.</div></div></div>
    <div class="col-md-4"><div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" id="optDuplikat">
      <label class="form-check-label" for="optDuplikat">Perbarui invoice yang sudah ada</label>
      <div class="form-text">Bila tidak aktif, nomor invoice yang sudah ada akan ditolak.</div></div></div>
    <div class="col-md-4"><div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" id="optBayar" checked>
      <label class="form-check-label" for="optBayar">Buat transaksi pembayaran dari kolom PEMBAYARAN</label>
      <div class="form-text">Nilai pembayaran Excel dijadikan satu transaksi pembayaran per invoice.</div></div></div>
    <div class="col-12"><button class="btn btn-primary" type="button" id="btnValidasi"><i class="bi bi-shield-check me-1"></i>Langkah 7 — Validasi Data</button></div>
  </div>
</div>

<!-- LANGKAH 7-8 -->
<div class="card mb-3 d-none" id="wz7">
  <div class="card-header"><i class="bi bi-shield-check me-1"></i>Langkah 7–8 — Hasil Validasi</div>
  <div class="card-body">
    <div class="kpi-grid mb-3" id="ringkasanValidasi"></div>
    <div id="ringkasanError"></div>
    <div class="table-wrap" style="max-height:380px"><table class="table table-sm table-hover mb-0" id="tabelMasalah">
      <thead><tr><th class="ctr">Baris</th><th class="ctr">Status</th><th>Invoice / Customer</th><th>Pesan</th></tr></thead>
      <tbody></tbody></table></div>
  </div>
</div>

<!-- LANGKAH 9 -->
<div class="card mb-3 d-none" id="wz9">
  <div class="card-header"><i class="bi bi-check2-circle me-1"></i>Langkah 9 — Konfirmasi Import</div>
  <div class="card-body">
    <div class="alert alert-warning">
      <strong>Perhatian.</strong> Baris yang lolos validasi akan disimpan ke basis data.
      Seluruh proses berjalan dalam satu transaksi database — bila terjadi kegagalan, tidak ada data yang tersimpan sebagian.
      Import ini dapat dibatalkan sepenuhnya (rollback) dari halaman riwayat import.
    </div>
    <button class="btn btn-success btn-lg" type="button" id="btnJalankan"><i class="bi bi-database-add me-1"></i>Langkah 10 — Simpan ke Database</button>
  </div>
</div>

<!-- LANGKAH 10 -->
<div class="card mb-3 d-none" id="wz10">
  <div class="card-header"><i class="bi bi-clipboard-check me-1"></i>Langkah 10 — Ringkasan Import</div>
  <div class="card-body" id="ringkasanAkhir"></div>
</div>

<?php viewStart('scripts'); ?>
<script>
(function () {
  let state = { sheet: null, jenis: 'invoice', mapping: {}, fields: [], batchId: null };
  const el = id => document.getElementById(id);
  const show = id => el(id).classList.remove('d-none');
  const hide = id => el(id).classList.add('d-none');

  function langkah(n) {
    document.querySelectorAll('.wizard-step').forEach(s => {
      const k = parseInt(s.dataset.step, 10);
      s.classList.toggle('active', k === n);
      s.classList.toggle('done', k < n);
    });
  }

  // ---- Langkah 1
  el('formUnggah').addEventListener('submit', function (e) {
    e.preventDefault();
    const fd = new FormData(this);
    SP.loading(true);
    fetch(SP.url('/import/unggah'), { method: 'POST', body: fd, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
      .then(r => r.json()).then(res => {
        SP.loading(false);
        if (!res.sukses) { SP.toast(res.pesan, 'danger'); return; }
        el('daftarSheet').innerHTML = res.sheets.map((s, i) =>
          '<tr><td class="ctr"><input class="form-check-input" type="radio" name="sheetPilih" value="' + i + '"' + (i === 0 ? ' checked' : '') + '></td>' +
          '<td><strong>' + s.nama + '</strong>' + (s.state !== 'visible' ? ' <span class="badge bg-secondary">tersembunyi</span>' : '') + '</td>' +
          '<td>' + (s.jenis === 'revision' ? '<span class="badge bg-warning-subtle text-warning-emphasis">Revisi Invoice (RF)</span>' : '<span class="badge bg-primary-subtle text-primary-emphasis">Invoice / Piutang</span>') + '</td>' +
          '<td class="num">' + s.kolom_terpetakan + '</td>' +
          '<td class="small text-body-secondary">' + (s.kolom_diabaikan.join(', ') || '—') + '</td></tr>'
        ).join('');
        window._sheets = res.sheets;
        show('wz2'); langkah(2);
        el('wz2').scrollIntoView({ behavior: 'smooth', block: 'start' });
        el('daftarSheet').querySelectorAll('input[name="sheetPilih"]').forEach(r => r.addEventListener('change', pilihSheet));
        pilihSheet();
      }).catch(() => { SP.loading(false); SP.toast('Gagal mengunggah berkas.', 'danger'); });
  });

  // ---- Langkah 2-5
  function pilihSheet() {
    const sel = el('daftarSheet').querySelector('input[name="sheetPilih"]:checked');
    if (!sel) return;
    const s = window._sheets[parseInt(sel.value, 10)];
    state.sheet = s.nama; state.jenis = s.jenis;
    SP.loading(true);
    SP.post(SP.url('/import/pratinjau'), { sheet: s.nama, jenis: s.jenis }).then(res => {
      SP.loading(false);
      if (!res.sukses) { SP.toast(res.pesan, 'danger'); return; }
      state.mapping = res.mapping; state.fields = res.fields; state.jenis = res.jenis;

      let fieldOpts = '<option value="">— Abaikan kolom ini —</option>';
      const byGroup = {};
      res.fields.forEach(f => { (byGroup[f.group] = byGroup[f.group] || []).push(f); });
      Object.keys(byGroup).forEach(g => {
        fieldOpts += '<optgroup label="' + g + '">';
        byGroup[g].forEach(f => { fieldOpts += '<option value="' + f.key + '">' + f.label + (f.wajib ? ' *' : '') + '</option>'; });
        fieldOpts += '</optgroup>';
      });

      const contoh = res.preview[0] || {};
      el('tabelMapping').innerHTML = Object.keys(res.header).map(col => {
        const diabaikan = res.diabaikan[col] !== undefined;
        const terpilih = res.mapping[col] || '';
        return '<tr' + (diabaikan ? ' class="table-secondary"' : '') + '>' +
          '<td class="ctr fw-bold">' + col + '</td>' +
          '<td>' + res.header[col] + (diabaikan ? ' <span class="badge bg-secondary">kolom rumus</span>' : '') + '</td>' +
          '<td><select class="form-select form-select-sm" data-map="' + col + '"' + (diabaikan ? ' disabled' : '') + '>' +
            fieldOpts.replace('value="' + terpilih + '"', 'value="' + terpilih + '" selected') + '</select></td>' +
          '<td class="small text-body-secondary">' + String(contoh[col] === null || contoh[col] === undefined ? '' : contoh[col]).substring(0, 40) + '</td></tr>';
      }).join('');

      const cols = Object.keys(res.header);
      el('tabelPreview').innerHTML =
        '<thead><tr><th>#</th>' + cols.map(c => '<th>' + c + '<br><span class="fw-normal" style="font-size:10px">' + res.header[c] + '</span></th>').join('') + '</tr></thead>' +
        '<tbody>' + res.preview.map(r => '<tr><td class="text-body-secondary">' + r._baris + '</td>' +
          cols.map(c => '<td class="small">' + String(r[c] === null || r[c] === undefined ? '' : r[c]).substring(0, 30) + '</td>').join('') + '</tr>').join('') + '</tbody>';

      document.querySelectorAll('[data-map]').forEach(s2 => s2.addEventListener('change', function () {
        if (this.value) state.mapping[this.dataset.map] = this.value;
        else delete state.mapping[this.dataset.map];
      }));

      show('wz3'); show('wz6'); langkah(5);
    }).catch(() => { SP.loading(false); SP.toast('Gagal memuat pratinjau.', 'danger'); });
  }
  el('btnKembali2').addEventListener('click', () => el('wz2').scrollIntoView({ behavior: 'smooth' }));

  function opsi() {
    return { auto_buat_master: el('optMaster').checked, perbarui_duplikat: el('optDuplikat').checked, buat_pembayaran: el('optBayar').checked };
  }

  function kartu(label, nilai, warna) {
    return '<div class="kpi kpi-' + warna + '"><span class="kpi-label">' + label + '</span><span class="kpi-value">' + SP.nf(nilai) + '</span></div>';
  }

  // ---- Langkah 7
  el('btnValidasi').addEventListener('click', function () {
    SP.loading(true);
    SP.post(SP.url('/import/validasi'), { sheet: state.sheet, jenis: state.jenis, mapping: state.mapping, opsi: opsi() })
      .then(res => {
        SP.loading(false);
        if (!res.sukses) { SP.toast(res.pesan, 'danger'); return; }
        const r = res.ringkasan;
        el('ringkasanValidasi').innerHTML =
          kartu('Total Baris', r.total, 'primary') + kartu('Lolos Validasi', r.sukses, 'success') +
          kartu('Gagal', r.gagal, 'danger') + kartu('Duplikat', r.duplikat, 'warning') +
          kartu('Peringatan', r.peringatan, 'info') + kartu('Baris Kosong Dilewati', r.dilewati, 'secondary');
        const errs = Object.keys(res.ringkasan_error || {});
        el('ringkasanError').innerHTML = errs.length
          ? '<div class="alert alert-warning"><strong>Ringkasan kesalahan:</strong><ul class="mb-0 mt-1 small">' +
            errs.map(k => '<li>(' + res.ringkasan_error[k] + '×) ' + k + '</li>').join('') + '</ul></div>'
          : '<div class="alert alert-success mb-3"><i class="bi bi-check-circle me-1"></i>Semua baris lolos validasi tanpa kesalahan.</div>';
        el('tabelMasalah').querySelector('tbody').innerHTML = (res.baris_bermasalah || []).map(b =>
          '<tr><td class="ctr">' + b.baris + '</td>' +
          '<td class="ctr"><span class="badge bg-' + (b.status === 'failed' ? 'danger' : (b.status === 'duplicate' ? 'warning' : 'info')) + '">' +
            ({ failed: 'Gagal', duplicate: 'Duplikat', warning: 'Peringatan' }[b.status] || b.status) + '</span></td>' +
          '<td class="small">' + (b.invoice_no || '-') + '<br><span class="text-body-secondary">' + (b.customer || '') + '</span></td>' +
          '<td class="small">' + [].concat(b.errors || [], b.warnings || []).join(' · ') + '</td></tr>'
        ).join('') || '<tr><td colspan="4" class="text-center text-body-secondary py-3">Tidak ada baris bermasalah.</td></tr>';
        show('wz7'); show('wz9'); langkah(8);
        el('wz7').scrollIntoView({ behavior: 'smooth', block: 'start' });
      }).catch(() => { SP.loading(false); SP.toast('Validasi gagal dijalankan.', 'danger'); });
  });

  // ---- Langkah 10
  el('btnJalankan').addEventListener('click', function () {
    if (!confirm('Simpan data hasil import ke database sekarang?')) return;
    SP.loading(true);
    this.disabled = true;
    SP.post(SP.url('/import/jalankan'), { sheet: state.sheet, jenis: state.jenis, mapping: state.mapping, opsi: opsi() })
      .then(res => {
        SP.loading(false);
        this.disabled = false;
        if (!res.sukses) { SP.toast(res.pesan, 'danger'); return; }
        const r = res.ringkasan;
        let html = '<div class="alert alert-success"><i class="bi bi-check-circle-fill me-1"></i>' + res.pesan + '</div>' +
          '<div class="kpi-grid mb-3">' + kartu('Total Baris', r.total, 'primary') + kartu('Tersimpan', r.sukses, 'success') +
          kartu('Gagal', r.gagal, 'danger') + kartu('Duplikat', r.duplikat, 'warning') +
          kartu('Peringatan', r.peringatan, 'info') + kartu('Dilewati', r.dilewati, 'secondary') + '</div>';
        const mb = res.master_baru || {};
        if (Object.keys(mb).length) {
          html += '<h6>Master data dibuat otomatis</h6><ul class="small">';
          Object.keys(mb).forEach(k => { html += '<li>' + k.replace(/_/g, ' ') + ': <strong>' + mb[k].jumlah + '</strong> (' + (mb[k].contoh || []).slice(0, 5).join(', ') + '…)</li>'; });
          html += '</ul>';
        }
        if (res.revisi) {
          html += '<div class="alert alert-info small">Revisi invoice diterapkan: <strong>' + res.revisi.diterapkan + '</strong>, tertunda: ' +
                  res.revisi.tertunda + '. Pendapatan dobel-hitung yang dicegah: <strong>' + SP.rp(res.revisi.revenue_dicegah) + '</strong>.</div>';
        }
        html += '<div class="d-flex gap-2"><a class="btn btn-primary" href="' + res.redirect + '">Lihat Detail Import</a>' +
                '<a class="btn btn-light" href="' + SP.url('/import') + '">Riwayat Import</a>' +
                '<a class="btn btn-outline-secondary" href="' + SP.url('/piutang') + '">Buka Daftar Piutang</a></div>';
        el('ringkasanAkhir').innerHTML = html;
        show('wz10'); langkah(10);
        el('wz10').scrollIntoView({ behavior: 'smooth', block: 'start' });
      }).catch(() => { SP.loading(false); this.disabled = false; SP.toast('Import gagal dijalankan.', 'danger'); });
  });
})();
</script>
<?php viewStop(); ?>
