<?php
// POST /api/check-device
 
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendError('Method not allowed', 405);
}
 
$input     = json_decode(file_get_contents('php://input'), true);
$device_id = trim($input['device_id'] ?? '');
 
if (!$device_id) {
    sendError('device_id is required');
}
 
$db   = getDB();
$stmt = $db->prepare("
    SELECT d.user_id, d.token, u.name, u.mobile, u.employee_id, u.role
    FROM devices d
    LEFT JOIN users u ON u.id = d.user_id
    WHERE d.device_id = ?
");
$stmt->bind_param("s", $device_id);
$stmt->execute();
$device = $stmt->get_result()->fetch_assoc();
$stmt->close();
 
if (!$device || empty($device['user_id'])) {
    $db->close();
    sendSuccess([
        'registered'  => false,
        'token'       => null,
        'message'     => 'Device not registered'
    ]);
}
 
// Fetch permissions for this role
$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", $device['role']);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$db->close();
 
$permissions = array_column($rows, 'name');
 
// Build dynamic menu from permissions
$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([
    'registered'  => true,
    'token'       => $device['token'],
    'message'     => 'Device already registered',
    'user'        => [
        'name'        => $device['name'],
        'mobile'      => $device['mobile'],
        'employee_id' => $device['employee_id'],
        'role'        => $device['role'],
        'device_id'   => $device_id,
    ],
    'permissions' => $permissions,
    'menu'        => $menu,
]);