<?php
include 'config/koneksi.php';
include 'includes/header.php';
include 'includes/navbar.php';

// Filter Kategori
$kategori_filter = isset($_GET['kategori']) ? $_GET['kategori'] : '';

// Query Data
$sql = "SELECT * FROM potensi_desa";
if ($kategori_filter) {
    // Sanitasi input sederhana
    $kategori_safe = mysqli_real_escape_string($koneksi, $kategori_filter);
    $sql .= " WHERE kategori = '$kategori_safe'";
}
$sql .= " ORDER BY created_at DESC";

$query = mysqli_query($koneksi, $sql);
?>

<div class="page-header">
    <div class="container">
        <h1>Potensi Desa</h1>
    </div>
</div>

<div class="container main-content">
    
    <!-- Filter Helper -->
    <div class="filter-bar text-center">
        <a href="potensi.php" class="btn-filter <?= ($kategori_filter == '') ? 'active' : ''; ?>">Semua</a>
        <a href="potensi.php?kategori=Wisata" class="btn-filter <?= ($kategori_filter == 'Wisata') ? 'active' : ''; ?>">Wisata</a>
        <a href="potensi.php?kategori=Pertanian" class="btn-filter <?= ($kategori_filter == 'Pertanian') ? 'active' : ''; ?>">Pertanian</a>
        <a href="potensi.php?kategori=UMKM" class="btn-filter <?= ($kategori_filter == 'UMKM') ? 'active' : ''; ?>">UMKM</a>
        <a href="potensi.php?kategori=Lainnya" class="btn-filter <?= ($kategori_filter == 'Lainnya') ? 'active' : ''; ?>">Lainnya</a>
    </div>

    <?php if (mysqli_num_rows($query) > 0): ?>
        <div class="potensi-grid">
            <?php while ($row = mysqli_fetch_assoc($query)): ?>
                <div class="card-potensi">
                    <div class="potensi-img">
                        <?php 
                        $img_path = "uploads/potensi/" . $row['gambar'];
                        $img_tampil = (file_exists($img_path) && $row['gambar'] != '') ? $img_path : "https://via.placeholder.com/600x400?text=Potensi+Desa";
                        ?>
                        <img src="<?= $img_tampil; ?>" alt="<?= htmlspecialchars($row['judul']); ?>">
                        <span class="badge-kategori"><?= htmlspecialchars($row['kategori']); ?></span>
                    </div>
                    <div class="potensi-info">
                        <h3><?= htmlspecialchars($row['judul']); ?></h3>
                        <p><?= htmlspecialchars(substr($row['deskripsi'], 0, 100)) . '...'; ?></p>
                        <a href="detail_potensi.php?id=<?= $row['id_potensi']; ?>" class="read-more">Lihat Detail <i class="fas fa-arrow-right"></i></a>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <div class="alert-info text-center">
            <p>Belum ada data potensi untuk kategori ini.</p>
        </div>
    <?php endif; ?>

</div>

<?php
include 'includes/footer.php';
?>
