<?php
// ==== DELETE ====
// ==== DELETE ====
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);

    // cek apakah produk dipakai di transaksi
    $cek = $conn->query("SELECT COUNT(*) AS jml FROM tabel_transaksi_detail WHERE produk_id=$id");
    $row = $cek->fetch_assoc();

    if ($row['jml'] > 0) {
        echo "<script>alert('Produk tidak bisa dihapus karena sudah dipakai di transaksi!'); 
              location.href='index.php?page=produk';</script>";
    } else {
        $conn->query("DELETE FROM tabel_produk WHERE id=$id");
        echo "<script>alert('Produk berhasil dihapus!'); 
              location.href='index.php?page=produk';</script>";
    }
}

// ==== SEARCH + PAGINATION ====
// ambil limit dari dropdown (default 5)
$limit  = isset($_GET['limit']) ? (int)$_GET['limit'] : 25;
$page   = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
$start  = ($page - 1) * $limit;

$search    = isset($_GET['search']) ? trim($_GET['search']) : '';
$kategoriF = isset($_GET['kategori']) ? trim($_GET['kategori']) : '';

$where = [];
if ($search) {
    $where[] = "(kode_barang LIKE '%$search%' OR nama_produk LIKE '%$search%' OR kategori LIKE '%$search%')";
}
if ($kategoriF) {
    $where[] = "kategori='$kategoriF'";
}
$whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";

// Hitung total data
$totalResult = $conn->query("SELECT COUNT(*) AS total FROM tabel_produk $whereSql");
$totalData   = $totalResult->fetch_assoc()['total'];
$totalPages  = ceil($totalData / $limit);

// Ambil data produk
$produk = $conn->query("SELECT * FROM tabel_produk $whereSql ORDER BY id DESC LIMIT $start, $limit");
?>

<h2 class="mb-4">Data Produk</h2>

<div class="d-flex justify-content-between mb-2">
    <a href="index.php?page=produk_tambah" class="btn btn-primary">
        <i class="fas fa-plus-circle"></i> Tambah Produk
    </a>


<!-- Form Filter -->
<form method="get" class="d-flex">
    <input type="hidden" name="page" value="produk">

    <input type="text" name="search" class="form-control me-2" 
           placeholder="Cari produk..." value="<?= htmlspecialchars($search) ?>">

    <!-- Tombol Reset Search -->
    <a href="index.php?page=produk" class="btn btn-outline-danger me-2">
        <i class="fas fa-sync-alt"></i> Reset
    </a>

    <!-- Filter Kategori -->
    <select name="kategori" class="form-control me-2">
        <option value="">-- Semua Kategori --</option>
        <?php
        $resKategori = $conn->query("SELECT DISTINCT kategori FROM tabel_produk ORDER BY kategori");
        while ($kat = $resKategori->fetch_assoc()):
        ?>
            <option value="<?= htmlspecialchars($kat['kategori']) ?>" 
                <?= ($kategoriF==$kat['kategori']) ? 'selected' : '' ?>>
                <?= htmlspecialchars($kat['kategori']) ?>
            </option>
        <?php endwhile; ?>
    </select>

    <!-- Limit per halaman -->
    <select name="limit" class="form-control me-2">
        <?php foreach ([25,50,100] as $opt): ?>
            <option value="<?= $opt ?>" <?= ($limit==$opt)?'selected':'' ?>>
                <?= $opt ?>-data
            </option>
        <?php endforeach; ?>
    </select>

    <button type="submit" class="btn btn-secondary">
        <i class="fas fa-search"></i>
    </button>
</form>
</div>

<table class="table table-bordered table-striped table-sm" style="font-size: 14px;">
    <thead class="table-dark">
        <tr>
            <th>No</th>
            <th>Kode Barang</th>
            <th>Nama Produk</th>
            <th>Stok</th>
            <th>Harga Beli</th>
            <th>Harga Eceran</th>
            <th>Kategori</th>
            <th width="100">Aksi</th>
        </tr>
    </thead>
    <tbody>
    <?php if ($produk->num_rows > 0): ?>
        <?php $no=$start+1; while($row = $produk->fetch_assoc()): ?>
        <tr>
            <td><?= $no++ ?></td>
            <td><?= $row['kode_barang'] ?></td>
            <td><?= $row['nama_produk'] ?></td>
            <td><?= $row['stok'] ?></td>
            <td>Rp <?= number_format($row['harga_beli'],0,',','.') ?></td>
            <td>Rp <?= number_format($row['harga_eceran'],0,',','.') ?></td>
            <td><?= $row['kategori'] ?></td>
            <td class="text-center">
                <a href="index.php?page=produk_edit&id=<?= $row['id'] ?>" 
                   class="btn btn-sm btn-warning" title="Edit">
                   <i class="fas fa-pencil-square"></i>
                </a>
                <a href="index.php?page=produk&hapus=<?= $row['id'] ?>" 
                   class="btn btn-sm btn-danger" 
                   onclick="return confirm('Yakin hapus produk ini?')" title="Hapus">
                   <i class="fas fa-trash"></i>
                </a>
            </td>
        </tr>
        <?php endwhile; ?>
    <?php else: ?>
        <tr><td colspan="8" class="text-center">Data tidak ditemukan</td></tr>
    <?php endif; ?>
    </tbody>
</table>

<!-- Pagination -->
<nav>
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
            <li class="page-item">
                <a class="page-link" href="index.php?page=produk&page_num=<?= $page-1 ?>&search=<?= urlencode($search) ?>&kategori=<?= urlencode($kategoriF) ?>&limit=<?= $limit ?>">Sebelumnya</a>
            </li>
        <?php endif; ?>
        <?php for ($i=1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= ($i==$page) ? 'active' : '' ?>">
                <a class="page-link" href="index.php?page=produk&page_num=<?= $i ?>&search=<?= urlencode($search) ?>&kategori=<?= urlencode($kategoriF) ?>&limit=<?= $limit ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <?php if ($page < $totalPages): ?>
            <li class="page-item">
                <a class="page-link" href="index.php?page=produk&page_num=<?= $page+1 ?>&search=<?= urlencode($search) ?>&kategori=<?= urlencode($kategoriF) ?>&limit=<?= $limit ?>">Berikutnya</a>
            </li>
        <?php endif; ?>
    </ul>
</nav>
