<?php

$batas       = 10;
$halaman     = isset($_GET['halaman']) ? (int)$_GET['halaman'] : 1;
$halaman_awal = ($halaman > 1) ? ($halaman * $batas) - $batas : 0;
$previous    = $halaman - 1;
$next        = $halaman + 1;

$where = '';
if ((isset($_GET['go']) || isset($_POST['go'])) && !empty($_GET['cari'] ?? $_POST['cari'] ?? '')) {
  $cari = mysqli_real_escape_string($koneksi, $_GET['cari'] ?? $_POST['cari']);
  $where = " WHERE nm_barang LIKE '%$cari%' OR kdbarang LIKE '%$cari%'";
}

$count_query = "SELECT COUNT(*) as total FROM tb_barang$where";
$count_result = mysqli_query($koneksi, $count_query);
$count_row = mysqli_fetch_assoc($count_result);
$jumlah_data = $count_row['total'];
$total_halaman = ceil($jumlah_data / $batas);

$q = mysqli_query($koneksi, "SELECT p.*, k.kategori as nama_kategori FROM tb_barang p LEFT JOIN tb_kat k ON p.kategori = k.id $where ORDER BY p.id DESC LIMIT $halaman_awal, $batas");

// Buffer all rows first so modals can be rendered outside the table
$rows = [];
while ($r = mysqli_fetch_assoc($q)) { $rows[] = $r; }

foreach ($rows as $pro): ?>
<tr>
  <td><?= $i++; ?></td>
  <td><code style="background:var(--surface-2);padding:3px 8px;border-radius:6px;font-size:0.8rem;color:var(--primary);"><?= htmlspecialchars($pro['kdbarang']); ?></code></td>
  <td><strong><?= htmlspecialchars($pro['nm_barang']); ?></strong></td>
  <td><?= htmlspecialchars($pro['nama_kategori'] ?? $pro['kategori']); ?></td>
  <td>
    <span style="font-weight:600;color:<?= ($pro['stok'] == 0) ? 'var(--danger-text)' : 'var(--success-text)'; ?>;">
      <?= $pro['stok']; ?>
    </span>
  </td>
  <td>
    <?php if ($pro['stok'] == 0): ?>
      <span class="badge badge-habis"><i class="fas fa-times-circle" style="font-size:9px;"></i> Habis</span>
    <?php else: ?>
      <span class="badge badge-ada"><i class="fas fa-check-circle" style="font-size:9px;"></i> Ada</span>
    <?php endif; ?>
  </td>
  <td>Rp <?= number_format($pro['harga_beli'], 0, ',', '.'); ?></td>
  <td>Rp <?= number_format($pro['harga_jual'], 0, ',', '.'); ?></td>
  <td><?= htmlspecialchars($pro['satuan'] ?? ''); ?></td>
  <td>
    <div class="action-buttons">
      <button type="button" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#hapus-prd<?= $pro['id'] ?>" title="Hapus">
        <i class="fas fa-trash-alt"></i>
      </button>
      <button type="button" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#edit-prd<?= $pro['id'] ?>" title="Edit">
        <i class="fas fa-edit"></i>
      </button>
    </div>
  </td>
</tr>
<?php endforeach; ?>

<?php
// Render all modals OUTSIDE the table
foreach ($rows as $pro): ?>

<!-- Modal Hapus Barang -->
<form action="" method="POST" id="form-hapus-prd<?= $pro['id'] ?>">
  <input type="hidden" name="id" value="<?= $pro['id'] ?>">
  <input type="hidden" name="hapus" value="1">
  <div class="modal fade" id="hapus-prd<?= $pro['id'] ?>" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title"><i class="fas fa-exclamation-triangle" style="color:#DC2626;margin-right:8px;"></i>Hapus Barang</h5>
          <button type="button" class="close" data-bs-dismiss="modal"><span>&times;</span></button>
        </div>
        <div class="modal-body">
          <p style="color:var(--text-secondary);margin-bottom:14px;">Apakah Anda yakin ingin menghapus barang berikut?</p>
          <div class="modal-detail-row">
            <div class="modal-detail-label">Kode</div>
            <div class="modal-detail-value"><?= htmlspecialchars($pro['kdbarang']) ?></div>
          </div>
          <div class="modal-detail-row">
            <div class="modal-detail-label">Nama Barang</div>
            <div class="modal-detail-value"><?= htmlspecialchars($pro['nm_barang']) ?></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
          <button type="submit" class="btn btn-danger" form="form-hapus-prd<?= $pro['id'] ?>"><i class="fas fa-trash-alt"></i> Hapus</button>
        </div>
      </div>
    </div>
  </div>
</form>

<!-- Modal Edit Barang -->
<div class="modal fade" id="edit-prd<?= $pro['id'] ?>" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>Edit Barang</h5>
        <button type="button" class="close" data-bs-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <form action="" method="POST" enctype="multipart/form-data" id="form-edit-prd<?= $pro['id'] ?>">
          <input type="hidden" name="id" value="<?= $pro['id'] ?>">
          <div class="form-group">
            <label>Kode Barang</label>
            <input type="text" class="form-control" name="kdbarang" value="<?= htmlspecialchars($pro['kdbarang']) ?>" readonly>
          </div>
          <div class="form-group">
            <label>Nama Barang</label>
            <input type="text" class="form-control" name="nm_barang" value="<?= htmlspecialchars($pro['nm_barang']) ?>">
          </div>
          <div class="form-group">
            <label>Kategori</label>
            <select name="kategori" class="form-control">
              <?php
                $qkat = mysqli_query($koneksi, "SELECT * FROM tb_kat");
                foreach ($qkat as $kat):
              ?>
              <option value="<?= $kat['id'] ?>" <?= ($kat['id'] == $pro['kategori']) ? 'selected' : '' ?>><?= htmlspecialchars($kat['kategori']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Stok</label>
            <input type="text" class="form-control" name="stok" value="<?= $pro['stok'] ?>">
          </div>
          <div class="form-group">
            <label>Harga Beli</label>
            <input type="text" class="form-control" name="harga_beli" value="<?= $pro['harga_beli'] ?>">
          </div>
          <div class="form-group">
            <label>Harga Jual</label>
            <input type="text" class="form-control" name="harga_jual" value="<?= $pro['harga_jual'] ?>">
          </div>
          <div class="form-group">
            <label>Satuan</label>
            <input type="text" class="form-control" name="satuan" value="<?= htmlspecialchars($pro['satuan'] ?? '') ?>">
          </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" form="form-edit-prd<?= $pro['id'] ?>" name="edit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
      </div>
        </form>
    </div>
  </div>
</div>

<?php endforeach; ?>

