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

<section class="content">
  <div class="container-fluid">
    <div class="row">
      <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">
            <?php if ($this->session->flashdata('success')): ?>
              <div class="alert alert-success alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fa fa-check-circle mr-2"></i>
                <strong>Berhasil!</strong> <?php echo $this->session->flashdata('success'); ?>
              </div>
            <?php endif; ?>

            <?php if ($this->session->flashdata('warning')): ?>
              <div class="alert alert-warning alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fa fa-exclamation-triangle mr-2"></i>
                <strong>Perhatian!</strong> <?php echo $this->session->flashdata('warning'); ?>
              </div>
            <?php endif; ?>

            <?php if ($this->session->flashdata('error')): ?>
              <div class="alert alert-danger alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fa fa-exclamation-circle mr-2"></i>
                <strong>Error!</strong> <?php echo $this->session->flashdata('error'); ?>
              </div>
            <?php endif; ?>

            <div class="alert alert-light border">
              <div class="row">
                <div class="col-md-3 mb-2 mb-md-0">
                  <label class="mb-1">Bulan Periode</label>
                  <select name="bulan" form="form-import" class="form-control form-control-sm" required>
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo ((int) ($f_bulan ?? date('n')) === $m) ? 'selected' : ''; ?>><?php echo bulan_indonesia($m); ?></option>
                    <?php endfor; ?>
                  </select>
                </div>
                <div class="col-md-3 mb-2 mb-md-0">
                  <label class="mb-1">Tahun Periode</label>
                  <input type="number" name="tahun" form="form-import" class="form-control form-control-sm" min="2020" max="2100" value="<?php echo (int) ($f_tahun ?? date('Y')); ?>" required>
                </div>
                <div class="col-md-6">
                  <label class="mb-1">Rentang Periode Import</label>
                  <div class="form-control form-control-sm bg-white d-flex align-items-center">
                    <i class="fa fa-calendar mr-2 text-muted"></i>
                    <?php echo html_escape((string) ($f_periode_label ?? '-')); ?>
                  </div>
                  <small class="text-muted">Baris dengan tanggal di luar rentang ini akan ditandai error saat preview.</small>
                </div>
              </div>
            </div>

            <a href="<?php echo site_url('transaksi/absensi/template'); ?>" class="btn btn-info btn-block mb-3">
              <i class="fa fa-download mr-1"></i> Download Template Excel
            </a>

            <?php echo form_open_multipart('transaksi/absensi/import', ['id' => 'form-import']); ?>
            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
            <div class="form-group">
              <label>Pilih File Excel <span class="text-danger">*</span></label>
              <div class="custom-file">
                <input type="file" name="file_import" id="file_import" class="custom-file-input" accept=".xlsx,.xls" required>
                <label class="custom-file-label" for="file_import">Pilih file...</label>
              </div>
              <small class="form-text text-muted">File harus berformat .xlsx atau .xls (maks 5MB)</small>
            </div>

            <div class="form-group">
              <label>
                <input type="checkbox" name="overwrite" id="overwrite" value="1">
                <strong>Timpa data yang sudah ada</strong>
              </label>
              <small class="d-block text-muted pl-4">Jika dicentang, data absensi yang sudah ada di database akan diperbarui dengan data dari file Excel.</small>
            </div>

            <div class="d-flex justify-content-between">
              <a href="<?php echo site_url('transaksi/absensi'); ?>" class="btn btn-secondary"><i class="fa fa-arrow-left mr-1"></i> Kembali</a>
              <button type="submit" class="btn btn-danger" id="btn-import-submit"><i class="fa fa-eye mr-1"></i> Preview Data</button>
            </div>
            <?php echo form_close(); ?>
          </div>
        </div>
      </div>

      <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 import absensi 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> Kolom wajib: <code>nip</code>, <code>nama_lengkap</code>, <code>tanggal</code>, <code>status</code></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> Format jam: <code>HH:MM</code> (24 jam)</li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Status valid: <code>MASUK</code>, <code>ALPHA</code>, <code>SAKIT</code>, <code>CUTI</code>, <code>LIBUR</code>, <code>LEMBUR</code></li>
              <li class="list-group-item"><i class="fa fa-check text-success mr-1"></i> Data akan ditampilkan di halaman preview sebelum disimpan</li>
              <li class="list-group-item text-muted"><i class="fa fa-info-circle mr-1"></i> Baris yang error tidak akan disimpan</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- Import History Card -->
    <?php if (!empty($history)): ?>
    <div class="card card-danger card-outline mt-3">
      <div class="card-header">
        <h3 class="card-title"><i class="fa fa-history mr-1"></i> Riwayat Import (10 Terakhir)</h3>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table id="tbl-history" class="table table-bordered table-hover table-striped table-sm">
            <thead>
              <tr>
                <th style="width:40px;">#</th>
                <th>Tanggal</th>
                <th>Nama File</th>
                <th style="text-align:center;">Total</th>
                <th style="text-align:center;">✓ Berhasil</th>
                <th style="text-align:center;">✗ Gagal</th>
                <th>Status</th>
                <th style="width:80px;">Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($history as $i => $h): 
                $badge = 'badge-success';
                $btn_delete_disabled = '';
                if ($h->status === 'PARTIAL') {
                  $badge = 'badge-warning';
                } elseif ($h->status === 'FAILED') {
                  $badge = 'badge-danger';
                } elseif ($h->status === 'DELETED') {
                  $badge = 'badge-secondary';
                  $btn_delete_disabled = 'disabled';
                }
              ?>
              <tr>
                <td><?php echo $i + 1; ?></td>
                <td><?php echo format_tanggal_waktu($h->created_at); ?></td>
                <td>
                  <small><?php echo html_escape($h->nama_file); ?></small>
                  <?php if ($h->gagal > 0 && $h->status !== 'DELETED'): ?>
                    <a href="javascript:" class="btn-detail-error" data-log="<?php echo htmlspecialchars($h->detail_log ?? ''); ?>" style="display:inline;">
                      <i class="fa fa-info-circle text-danger" title="Lihat detail error"></i>
                    </a>
                  <?php endif; ?>
                </td>
                <td style="text-align:center;"><strong><?php echo $h->total_baris; ?></strong></td>
                <td style="text-align:center;"><span class="badge badge-success"><?php echo $h->berhasil; ?></span></td>
                <td style="text-align:center;"><span class="badge badge-danger"><?php echo $h->gagal; ?></span></td>
                <td><span class="badge <?php echo $badge; ?>"><?php echo $h->status; ?></span></td>
                <td style="text-align:center;">
                  <?php if ($h->status !== 'DELETED'): ?>
                    <a href="javascript:" class="btn-delete-batch" data-id="<?php echo $h->id_import; ?>" data-name="<?php echo htmlspecialchars($h->nama_file); ?>" title="Hapus batch ini">
                      <i class="fa fa-trash text-danger"></i>
                    </a>
                  <?php else: ?>
                    <span class="text-muted"><i class="fa fa-trash"></i></span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <?php endif; ?>
  </div>
</section>

<!-- Modal - Detail Error Log -->
<div class="modal fade" id="modal-error-log" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-exclamation-triangle mr-2 text-danger"></i> Detail Error Import</h5>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <pre id="error-log-content" style="max-height: 400px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px;"></pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const fileInput = document.getElementById('file_import');
  const formImport = document.getElementById('form-import');
  const btnImport = document.getElementById('btn-import-submit');
  if (fileInput) {
    fileInput.addEventListener('change', function() {
      const fileName = this.value.split('\\').pop();
      const label = this.nextElementSibling;
      if (label && label.classList.contains('custom-file-label')) {
        label.textContent = fileName;
      }
    });
  }

  if (formImport && btnImport) {
    formImport.addEventListener('submit', function() {
      btnImport.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> Memproses...';
      btnImport.disabled = true;
    });
  }
});

window.addEventListener('load', function() {
  if (typeof $ !== 'undefined') {
    $(document).ready(function() {
      // DataTable
      const tbl = document.getElementById('tbl-history');
      if (tbl && typeof $.fn.dataTable !== 'undefined') {
        $(tbl).DataTable({
          'pageLength': 10,
          'order': [[1, 'desc']],
          'columnDefs': [
            { 'orderable': false, 'targets': 7 }
          ],
          'language': {
            'url': '//cdn.datatables.net/plug-ins/1.13.8/i18n/id.json'
          }
        });
      }

      // Show error log detail
      $(document).on('click', '.btn-detail-error', function(e) {
        e.preventDefault();
        let logText = $(this).data('log');
        $('#error-log-content').text(logText);
        $('#modal-error-log').modal('show');
      });

      // Delete batch confirmation
      $(document).on('click', '.btn-delete-batch', function(e) {
        e.preventDefault();
        let id = $(this).data('id');
        let name = $(this).data('name');
        
        Swal.fire({
          title: 'Hapus Batch Import?',
          html: '<strong>File:</strong> ' + name + '<br><strong>Batch ID:</strong> #' + id + '<br><br>' +
                '<span class="text-danger"><i class="fa fa-warning mr-2"></i>Semua data dari batch ini akan dihapus dari sistem. Tindakan ini tidak dapat dibatalkan.</span>',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#dc3545',
          cancelButtonColor: '#6c757d',
          confirmButtonText: '<i class="fa fa-trash mr-2"></i> Ya, Hapus',
          cancelButtonText: 'Batal'
        }).then((result) => {
          if (result.isConfirmed) {
            window.location.href = '<?php echo site_url('transaksi/absensi/delete_batch/'); ?>' + id;
          }
        });
      });
    });
  }
});
</script>
