<section class="content-header">
  <div class="container-fluid">
    <div class="row mb-2 align-items-center">
      <div class="col-sm-8">
        <h1><?php echo $page_title; ?></h1>
        <p class="text-muted mb-0">
          <?php if ($periode_aktif): ?>
            Periode aktif: <strong><?php echo bulan_indonesia($periode_aktif->bulan) . ' ' . $periode_aktif->tahun; ?></strong>
            &nbsp;<span class="badge badge-<?php echo $periode_aktif->status === 'APPROVED' ? 'success' : ($periode_aktif->status === 'OPEN' ? 'info' : 'warning'); ?>">
              <?php echo $periode_aktif->status; ?>
            </span>
          <?php else: ?>
            Belum ada periode aktif.
          <?php endif; ?>
        </p>
      </div>
      <div class="col-sm-4 text-right">
        <small class="text-muted"><i class="fa fa-clock-o mr-1"></i> Data diperbarui: <span id="last-refresh"><?php echo date('H:i:s'); ?></span></small>
        <button class="btn btn-sm btn-outline-secondary ml-2" id="btn-refresh" title="Refresh Data">
          <i class="fa fa-refresh"></i>
        </button>
      </div>
    </div>
  </div>
</section>

<style>
  .dashboard-grid-row {
    display: flex;
    flex-wrap: wrap;
  }

  .dashboard-grid-row > [class*='col-'] {
    display: flex;
    flex-direction: column;
    margin-bottom: 1rem;
  }

  .dashboard-grid-row .small-box,
  .dashboard-grid-row .card {
    height: 100%;
    margin-bottom: 0;
  }

  .dashboard-grid-row .small-box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .dashboard-grid-row .card {
    display: flex;
    flex-direction: column;
  }

  .dashboard-grid-row .card .card-body {
    flex: 1 1 auto;
  }

  .dashboard-chart-body {
    position: relative;
    min-height: 300px;
  }

  .dashboard-chart-body canvas {
    width: 100% !important;
    height: 100% !important;
  }

  .dashboard-side-column {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .dashboard-fill-card {
    flex: 1 1 auto;
    min-height: 280px;
  }

  .dashboard-fill-card .card-body {
    overflow: auto;
  }

  @media (max-width: 991.98px) {
    .dashboard-side-column {
      gap: 0;
    }

    .dashboard-fill-card {
      min-height: 0;
    }
  }
</style>

<section class="content">
  <div class="container-fluid">

    <!-- ====== STAT CARDS ====== -->
    <div class="row dashboard-grid-row">
      <div class="col-lg-3 col-6">
        <div class="small-box bg-danger">
          <div class="inner">
            <h3 id="stat-pegawai"><?php echo $stat['total_pegawai']; ?></h3>
            <p>Pegawai Aktif</p>
          </div>
          <div class="icon"><i class="fa fa-users"></i></div>
          <a href="<?php echo site_url('master/pegawai'); ?>" class="small-box-footer">Lihat Detail <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div>

      <div class="col-lg-3 col-6">
        <div class="small-box bg-gradient-danger">
          <div class="inner">
            <h3 id="stat-payroll"><?php echo $stat['payroll']['total']; ?> <small style="font-size:14px;">pegawai</small></h3>
            <p>Payroll Periode Ini</p>
          </div>
          <div class="icon"><i class="fa fa-calculator"></i></div>
          <a href="<?php echo site_url('transaksi/payroll'); ?>" class="small-box-footer">Ke Payroll <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div>

      <div class="col-lg-3 col-6">
        <div class="small-box <?php echo $stat['batch_pending'] > 0 ? 'bg-warning' : 'bg-success'; ?>">
          <div class="inner">
            <h3 id="stat-batch"><?php echo $stat['batch_pending']; ?></h3>
            <p>Batch Absensi Pending</p>
          </div>
          <div class="icon"><i class="fa fa-calendar-check-o"></i></div>
          <a href="<?php echo site_url('transaksi/absensi/import'); ?>" class="small-box-footer">Ke Import <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div>

      <div class="col-lg-3 col-6">
        <div class="small-box bg-info">
          <div class="inner">
            <h3 id="stat-neto"><?php echo rupiah($stat['payroll']['total_neto']); ?></h3>
            <p>Total Neto Periode Ini</p>
          </div>
          <div class="icon"><i class="fa fa-money"></i></div>
          <a href="<?php echo site_url('output/laporan/payroll'); ?>" class="small-box-footer">Lihat Laporan <i class="fa fa-arrow-circle-right"></i></a>
        </div>
      </div>
    </div>
    <!-- /STAT CARDS -->

    <!-- ====== CHARTS ROW ====== -->
    <div class="row dashboard-grid-row">
      <!-- Grafik Tren Payroll -->
      <div class="col-lg-8">
        <div class="card card-danger card-outline">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-line-chart mr-1"></i> Tren Total Neto Payroll</h3>
            <div class="card-tools">
              <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fa fa-minus"></i></button>
            </div>
          </div>
          <div class="card-body dashboard-chart-body">
            <canvas id="chartPayrollTren"></canvas>
          </div>
        </div>
      </div>

      <!-- Grafik Pegawai per Divisi -->
      <div class="col-lg-4">
        <div class="card card-danger card-outline">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-pie-chart mr-1"></i> Pegawai per Divisi</h3>
            <div class="card-tools">
              <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fa fa-minus"></i></button>
            </div>
          </div>
          <div class="card-body dashboard-chart-body">
            <canvas id="chartDivisi"></canvas>
          </div>
        </div>
      </div>
    </div>
    <!-- /CHARTS ROW -->

    <!-- ====== BOTTOM ROW ====== -->
    <div class="row dashboard-grid-row">

      <!-- Batch Import Terbaru -->
      <div class="col-lg-7">
        <div class="card card-danger card-outline">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-upload mr-1"></i> Batch Import Absensi Terbaru</h3>
          </div>
          <div class="card-body p-0">
            <table class="table table-sm table-striped mb-0">
              <thead class="bg-light">
                <tr>
                  <th>File</th>
                  <th class="text-center">Total</th>
                  <th class="text-center">Sukses</th>
                  <th class="text-center">Gagal</th>
                  <th class="text-center">Status</th>
                  <th>Waktu</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($batch_terbaru)): ?>
                  <tr><td colspan="6" class="text-center text-muted py-3">Belum ada import.</td></tr>
                <?php else: ?>
                  <?php foreach ($batch_terbaru as $b): ?>
                    <tr>
                      <td class="text-truncate" style="max-width:150px;" title="<?php echo htmlspecialchars($b->nama_file); ?>">
                        <?php echo htmlspecialchars($b->nama_file); ?>
                      </td>
                      <td class="text-center"><?php echo $b->total_baris; ?></td>
                      <td class="text-center text-success font-weight-bold"><?php echo $b->berhasil; ?></td>
                      <td class="text-center <?php echo $b->gagal > 0 ? 'text-danger font-weight-bold' : ''; ?>"><?php echo $b->gagal; ?></td>
                      <td class="text-center">
                        <?php
                          $badge = ['SUCCESS'=>'success','PARTIAL'=>'warning','FAILED'=>'danger','DELETED'=>'secondary'];
                          $b_status = strtoupper($b->status);
                        ?>
                        <span class="badge badge-<?php echo $badge[$b_status] ?? 'secondary'; ?>"><?php echo $b_status; ?></span>
                      </td>
                      <td><small><?php echo date('d/m H:i', strtotime($b->created_at)); ?></small></td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
          <div class="card-footer text-right py-2">
            <a href="<?php echo site_url('transaksi/absensi/import'); ?>" class="btn btn-sm btn-outline-danger">
              <i class="fa fa-arrow-right mr-1"></i> Ke Halaman Import
            </a>
          </div>
        </div>
      </div>

      <!-- Aktivitas Terbaru + Quick Actions -->
      <div class="col-lg-5 dashboard-side-column">
        <!-- Quick Actions -->
        <div class="card card-danger card-outline">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-bolt mr-1"></i> Quick Actions</h3>
          </div>
          <div class="card-body py-2">
            <div class="row">
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('transaksi/absensi/import'); ?>" class="btn btn-block btn-outline-danger btn-sm">
                  <i class="fa fa-upload mr-1"></i> Import Absensi
                </a>
              </div>
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('transaksi/lembur'); ?>" class="btn btn-block btn-outline-warning btn-sm">
                  <i class="fa fa-clock-o mr-1"></i> Input Lembur
                </a>
              </div>
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('transaksi/payroll'); ?>" class="btn btn-block btn-danger btn-sm">
                  <i class="fa fa-calculator mr-1"></i> Proses Payroll
                </a>
              </div>
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('output/slip_gaji'); ?>" class="btn btn-block btn-outline-dark btn-sm">
                  <i class="fa fa-file-pdf-o mr-1"></i> Arsip Slip Gaji
                </a>
              </div>
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('output/laporan'); ?>" class="btn btn-block btn-outline-info btn-sm">
                  <i class="fa fa-bar-chart mr-1"></i> Lihat Laporan
                </a>
              </div>
              <div class="col-6 mb-2">
                <a href="<?php echo site_url('master/pegawai'); ?>" class="btn btn-block btn-outline-secondary btn-sm">
                  <i class="fa fa-user-plus mr-1"></i> Tambah Pegawai
                </a>
              </div>
            </div>
          </div>
        </div>

        <!-- Aktivitas Terbaru -->
        <div class="card card-danger card-outline dashboard-fill-card">
          <div class="card-header">
            <h3 class="card-title"><i class="fa fa-history mr-1"></i> Aktivitas Terbaru</h3>
          </div>
          <div class="card-body p-0">
            <ul class="list-group list-group-flush">
              <?php if (empty($aktivitas)): ?>
                <li class="list-group-item text-muted text-center">Belum ada aktivitas.</li>
              <?php else: ?>
                <?php foreach ($aktivitas as $a): ?>
                  <li class="list-group-item py-2 px-3">
                    <span class="badge badge-<?php echo $a->tipe === 'PAYROLL' ? 'danger' : 'info'; ?> mr-1"><?php echo $a->tipe; ?></span>
                    <small><?php echo htmlspecialchars($a->keterangan); ?></small>
                    <div class="text-muted" style="font-size:11px;"><?php echo date('d M Y H:i', strtotime($a->waktu)); ?></div>
                  </li>
                <?php endforeach; ?>
              <?php endif; ?>
            </ul>
          </div>
        </div>
      </div>

    </div>
    <!-- /BOTTOM ROW -->

  </div>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script>
(function () {
  // ---- DATA dari PHP ----
  var divisiLabels = <?php echo json_encode($divisi_chart['labels']); ?>;
  var divisiValues = <?php echo json_encode($divisi_chart['values']); ?>;
  var trenLabels   = <?php echo json_encode($payroll_chart['labels']); ?>;
  var trenNeto     = <?php echo json_encode($payroll_chart['neto']); ?>;
  var trenPegawai  = <?php echo json_encode($payroll_chart['pegawai']); ?>;

  // Warna palet merah/abu
  var palette = ['#c0392b','#e74c3c','#e57373','#ef9a9a','#ffcdd2','#b71c1c','#d32f2f'];

  // ---- Grafik Tren Payroll ----
  var ctxTren = document.getElementById('chartPayrollTren').getContext('2d');
  new Chart(ctxTren, {
    type: 'bar',
    data: {
      labels: trenLabels,
      datasets: [
        {
          label: 'Total Neto (Rp)',
          data: trenNeto,
          backgroundColor: 'rgba(192,57,43,0.7)',
          borderColor: '#c0392b',
          borderWidth: 1,
          yAxisID: 'y',
          order: 2,
        },
        {
          label: 'Jml Pegawai',
          data: trenPegawai,
          type: 'line',
          borderColor: '#333',
          backgroundColor: 'transparent',
          borderWidth: 2,
          pointRadius: 4,
          yAxisID: 'y1',
          order: 1,
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { mode: 'index', intersect: false },
      plugins: {
        legend: { position: 'top' },
        tooltip: {
          callbacks: {
            label: function(ctx) {
              if (ctx.datasetIndex === 0) {
                return ' Neto: Rp ' + ctx.parsed.y.toLocaleString('id-ID');
              }
              return ' Pegawai: ' + ctx.parsed.y;
            }
          }
        }
      },
      scales: {
        y:  { type: 'linear', position: 'left',  ticks: { callback: v => 'Rp ' + (v/1000000).toFixed(1) + 'jt' } },
        y1: { type: 'linear', position: 'right', grid: { drawOnChartArea: false }, ticks: { stepSize: 1 } }
      }
    }
  });

  // ---- Grafik Donut Divisi ----
  var ctxDiv = document.getElementById('chartDivisi').getContext('2d');
  new Chart(ctxDiv, {
    type: 'doughnut',
    data: {
      labels: divisiLabels,
      datasets: [{
        data: divisiValues,
        backgroundColor: palette,
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { position: 'bottom', labels: { font: { size: 11 } } },
        tooltip: {
          callbacks: {
            label: function(ctx) {
              return ' ' + ctx.label + ': ' + ctx.parsed + ' pegawai';
            }
          }
        }
      }
    }
  });

  // ---- Auto-refresh stat cards setiap 60 detik ----
  function refreshStats() {
    fetch('<?php echo site_url('dashboard/ajax_stat'); ?>', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: '<?php echo $this->security->get_csrf_token_name(); ?>=' + encodeURIComponent(
        document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*<?php echo $this->config->item('csrf_cookie_name'); ?>\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')
      )
    })
    .then(r => r.json())
    .then(function(res) {
      if (!res.success) return;
      var d = res.data;
      var el = function(id) { return document.getElementById(id); };
      if (el('stat-pegawai')) el('stat-pegawai').textContent = d.total_pegawai;
      if (el('stat-payroll')) el('stat-payroll').innerHTML = d.payroll.total + ' <small style="font-size:14px;">pegawai</small>';
      if (el('stat-batch'))   el('stat-batch').textContent  = d.batch_pending;
      if (el('stat-neto'))    el('stat-neto').textContent   = 'Rp ' + parseFloat(d.payroll.total_neto).toLocaleString('id-ID', {minimumFractionDigits:0});
      el('last-refresh').textContent = new Date().toLocaleTimeString('id-ID');
    })
    .catch(function() {});
  }

  document.getElementById('btn-refresh').addEventListener('click', refreshStats);
  setInterval(refreshStats, 60000);
})();
</script>

