100) { $error = 'Indique um nome (máx. 100 caracteres).'; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > 190) { $error = 'Email inválido.'; } elseif (!in_array($role, $roles, true)) { $error = 'Perfil inválido.'; } elseif (mb_strlen($phone) > 20) { $error = 'Telefone demasiado longo (máx. 20 caracteres).'; } else { $other = db_get_user_by_email($pdo, $email); if ($other && (int) $other['id'] !== (int) $target['id']) { $error = 'Já existe outro utilizador com esse email.'; } } if ($error === '') { $fields = ['name', 'email', 'phone', 'role', 'is_active']; $before = array_intersect_key($target, array_flip($fields)); $new = ['name' => $name, 'email' => $email, 'phone' => $phone !== '' ? $phone : null, 'role' => $role, 'is_active' => $active]; $pdo->prepare('UPDATE users SET name=?, email=?, phone=?, role=?, is_active=? WHERE id=?') ->execute([$name, $email, $new['phone'], $role, $active, (int) $target['id']]); $changes = platform_audit_diff($before, $new); if ($changes) { audit('user.update', [ 'target_type' => 'user', 'target_id' => (int) $target['id'], 'target_label' => $name, 'changes' => $changes, ]); } $saved = true; $target = db_get_user($pdo, (int) $target['id']) ?? $target; } else { // Mantém o que foi escrito para o formulário não perder as alterações. $target = array_merge($target, ['name' => $name, 'email' => $email, 'phone' => $phone, 'role' => $role, 'is_active' => $active]); } } $page_title = 'Editar utilizador'; include __DIR__ . '/../../includes/header.php'; ?>