<?php
/**
 * Permission Helper Functions
 * Include this in config.php or admin-security.php to make it globally available
 */

if (!function_exists('has_permission')) {
    function has_permission($permission_slug, $user_id = null)
    {
        global $con;

        // 1. Identify User
        if ($user_id === null) {
            if (!isset($_SESSION['aid'])) {
                return false;
            }
            $user_id = $_SESSION['aid'];
        }

        // 2. Superuser Bypass (The user 'admin2' is the system administrator and always has access)
        if (isset($_SESSION['username']) && $_SESSION['username'] === 'admin2' && $_SESSION['aid'] == $user_id) {
            return true;
        }

        // 3. Fallback: Check DB if session info is missing or user_id is different
        // If we have session role and it matches the requested user_id, use it.
        if (isset($_SESSION['role']) && isset($_SESSION['aid']) && $_SESSION['aid'] == $user_id) {
            $role = $_SESSION['role'];
            $username = $_SESSION['username'] ?? '';
        } else {
            $query = mysqli_query($con, "SELECT username, role FROM users WHERE id='$user_id'");
            if (!$query || mysqli_num_rows($query) == 0) {
                return false;
            }
            $row = mysqli_fetch_array($query);
            $username = $row['username'];
            $role = $row['role'];
        }

        // Final superuser check via DB if session check didn't catch it
        if ($username === 'admin2') {
            return true;
        }

        // 4. Role-Based Check in role_permissions table
        $slug_esc = mysqli_real_escape_string($con, $permission_slug);
        $role_esc = mysqli_real_escape_string($con, $role);

        $perm_query = mysqli_query($con, "SELECT id FROM role_permissions WHERE role='$role_esc' AND permission_slug='$slug_esc'");

        if ($perm_query && mysqli_num_rows($perm_query) > 0) {
            return true;
        }

        return false;
    }
}
?>
