<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('transaksi/absensi/import'); ?>">Import Absensi</a></li>
          <li class="breadcrumb-item active">Preview</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content">
  <div class="container-fluid">
    <div class="row mb-3">
      <div class="col-sm-4">
        <div class="small-box bg-secondary">
          <div class="inner"><h3><?php echo $total; ?></h3><p>Total Baris</p></div>
          <div class="icon"><i class="fa fa-table"></i></div>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="small-box bg-success">
          <div class="inner"><h3><?php echo $valid_count; ?></h3><p>Siap Disimpan</p></div>
          <div class="icon"><i class="fa fa-check"></i></div>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="small-box bg-danger">
          <div class="inner"><h3><?php echo $error_count; ?></h3><p>Baris Bermasalah</p></div>
          <div class="icon"><i class="fa fa-exclamation"></i></div>
        </div>
      </div>
    </div>

    <div class="card card-danger card-outline">
      <div class="card-header d-flex align-items-center">
        <h3 class="card-title mr-auto">
          <i class="fa fa-eye mr-1"></i> Preview: <code><?php echo html_escape($filename); ?></code>
          <span class="badge badge-info ml-2"><?php echo html_escape((string) ($periode_label ?? '-')); ?></span>
          <?php if (!empty($overwrite_existing)): ?>
            <span class="badge badge-warning ml-2">Mode Timpa Aktif</span>
          <?php else: ?>
            <span class="badge badge-secondary ml-2">Mode Tambah Saja</span>
          <?php endif; ?>
        </h3>
        <?php if ($valid_count > 0): ?>
        <button type="button" id="btn-simpan-absensi" class="btn btn-success btn-sm" data-save-url="<?php echo site_url('transaksi/absensi/simpan_import'); ?>" data-progress-url="<?php echo site_url('transaksi/absensi/import_progress'); ?>">
          <i class="fa fa-save mr-1"></i> Simpan <?php echo $valid_count; ?> Data Valid
        </button>
        <?php endif; ?>
        <a href="<?php echo site_url('transaksi/absensi/import'); ?>" class="btn btn-secondary btn-sm ml-2">
          <i class="fa fa-arrow-left mr-1"></i> Upload Ulang
        </a>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-bordered table-sm mb-0" style="font-size:12px;">
            <thead class="thead-dark">
              <tr>
                <th>Baris</th>
                <th>NIP</th>
                <th>Nama</th>
                <th>Tanggal</th>
                <th>Jam Masuk</th>
                <th>Jam Keluar</th>
                <th>Status</th>
                <th>Keterangan</th>
                <th>Aksi</th>
                <th>Validasi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($preview as $p): ?>
              <tr class="<?php echo !empty($p['valid']) ? '' : 'table-danger'; ?>">
                <td><?php echo (int) ($p['baris'] ?? 0); ?></td>
                <td><?php echo html_escape((string) ($p['nip'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['nama_lengkap'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['tanggal'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['jam_masuk'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['jam_keluar'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['status'] ?? '')); ?></td>
                <td><?php echo html_escape((string) ($p['keterangan'] ?? '')); ?></td>
                <td>
                  <?php if (($p['aksi'] ?? 'INSERT') === 'UPDATE'): ?>
                    <span class="badge badge-warning">UPDATE</span>
                  <?php else: ?>
                    <span class="badge badge-info">INSERT</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if (!empty($p['valid'])): ?>
                    <span class="badge badge-success">Valid</span>
                  <?php else: ?>
                    <span class="badge badge-danger"><?php echo count((array) ($p['errors'] ?? [])); ?> Error</span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php if (empty($p['valid'])): ?>
              <tr class="table-danger">
                <td colspan="10" class="py-1 pl-4" style="font-size:11px; color:#721c24;">
                  <i class="fa fa-exclamation-circle mr-1"></i>
                  <?php echo html_escape(implode(' ; ', (array) ($p['errors'] ?? []))); ?>
                </td>
              </tr>
              <?php endif; ?>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</section>

<div id="import-progress-wrap" class="card card-outline card-success" style="display:none; position: sticky; bottom: 10px; z-index: 20;">
  <div class="card-body">
    <div class="d-flex align-items-center justify-content-between mb-2">
      <div><i class="fa fa-spinner fa-spin mr-2"></i><strong>Memproses simpan import absensi...</strong></div>
      <span class="badge badge-success" id="import-progress-percent">0%</span>
    </div>
    <div class="progress progress-sm">
      <div id="import-progress-bar" class="progress-bar bg-success" role="progressbar" style="width:0%"></div>
    </div>
    <small id="import-progress-text" class="text-muted d-block mt-2">Menunggu proses...</small>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>';
  var csrfCookieName = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
  var csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
  var btn = document.getElementById('btn-simpan-absensi');
  var progressWrap = document.getElementById('import-progress-wrap');
  var progressPercent = document.getElementById('import-progress-percent');
  var progressBar = document.getElementById('import-progress-bar');
  var progressText = document.getElementById('import-progress-text');
  var pollTimer = null;

  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 '';
  }

  function setProgressState(percent, text) {
    var safePercent = Math.max(0, Math.min(100, parseInt(percent || 0, 10)));
    if (progressPercent) progressPercent.textContent = safePercent + '%';
    if (progressBar) progressBar.style.width = safePercent + '%';
    if (progressText && text) progressText.textContent = text;
  }

  function stopPolling() {
    if (pollTimer) {
      clearInterval(pollTimer);
      pollTimer = null;
    }
  }

  function startPolling(progressUrl, token) {
    pollTimer = setInterval(function() {
      fetch(progressUrl + '?token=' + encodeURIComponent(token), {
        method: 'GET',
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
      })
      .then(function(res) { return res.json(); })
      .then(function(resp) {
        var data = (resp && resp.data) ? resp.data : {};
        setProgressState(data.percent, data.message || 'Sedang memproses...');
        if (data.status === 'completed' || data.status === 'failed') {
          stopPolling();
        }
      })
      .catch(function() {});
    }, 500);
  }

  if (!btn) {
    return;
  }

  btn.addEventListener('click', function() {
    var saveUrl = btn.getAttribute('data-save-url') || '';
    var progressUrl = btn.getAttribute('data-progress-url') || '';
    var token = 'impa_save_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);

    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> Menyimpan...';
    btn.disabled = true;
    if (progressWrap) progressWrap.style.display = 'block';

    setProgressState(0, 'Memulai proses simpan...');
    startPolling(progressUrl, token);

    fetch(saveUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: 'progress_token=' + encodeURIComponent(token) + '&' + encodeURIComponent(csrfName) + '=' + encodeURIComponent(readCookie(csrfCookieName) || csrfHash)
    })
    .then(function(res) { return res.json(); })
    .then(function(resp) {
      stopPolling();
      if (resp && resp.success) {
        setProgressState(100, resp.message || 'Import selesai');
        window.location.href = (resp.data && resp.data.redirect_url) ? resp.data.redirect_url : '<?php echo site_url('transaksi/absensi/import'); ?>';
        return;
      }

      setProgressState(0, (resp && resp.message) ? resp.message : 'Gagal menyimpan data preview absensi.');
      btn.innerHTML = '<i class="fa fa-save mr-1"></i> Simpan <?php echo $valid_count; ?> Data Valid';
      btn.disabled = false;
    })
    .catch(function() {
      stopPolling();
      setProgressState(0, 'Terjadi kesalahan saat menyimpan data preview absensi.');
      btn.innerHTML = '<i class="fa fa-save mr-1"></i> Simpan <?php echo $valid_count; ?> Data Valid';
      btn.disabled = false;
    });
  });
});
</script>
