<?php $this->start('body'); ?>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
  <h5 class="mb-0 fw-semibold"><i class="fas fa-file-import me-2 text-muted"></i>Data Import</h5>
</div>

<?= flashHtml(); ?>

<!-- Entity tabs — pure PHP navigation to avoid re-parsing columns in JS -->
<ul class="nav nav-tabs mb-3">
  <?php foreach (['trucks'=>'Trucks','drivers'=>'Drivers','customers'=>'Customers'] as $k=>$v): ?>
    <li class="nav-item">
      <a href="<?= PROOT; ?>Import?entity=<?= $k; ?>"
         class="nav-link <?= $this->data['entity']===$k ? 'active' : ''; ?>">
        <i class="fas fa-<?= $k==='trucks'?'truck':($k==='drivers'?'id-card':'building'); ?> me-1"></i><?= $v; ?>
      </a>
    </li>
  <?php endforeach; ?>
</ul>

<!-- Vue 3 mount point -->
<div id="dataImport" v-cloak>

  <!-- Step 1: template + upload -->
  <div class="card border-0 shadow-sm mb-3">
    <div class="card-body">
      <div class="row g-3 align-items-end">
        <div class="col-md-8">
          <label class="form-label fw-semibold mb-1">1 · Get the template</label>
          <p class="small text-muted mb-2">Download an Excel template with the correct column headers for <strong>{{ entityLabel }}</strong>. The template also includes one sample row you should delete before importing.</p>
          <button class="btn btn-sm btn-outline-primary" @click="downloadTemplate">
            <i class="fas fa-download me-1"></i>Download {{ entity }} template.xlsx
          </button>
        </div>
        <div class="col-md-4">
          <label class="form-label fw-semibold mb-1">Required columns</label>
          <ul class="small mb-0 ps-3">
            <li v-for="c in requiredCols" :key="c.field">{{ c.label.replace('*','') }}</li>
          </ul>
        </div>
      </div>
      <hr>
      <div class="row g-3 align-items-end">
        <div class="col-md-8">
          <label class="form-label fw-semibold mb-1">2 · Upload the filled file</label>
          <p class="small text-muted mb-2">The file is parsed in your browser (nothing uploads to the server yet) so you can preview and fix issues before importing.</p>
          <input type="file" id="importFile" class="form-control" accept=".xlsx,.xls,.csv" @change="onFile">
        </div>
        <div class="col-md-4 text-md-end">
          <button v-if="fileName" class="btn btn-sm btn-outline-secondary" @click="clearFile">
            <i class="fas fa-times me-1"></i>Clear
          </button>
          <div v-if="fileName" class="small text-muted mt-1"><i class="fas fa-file-excel me-1"></i>{{ fileName }} · {{ rows.length }} rows</div>
        </div>
      </div>
    </div>
  </div>

  <!-- Error banner -->
  <div v-if="error" class="alert alert-danger small">{{ error }}</div>

  <!-- Step 3: preview -->
  <div v-if="rows.length > 0 && !result" class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between py-2">
      <span class="fw-semibold text-uppercase small"><i class="fas fa-table me-1"></i>Preview ({{ previewRows.length }} of {{ rows.length }} shown)</span>
      <button class="btn btn-sm btn-primary" @click="submitImport" :disabled="importing">
        <i class="fas fa-check me-1"></i>
        <span v-if="!importing">Import {{ rows.length }} row(s)</span>
        <span v-else>Importing…</span>
      </button>
    </div>
    <div class="table-responsive">
      <table class="table table-sm mb-0 align-middle">
        <thead class="table-light">
          <tr>
            <th style="width:40px;">#</th>
            <th>Issues</th>
            <th v-for="c in columns.slice(0, 6)" :key="c.field">{{ c.label.replace('*','') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(r, idx) in previewRows" :key="idx" :class="rowIssues(r).length ? 'table-warning' : ''">
            <td class="text-muted small">{{ idx + 2 }}</td>
            <td class="small">
              <span v-if="rowIssues(r).length === 0" class="text-success"><i class="fas fa-check"></i></span>
              <span v-else class="text-warning" :title="rowIssues(r).join(', ')">
                <i class="fas fa-exclamation-triangle"></i> {{ rowIssues(r).length }}
              </span>
            </td>
            <td v-for="c in columns.slice(0, 6)" :key="c.field" class="small">{{ r[c.field] || '' }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-if="hasMoreRows" class="card-footer bg-white small text-muted py-2 text-center">
      … and {{ rows.length - 20 }} more rows (not previewed but will be imported)
    </div>
  </div>

  <!-- Step 4: results -->
  <div v-if="result" class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between py-2">
      <span class="fw-semibold text-uppercase small"><i class="fas fa-clipboard-check me-1"></i>Import Result</span>
      <div>
        <span class="badge bg-success me-1"><i class="fas fa-check me-1"></i>{{ result.imported }} imported</span>
        <span class="badge bg-danger" v-if="result.failed > 0"><i class="fas fa-times me-1"></i>{{ result.failed }} failed</span>
      </div>
    </div>
    <div class="card-body">
      <div v-if="result.failed === 0" class="alert alert-success mb-3 small">
        <i class="fas fa-check-circle me-1"></i>All {{ result.imported }} row(s) imported successfully.
      </div>
      <div v-if="result.failed > 0" class="alert alert-warning mb-3 small">
        <i class="fas fa-exclamation-triangle me-1"></i>
        {{ result.imported }} row(s) imported, {{ result.failed }} failed. Fix the failed rows in Excel and re-upload only those rows.
      </div>
      <div v-if="result.failed > 0" class="table-responsive">
        <table class="table table-sm">
          <thead class="table-light">
            <tr><th style="width:60px;">Row</th><th>Status</th><th>Message</th></tr>
          </thead>
          <tbody>
            <tr v-for="(res, i) in result.results.filter(x => !x.ok)" :key="i" class="table-danger">
              <td>{{ res.row }}</td>
              <td><span class="badge bg-danger">Failed</span></td>
              <td class="small">{{ res.msg }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="d-flex gap-2 mt-2">
        <button class="btn btn-sm btn-outline-secondary" @click="clearFile"><i class="fas fa-redo me-1"></i>Import another file</button>
        <a :href="proot + entity.charAt(0).toUpperCase() + entity.slice(1)" class="btn btn-sm btn-primary">
          <i class="fas fa-arrow-right me-1"></i>View {{ entityLabel }}
        </a>
      </div>
    </div>
  </div>

  <!-- Empty state -->
  <div v-if="rows.length === 0 && !result && !error" class="text-center text-muted small py-4 fst-italic">
    Choose or drop a file above to preview it.
  </div>

</div>

<script>
window.__pacificImport = {
    proot:   '<?= PROOT; ?>',
    csrf:    '<?= csrf_token(); ?>',
    entity:  <?= json_encode($this->data['entity']); ?>,
    columns: <?= json_encode($this->data['columns'], JSON_UNESCAPED_UNICODE); ?>
};
</script>
<style>
[v-cloak] { display: none; }
</style>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script src="<?= PROOT; ?>js/Olibs/xlsx.full.min.js"></script>
<script src="<?= PROOT; ?>js/Olibs/vue.global.prod.js"></script>
<script src="<?= PROOT; ?>js/Projects/data-import.js?v=<?= @filemtime(ROOT . '/js/Projects/data-import.js') ?: '1'; ?>"></script>
<?php $this->end(); ?>
