<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<h4 class="mb-4">Laporan Penjualan</h4>

<!-- Filter -->
<form method="get" action="<?= base_url('admin/report/sales') ?>" class="mb-4">
  <div class="row g-2 align-items-end">
    <div class="col-md-3">
      <label for="start_date" class="form-label">Tanggal Mulai</label>
      <input type="date" id="start_date" name="start_date" class="form-control" value="<?= esc($_GET['start_date'] ?? '') ?>">
    </div>
    <div class="col-md-3">
      <label for="end_date" class="form-label">Tanggal Akhir</label>
      <input type="date" id="end_date" name="end_date" class="form-control" value="<?= esc($_GET['end_date'] ?? '') ?>">
    </div>
    <div class="col-md-3">
      <label for="user_id" class="form-label">Pilih Kasir</label>
      <select name="user_id" id="user_id" class="form-select">
        <option value="">Semua Kasir</option>
        <?php foreach ($users as $user): ?>
          <option value="<?= $user['id'] ?>" <?= ($user['id'] == ($_GET['user_id'] ?? '')) ? 'selected' : '' ?>>
            <?= esc($user['username']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-3">
      <button type="submit" class="btn btn-primary w-100">
        <i class="bi bi-search"></i> Tampilkan
      </button>
    </div>
    <div class="col-md-3">
      <a href="<?= base_url('admin/report/sales') ?>" class="btn btn-secondary">Reset</a>
    </div>
  </div>
</form>

<!-- Tabel dan Hapus Massal -->
<form method="post" action="<?= base_url('admin/report/sales/delete') ?>" onsubmit="return confirm('Yakin ingin menghapus data yang dipilih?')">
  <?php if (session()->get('role') === 'superadmin'): ?>
    <div class="mb-3">
      <button type="submit" class="btn btn-danger btn-sm">
        <i class="fas fa-trash-alt"></i> Hapus Terpilih
      </button>
    </div>
  <?php endif; ?>

  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <?php if (session()->get('role') === 'superadmin'): ?>
          <th><input type="checkbox" id="checkAll"></th>
        <?php endif; ?>
        <th>Kode</th>
        <th>Tanggal</th>
        <th>Pelanggan</th>
        <th>Total</th>
        <th>Kasir</th>
        <th>Aksi</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($sales as $s): ?>
        <tr>
          <?php if (session()->get('role') === 'superadmin'): ?>
            <td><input type="checkbox" name="ids[]" value="<?= $s['id'] ?>"></td>
          <?php endif; ?>
          <td><?= esc($s['kode']) ?></td>
          <td><?= date('d-m-Y', strtotime($s['tanggal'])) ?></td>
          <td><?= esc($s['customer_name'] ?? '-') ?></td>
          <td>Rp <?= number_format($s['total_bayar']) ?></td>
          <td><?= esc($s['user_name'] ?? '-') ?></td>
          <td>
            <button class="btn btn-sm" style="background-color: #d0ebff; color: #084298;" onclick="showDetail(<?= $s['id'] ?>)">
              <i class="fas fa-eye"></i> Detail
            </button>

            <a href="<?= base_url('admin/report/sales/edit/' . $s['id']) ?>" class="btn btn-sm" style="background-color: #e7f5ff; color: #1c7ed6;">
              <i class="fas fa-edit"></i> Edit
            </a>

            <a href="<?= base_url('admin/sales/print/' . $s['id']) ?>" target="_blank" class="btn btn-sm" style="background-color: #d3f9d8; color: #2b8a3e;">
              <i class="fas fa-print"></i> Print
            </a>
          </td>
        </tr>
      <?php endforeach ?>
    </tbody>
  </table>
</form>

<!-- Pagination -->
<?php if (!empty($pager) && $pager['totalPages'] > 1): ?>
  <nav class="mt-4">
    <ul class="pagination justify-content-center">
      <?php
        $queryParams = $_GET;
        $current = $pager['currentPage'];
        $total   = $pager['totalPages'];

        function pageLink($page, $label, $disabled = false, $active = false, $queryParams = []) {
          $queryParams['page'] = $page;
          $url = current_url() . '?' . http_build_query($queryParams);
          $class = 'page-item';
          if ($disabled) $class .= ' disabled';
          if ($active) $class .= ' active';
          return "<li class=\"$class\"><a class=\"page-link\" href=\"$url\">$label</a></li>";
        }

        echo pageLink(1, 'First', $current === 1, false, $queryParams);
        echo pageLink($current - 1, 'Previous', $current === 1, false, $queryParams);

        for ($i = 1; $i <= $total; $i++) {
          if ($i === $current || abs($i - $current) <= 2 || $i === 1 || $i === $total) {
            echo pageLink($i, $i, false, $i === $current, $queryParams);
          } elseif ($i == 2 && $current > 4) {
            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
          } elseif ($i == $total - 1 && $current < $total - 3) {
            echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
          }
        }

        echo pageLink($current + 1, 'Next', $current === $total, false, $queryParams);
        echo pageLink($total, 'Last', $current === $total, false, $queryParams);
      ?>
    </ul>
  </nav>
<?php endif; ?>

<!-- Modal -->
<div class="modal fade" id="detailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Detail Transaksi</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
      </div>
      <div class="modal-body" id="modalBody">
        <p>Memuat data...</p>
      </div>
    </div>
  </div>
</div>

<!-- Script -->
<script>
function showDetail(saleId) {
  fetch('<?= base_url('admin/sales/detail/') ?>' + saleId)
    .then(res => res.text())
    .then(html => {
      document.getElementById('modalBody').innerHTML = html;
      new bootstrap.Modal(document.getElementById('detailModal')).show();
    })
    .catch(err => {
      document.getElementById('modalBody').innerHTML = '<div class="alert alert-danger">Gagal memuat detail.</div>';
    });
}

// Select all checkbox
document.addEventListener('DOMContentLoaded', function () {
  const checkAll = document.getElementById('checkAll');
  if (checkAll) {
    checkAll.addEventListener('change', function () {
      document.querySelectorAll('input[name="ids[]"]').forEach(cb => {
        cb.checked = checkAll.checked;
      });
    });
  }
});
</script>

<?= $this->endSection() ?>
