<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0"><?php echo $page_subtitle; ?></p>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></li>
          <li class="breadcrumb-item"><a href="<?php echo site_url('master/pegawai'); ?>">Data Pegawai</a></li>
          <li class="breadcrumb-item active">Import</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="row">
      <!-- Upload Card -->
      <div class="col-md-7">
        <div class="card card-danger card-outline">
          <div class="card-header"><h3 class="card-title"><i class="fa fa-upload mr-1"></i> Upload File Excel</h3></div>
          <div class="card-body">
            <p class="text-muted mb-3">
              <i class="fa fa-info-circle mr-1 text-danger"></i>
              Upload file Excel sesuai template. Data akan ditampilkan preview sebelum disimpan.
            </p>
            <?php echo form_open_multipart('master/import_pegawai/upload', ['id'=>'form-upload']); ?>
              <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
              <div class="custom-file mb-3">
                <input type="file" class="custom-file-input" id="file_excel" name="file_excel" accept=".xlsx,.xls" required>
                <label class="custom-file-label" for="file_excel">Pilih file .xlsx atau .xls</label>
              </div>
              <div class="custom-control custom-checkbox mb-3">
                <input type="checkbox" class="custom-control-input" id="overwrite_existing" name="overwrite_existing" value="1">
                <label class="custom-control-label" for="overwrite_existing">Timpa data yang sudah ada (berdasarkan NIP)</label>
              </div>
              <button type="submit" class="btn btn-danger btn-block" id="btn-upload">
                <i class="fa fa-eye mr-1"></i> Preview Data
              </button>
            <?php echo form_close(); ?>
          </div>
          <div class="card-footer">
            <a href="<?php echo site_url('master/import_pegawai/template'); ?>" class="btn btn-outline-secondary btn-sm">
              <i class="fa fa-download mr-1"></i> Download Template Excel
            </a>
          </div>
        </div>
      </div>

      <!-- Info panduan -->
      <div class="col-md-5">
        <div class="card card-outline card-info">
          <div class="card-header"><h3 class="card-title"><i class="fa fa-book mr-1"></i> Panduan Import</h3></div>
          <div class="card-body p-0">
            <ul class="list-group list-group-flush" style="font-size:13px;">
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Download template terlebih dahulu</li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Jangan ubah nama header kolom</li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Format tanggal: <code>YYYY-MM-DD</code></li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Jenis kelamin: <code>L</code> atau <code>P</code></li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Kode divisi &amp; jabatan harus sesuai sistem</li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> NIP tidak boleh duplikat</li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Centang <strong>Timpa data yang sudah ada</strong> untuk update pegawai dengan NIP yang sama</li>
              <li class="list-group-item text-muted"><i class="fa fa-info-circle mr-1"></i> Baris dengan error akan dilewati saat simpan</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- Riwayat Import -->
    <?php if (!empty($riwayat)): ?>
    <div class="card card-danger card-outline">
      <div class="card-header"><h3 class="card-title"><i class="fa fa-history mr-1"></i> Riwayat Import Terakhir</h3></div>
      <div class="card-body p-0">
        <table class="table table-sm table-bordered mb-0">
          <thead>
            <tr><th>Waktu</th><th>File</th><th>Total</th><th>Berhasil</th><th>Gagal</th><th>Status</th></tr>
          </thead>
          <tbody>
            <?php foreach ($riwayat as $r): ?>
            <tr>
              <td style="font-size:12px;"><?php echo $r->created_at; ?></td>
              <td><?php echo html_escape($r->nama_file); ?></td>
              <td><?php echo $r->total_baris; ?></td>
              <td><span class="text-success font-weight-bold"><?php echo $r->berhasil; ?></span></td>
              <td><span class="text-danger font-weight-bold"><?php echo $r->gagal; ?></span></td>
              <td>
                <?php
                  $badge = ['SUCCESS'=>'badge-aktif','PARTIAL'=>'badge-warning','FAILED'=>'badge-danger'];
                  echo '<span class="badge '.($badge[$r->status]??'badge-secondary').'">'.$r->status.'</span>';
                ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <?php endif; ?>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var csrfTokenName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var fileInput = document.getElementById('file_excel');
  var formUpload = document.getElementById('form-upload');
  var btnUpload = document.getElementById('btn-upload');

  function readCookie(name) {
    var pairs = (document.cookie || '').split(';');
    for (var i = 0; i < pairs.length; i++) {
      var part = pairs[i].trim();
      if (part.indexOf(name + '=') === 0) {
        return decodeURIComponent(part.substring(name.length + 1));
      }
    }
    return '';
  }

  if (fileInput) {
    fileInput.addEventListener('change', function() {
      var fileName = (this.value || '').split('\\\\').pop();
      var label = this.nextElementSibling;
      if (label && label.classList.contains('custom-file-label')) {
        label.textContent = fileName || 'Pilih file .xlsx atau .xls';
      }
    });
  }

  if (formUpload && btnUpload) {
    formUpload.addEventListener('submit', function() {
      var csrfInput = formUpload.querySelector('input[name="' + csrfTokenName + '"]');
      var csrfFromCookie = readCookie(csrfCookieName);
      if (csrfInput && csrfFromCookie) {
        csrfInput.value = csrfFromCookie;
      }

      btnUpload.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> Memproses...';
      btnUpload.disabled = true;
    });
  }
});
</script>
