<?php
/**
 * includes/module_permission.php
 * Helper untuk menampilkan / memproteksi menu berdasarkan app_role_menu_permissions.
 */

if (!function_exists('mp_current_role')) {
    function mp_current_role() {
        if (isset($_SESSION['user']['role'])) return strtolower((string)$_SESSION['user']['role']);
        if (isset($_SESSION['role'])) return strtolower((string)$_SESSION['role']);
        if (isset($_SESSION['user_role'])) return strtolower((string)$_SESSION['user_role']);
        return 'viewer';
    }
}

if (!function_exists('modulesForRole')) {
    function modulesForRole($conn, $role = null) {
        $role = $role ?: mp_current_role();
        if (!$conn instanceof mysqli) return array();

        // Admin/superadmin tetap full akses.
        if (in_array($role, array('admin', 'superadmin'), true)) {
            $sql = "SELECT module_key, module_name, module_group, route_path, icon
                    FROM app_menu_modules
                    WHERE is_active=1
                    ORDER BY sort_order ASC, module_name ASC";
            $res = $conn->query($sql);
        } else {
            $stmt = $conn->prepare("SELECT m.module_key, m.module_name, m.module_group, m.route_path, m.icon
                    FROM app_menu_modules m
                    INNER JOIN app_role_menu_permissions p ON p.module_key=m.module_key
                    WHERE m.is_active=1 AND p.role_name=? AND p.can_view=1
                    ORDER BY m.sort_order ASC, m.module_name ASC");
            if (!$stmt) return array();
            $stmt->bind_param('s', $role);
            $stmt->execute();
            $res = $stmt->get_result();
        }

        $rows = array();
        if ($res) {
            while ($r = $res->fetch_assoc()) $rows[] = $r;
        }
        if (isset($stmt) && $stmt) $stmt->close();
        return $rows;
    }
}

if (!function_exists('userCanAccessModule')) {
    function userCanAccessModule($conn, $moduleKey, $role = null) {
        $role = $role ?: mp_current_role();
        if (in_array($role, array('admin', 'superadmin'), true)) return true;
        if (!$conn instanceof mysqli) return false;
        $stmt = $conn->prepare("SELECT 1
                FROM app_role_menu_permissions
                WHERE role_name=? AND module_key=? AND can_view=1
                LIMIT 1");
        if (!$stmt) return false;
        $stmt->bind_param('ss', $role, $moduleKey);
        $stmt->execute();
        $res = $stmt->get_result();
        $ok = $res && $res->num_rows > 0;
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('requireModuleAccess')) {
    function requireModuleAccess($conn, $moduleKey) {
        if (!userCanAccessModule($conn, $moduleKey)) {
            echo '<div class="p-6 rounded-2xl bg-red-50 border border-red-200 text-red-700 font-bold">Akses ditolak. Role Anda tidak memiliki izin membuka modul ini.</div>';
            return false;
        }
        return true;
    }
}
