<?php
// enrepcore/includes/asset/asset_import.php
// Loaded via modal with ?clientnumber=##&tenant=TENANT_URL

$d = explode('|', $_REQUEST['data']);
$clientnumber = (int)$d[0];
$tenant = $_REQUEST['tenant'];
$uid = bin2hex(random_bytes(4));
?>
<div id="assetImportModal-<?=$uid?>"
     class="container-fluid py-2 asset-import-root"
     data-client="<?=$clientnumber?>"
     data-tenant="<?=htmlspecialchars($tenant, ENT_QUOTES)?>">
  <div class="row">
    <div class="col-12">
      <h5 class="mb-3"><i class="fad fa-file-csv me-2"></i>Import Assets</h5>

      <div class="d-flex gap-2 flex-wrap">
        <button id="btnDownloadTemplate" class="btn btn-info"
                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                title="Download CSV template with headers and one example row">
          <i class="fad fa-download me-2"></i>Download template
        </button>

        <label for="csvFile" class="btn btn-info mb-0"
               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
               title="Upload a CSV file of assets">
          <i class="fad fa-upload me-2"></i>Upload assets
          <input type="file" id="csvFile" accept=".csv" hidden>
        </label>
      </div>

      <hr class="my-3">

      <div class="note note-primary mb-3">
        <strong>CSV headers (exact):</strong>
        <code>Description, Safe working load, Plant Number, Serial Number, Model, Date of manufacture, Manufacturer, Due Date</code>
      </div>

      <div id="uploadFeedback"></div>

      <div id="previewSection" class="d-none">
        <div class="alert alert-secondary py-2">
          <i class="fad fa-list-check me-2"></i>
          Map each row to a <strong>Location</strong> and <strong>Code</strong>, then press Import.
        </div>

        <div class="table-responsive">
          <table class="table table-sm align-middle" id="previewTable">
            <thead>
              <tr class="table-light">
                <th>#</th><th>Description</th><th>SWL</th><th>Plant No.</th><th>Serial No.</th>
                <th>Model</th><th>DoM</th><th>Manufacturer</th><th>Due Date</th>
                <th>Location</th><th>Code</th><th>Status</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>

        <div class="d-flex justify-content-end gap-2">
          <button id="btnImport" class="btn btn-info"
                  data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                  title="Insert all valid rows into itemdetails">
            <i class="fad fa-check-circle me-2"></i>Import
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(() => {
  // bind to this instance only
  const root = document.getElementById('assetImportModal-<?=$uid?>');
  if (!root || root.dataset.inited === '1') return;
  root.dataset.inited = '1';

  // scoped constants
  const CLIENTNUMBER   = Number(root.dataset.client);
  const TENANT         = root.dataset.tenant;
  const API            = ROOT_URL + '/includes/asset/asset_functions.php';

  // scoped elements
  const csvInput       = root.querySelector('#csvFile');
  const btnDownload    = root.querySelector('#btnDownloadTemplate');
  const previewSection = root.querySelector('#previewSection');
  const previewTbody   = root.querySelector('#previewTable tbody');
  const uploadFeedback = root.querySelector('#uploadFeedback');
  const btnImport      = root.querySelector('#btnImport');

  // helpers
  const showMsg  = (type, msg) => uploadFeedback.innerHTML = '<div class="alert alert-'+type+' py-2 mb-3">'+msg+'</div>';
  const clearMsg = () => uploadFeedback.innerHTML = '';
  const escapeHtml = s => (s||'').toString().replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));

  // download template (keeps page in place)
  btnDownload?.addEventListener('click', () => {
    const url = API + '?FUNCTION=assetDownloadTemplate&tenant=' + encodeURIComponent(TENANT);
    fetch(url, { credentials: 'same-origin' })
      .then(r => { if (!r.ok) throw new Error(); return r.blob(); })
      .then(blob => {
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'asset_import_template.csv';
        document.body.appendChild(a); a.click(); a.remove();
        URL.revokeObjectURL(a.href);
      })
      .catch(() => showResponse('danger', 'Could not download template.'));
  });

  // build table row (scoped)
  const buildRow = (idx, row, locations, codes) => {
    const tr = document.createElement('tr');
    tr.dataset.index = String(idx);
    tr.innerHTML = `
      <td>${idx+1}</td>
      <td>${escapeHtml(row.desc)}</td>
      <td>${escapeHtml(row.swl)}</td>
      <td>${escapeHtml(row.plantnumber)}</td>
      <td>${escapeHtml(row.serialnumber)}</td>
      <td>${escapeHtml(row.model)}</td>
      <td>${escapeHtml(row.dateofmanf)}</td>
      <td>${escapeHtml(row.manf)}</td>
      <td>${escapeHtml(row.duedate_display)}</td>
      <td></td><td></td>
      <td class="status"><span class="badge bg-secondary">Pending</span></td>
    `;
    const tdLoc  = tr.children[9];
    const tdCode = tr.children[10];

    const selLoc = document.createElement('select');
    selLoc.className = 'form-select form-select-sm w-100';
    selLoc.innerHTML = '<option value="">Select location</option>' +
      locations.map(l => `<option value="${l.locnumber}">${escapeHtml(l.locname)} (${escapeHtml(l.postcode||'')})</option>`).join('');
    tdLoc.appendChild(selLoc);

    const selCode = document.createElement('select');
    selCode.className = 'form-select form-select-sm w-100';
    selCode.innerHTML = '<option value="">Select code</option>' +
      codes.map(c => `<option value="${c.code}">${escapeHtml(c.code)} – ${escapeHtml(c.description||'')}</option>`).join('');
    tdCode.appendChild(selCode);

    if (row._duplicate) {
      tr.classList.add('opacity-50');
      selLoc.disabled = true;
      selCode.disabled = true;
    }
    tr._data = row; tr._selLoc = selLoc; tr._selCode = selCode;
    return tr;
  };

  // upload parse
  csvInput?.addEventListener('change', () => {
    clearMsg();
    const f = csvInput.files && csvInput.files[0]; if (!f) return;

    const fd = new FormData();
    fd.append('FUNCTION','assetUploadCSV');
    fd.append('tenant', TENANT);
    fd.append('clientnumber', CLIENTNUMBER);
    fd.append('file', f);

    fetch(API, { method:'POST', body: fd })
      .then(r => r.json())
      .then(j => {
        if (j.status !== 'ok') { showMsg('danger', j.message||'Upload failed.'); previewSection.classList.add('d-none'); return; }
        previewTbody.innerHTML = '';
        j.rows.forEach((row, idx) => {
          const tr = buildRow(idx, row, j.locations, j.codes);
          const statusTd = tr.querySelector('.status');
          if (row._error) {
            statusTd.innerHTML = `<span class="badge bg-danger" data-mdb-tooltip-init title="${escapeHtml(row._error)}">Invalid</span>`;
          } else if (row._duplicate) {
            statusTd.innerHTML = '<span class="badge bg-warning" data-mdb-tooltip-init title="Duplicate plant+serial exists">Duplicate</span>';
          } else {
            statusTd.innerHTML = '<span class="badge bg-success">OK</span>';
          }
          previewTbody.appendChild(tr);
        });
        if (window.mdb && mdb.Tooltip) root.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => new mdb.Tooltip(el));
        previewSection.classList.remove('d-none');
        showMsg('success','File parsed. Assign Location and Code, then import.');
      })
      .catch(() => showMsg('danger','Error uploading or parsing CSV.'));
  });

  // commit import
  btnImport?.addEventListener('click', () => {
    clearMsg();
    const payload = [];
    let hasErr = false;

    Array.from(previewTbody.querySelectorAll('tr')).forEach(tr => {
      const row = tr._data || {};
      const statusTd = tr.querySelector('.status');
      if (row._duplicate) return; // skip duplicates

      const loc  = tr._selLoc?.value || '';
      const code = tr._selCode?.value || '';

      if (row._error || !loc || !code) {
        hasErr = true;
        if (!row._error) statusTd.innerHTML = '<span class="badge bg-danger">Fix required</span>';
        return;
      }

      payload.push({
        desc: row.desc, swl: row.swl, plantnumber: row.plantnumber, serialnumber: row.serialnumber,
        model: row.model, dateofmanf: row.dateofmanf, manf: row.manf, duedate: row.duedate,
        locnumber: parseInt(loc, 10), code
      });
      statusTd.innerHTML = '<span class="badge bg-info">Queued</span>';
    });

    if (!payload.length) { showMsg('warning','Nothing to import. Duplicates are skipped. Fix remaining rows or upload another file.'); return; }
    if (hasErr) { showMsg('warning','Some rows need fixing. Only valid, non-duplicate rows will be imported.'); }

    const fd = new FormData();
    fd.append('FUNCTION','assetCommitImport');
    fd.append('tenant', TENANT);
    fd.append('clientnumber', CLIENTNUMBER);
    fd.append('rows', JSON.stringify(payload));

    fetch(API, { method:'POST', body: fd })
      .then(r => r.json())
      .then(j => {
        if (j.status === 'ok') { showResponse('success', `Imported ${j.inserted} item(s).`); killModal('popupBox'); window.location.reload()}
        else { showResponse('danger', j.message || 'Import failed.'); }
      })
      .catch(() => showResponse('danger','Error committing import.'));
  });
})();
</script>
