<?php
include "../config/koneksi.php";

$current_module = $_GET['module'] ?? '';
$level_user     = $_SESSION['leveluser'] ?? '';

// Tentukan Query
if ($level_user === 'admin') {
    $query = "SELECT * FROM modul WHERE aktif='Y' ORDER BY urutan ASC";
} elseif ($level_user === 'user') {
    $query = "SELECT * FROM modul WHERE status='user' AND aktif='Y' ORDER BY urutan ASC";
} else {
    $query = "";
}

if (!empty($query)) {
    $hasil = mysqli_query($konek, $query);

    if ($hasil) {
        while ($m = mysqli_fetch_array($hasil)) {
            $link       = htmlspecialchars($m['link']);
            $nama_modul = htmlspecialchars($m['nama_modul']);
            
            // 1. Deteksi Active
            $is_active = (!empty($current_module) && strpos($link, "module={$current_module}") !== false) ? 'active' : '';

            // 2. Mapping Ikon Otomatis berdasarkan nama modul/link
            $icon = 'fa-folder'; // Ikon default
            $lower_name = strtolower($nama_modul);
            
            if (strpos($lower_name, 'user') !== false || strpos($lower_name, 'pengguna') !== false) {
                $icon = 'fa-users';
            } elseif (strpos($lower_name, 'kategori') !== false) {
                $icon = 'fa-tags';
            } elseif (strpos($lower_name, 'laporan') !== false || strpos($lower_name, 'report') !== false) {
                $icon = 'fa-file-alt';
            } elseif (strpos($lower_name, 'setting') !== false || strpos($lower_name, 'pengaturan') !== false) {
                $icon = 'fa-cog';
            } elseif (strpos($lower_name, 'produk') !== false || strpos($lower_name, 'barang') !== false) {
                $icon = 'fa-box';
            } elseif (strpos($lower_name, 'pesanan') !== false || strpos($lower_name, 'transaksi') !== false) {
                $icon = 'fa-shopping-cart';
            }

            // 3. Render HTML
            echo "<a href=\"{$link}\" class=\"adm-nav-item {$is_active}\">";
            echo "  <i class=\"fa {$icon} adm-nav-icon\"></i>";
            echo "  <span>{$nama_modul}</span>";
            echo "</a>";
        }
    }
}
?>