<?php
// GET /api/menu — dynamic menu based on authenticated user's role permissions

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

$authPayload = $GLOBALS['auth_user'];
$db          = getDB();

$stmt = $db->prepare("
    SELECT p.name
    FROM role_permissions rp
    JOIN roles r      ON r.id = rp.role_id
    JOIN permissions p ON p.id = rp.permission_id
    WHERE r.name = ?
");
$stmt->bind_param("s", $authPayload['role']);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$db->close();

$permissions = array_column($rows, 'name');
$menu        = [];

if (in_array('DASHBOARD_VIEW', $permissions)) {
    $menu[] = ['name' => 'Dashboard', 'path' => 'Dashboard', 'icon' => 'home'];
}

$userChildren = [];
if (in_array('USER_CREATE', $permissions)) $userChildren[] = ['name' => 'Add User',   'path' => 'AddUser'];
if (!empty(array_intersect(['USER_CREATE','USER_EDIT','USER_DELETE'], $permissions))) {
    $userChildren[] = ['name' => 'User List', 'path' => 'UserList'];
}
if (!empty($userChildren)) {
    $menu[] = ['name' => 'Users', 'path' => 'Users', 'icon' => 'users', 'children' => array_values($userChildren)];
}

if (in_array('READING_VIEW', $permissions)) {
    $menu[] = ['name' => 'Readings', 'path' => 'Readings', 'icon' => 'file-text'];
}

if (in_array('REPORT_VIEW', $permissions)) {
    $menu[] = ['name' => 'Reports', 'path' => 'Reports', 'icon' => 'bar-chart'];
}

if (in_array('ROLE_MANAGE', $permissions)) {
    $menu[] = ['name' => 'Roles', 'path' => 'Roles', 'icon' => 'shield'];
}

$menu[] = ['name' => 'Profile', 'path' => 'Profile', 'icon' => 'user'];

sendSuccess(['data' => $menu]);
