<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'layouts/dbconn.php';

echo "Debugging Audiologist Permissions...\n";

// 1. Get Role ID
$role_name = 'Audiologist';
$stmt = $conn->prepare("SELECT role_id, role_name FROM user_roles WHERE role_name = ?");
$stmt->bind_param("s", $role_name);
$stmt->execute();
$role = $stmt->get_result()->fetch_assoc();

if (!$role) {
    echo "Role '$role_name' not found in user_roles table.\n";
    // List all roles
    echo "Available roles:\n";
    $result = $conn->query("SELECT * FROM user_roles");
    while ($r = $result->fetch_assoc()) {
        echo " - " . $r['role_name'] . " (ID: " . $r['role_id'] . ")\n";
    }
    exit;
}

$role_id = $role['role_id'];
echo "Role found: " . $role['role_name'] . " (ID: $role_id)\n";

// 2. Get Permissions
$sql = "SELECT rp.*, m.menu_name, m.menu_url, m.is_active 
        FROM role_permissions rp 
        LEFT JOIN menu_items m ON rp.menu_id = m.menu_id 
        WHERE rp.role_id = $role_id";

$result = $conn->query($sql);

if ($result->num_rows === 0) {
    echo "No permissions found for Role ID $role_id in role_permissions table.\n";
} else {
    echo "Found " . $result->num_rows . " permission entries:\n";
    while ($row = $result->fetch_assoc()) {
        echo " - Menu ID: " . $row['menu_id'];
        echo " | Name: " . ($row['menu_name'] ?? 'NULL');
        echo " | URL: " . ($row['menu_url'] ?? 'NULL');
        echo " | Active: " . ($row['is_active'] ?? 'NULL');
        echo " | View: " . $row['can_view'];
        echo " | Edit: " . $row['can_edit'];
        echo "\n";
    }
}

// 3. Check menu_items for likely audiologist pages
echo "\nChecking for Audiologist-related menu items:\n";
$audit_sql = "SELECT * FROM menu_items WHERE menu_name LIKE '%Audio%' OR menu_url LIKE '%audiometry%'";
$audit_result = $conn->query($audit_sql);
while ($row = $audit_result->fetch_assoc()) {
    echo " - Item: " . $row['menu_name'] . " (" . $row['menu_url'] . ") ID: " . $row['menu_id'] . "\n";
}
?>